<?php

namespace App\Http\Controllers\MedicalSetting;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Symptom;
use App\Models\SymptomClassification;
use Response;
use App\Imports\ImportSymptom;
use Session;
use Maatwebsite\Excel\Facades\Excel;

class SymptomsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:symptoms-list', ['only' => ['index']]);
    }

    public function index(Request $request)
    {
        $data = Symptom::select([
                    'symptoms.id',
                    'symptoms.symptoms_title',
                    'symptoms.code',
                    'symptoms.description',
                    'symptoms.type as type',
                    'symptoms.priority',
                    'symptoms.status',
                    'symptom_classifications.symptoms_type as symptoms_type',
                ])
        		->leftjoin('symptom_classifications', 'symptom_classifications.id', 'symptoms.type')
                ->orderBy('priority', 'ASC');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('symptoms.symptoms_title', 'like', '%'.$search_query.'%')
                    ->orWhere('symptoms.code', 'like', '%'.$search_query.'%')
                    ->orWhere('symptom_classifications.symptoms_type', 'like', '%'.$search_query.'%')
                    ->orWhere('symptoms.type', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

            return view('symptoms.table', compact('data'));
        }
        else
        {
            $data = $data->paginate(10);

            return view('symptoms.index', compact('data'));
        }
    }

    public function create()
    {
    	$priority = Symptom::max('priority')+1;
    	$symptom_types = SymptomClassification::select(['id', 'symptoms_type'])->where('status', 1)->get();

        return view('symptoms.create', compact('priority', 'symptom_types'));
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'symptoms_title' => 'required|unique:symptoms,symptoms_title,NULL,id',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $priority = Symptom::max('priority')+1;
        $data['priority'] = $priority;

        $symptom = Symptom::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Symptom created successfully.',
                'data'    => $symptom
            ]);
        }
    }

    public function edit($id)
    {
        $data = Symptom::find($id);
        $symptom_types = SymptomClassification::select(['id', 'symptoms_type'])->where('status', 1)->get();

        return view('symptoms.edit', compact('data', 'symptom_types'));
    }

    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'symptoms_title' => 'required|unique:symptoms,symptoms_title,'.$id.',id',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $symptom = Symptom::find($id);

        if (!$symptom) {
            return redirect()->back()
                ->with('error','Symptom not found!');
        }

        $symptom->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Symptom Updated successfully',
                'data'    => $symptom
            ]);
        }
    }

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $Update = Symptom::where('id', '=', $request->id)->update($data);

            $Redirect = 'test-units';

            if($Update){
                return response()->json([
                    'success' => true,
                    'message' => ['Symptom status successfully change'],
                    'data'    => [
                        'redirect' => $Redirect,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data'    => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function destroy(Request $request)
    {
        Symptom::find($request->id)->delete();

        $Redirect = 'symptoms';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }

    public function importCreate()
    {
        $symptom_classifications = SymptomClassification::all();

       return view('symptoms.import' , compact('symptom_classifications'));
    }

    public function importPreview(Request $request)
    {
        $symptoms_data = [];

        Session::put('SymptomsData', $symptoms_data);

        try {
            Excel::import(new ImportSymptom, $request->file('symptoms'));

            $data = Session::get('SymptomsData');
          

            return view('symptoms.preview', compact('data'));

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => [$e->getMessage()],
            ]);
        }
    }

    public function importSessionDestroy(Request $request)
    {
        $symptoms_data = Session::get('SymptomsData');

        unset($symptoms_data[$request->id]);

        Session::put('SymptomsData', $symptoms_data);

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully']
        ]);
    }

    public function importStore(Request $request)
    {
        ini_set('memory_limit', '3000M');
        ini_set('max_execution_time', '0');

        // Validate the file input
        $request->validate([
            'symptoms'      => 'required|file|mimes:xlsx,xls',
            'symptoms_type' => 'required'
        ]);

        // Process the uploaded file using the ImportSymptom class
        \Excel::import(new ImportSymptom, $request->file('symptoms'));

        // Get the data stored in the session
        $data = Session::get('SymptomsData', []);
        // dd($data);

        if (!empty($data)) {
            foreach ($data as $row) {
                $exist_symptoms = Symptom::where('symptoms_title', $row[0])->exists();

                if (!$exist_symptoms) {
                    $symptoms = [
                        'symptoms_title' => $row[0],
                        'code'           => $row[1]??'',
                        'description'    => $row[2]??'',
                        'type'           => $request->symptoms_type,
                    ];

                    Symptom::create($symptoms);
                }
            }

            return redirect()->route('symptoms.index')
                ->with('success', 'Symptoms uploaded successfully');
        } else {
            return redirect()->back()
                ->with('error', 'Empty file uploaded or no valid data found');
        }
    }


}
