<?php

namespace App\Http\Controllers\MedicalSetting;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Finding;
use App\Models\FindingCategory;
use App\Imports\ImportFinding;
use Session;
use Maatwebsite\Excel\Facades\Excel;

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

    public function index(Request $request)
    {
        $data = Finding::select([
                    'findings.id',
                    'findings.name',
                    'findings.description',
                    'findings.status',
                    'findings.priority',
                    'finding_categories.category',
                ])
        		->leftjoin('finding_categories', 'finding_categories.id', 'findings.finding_category_id')
                ->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('findings.name', 'like', '%'.$search_query.'%')
                    ->orWhere('findings.description', 'like', '%'.$search_query.'%')
                    ->orWhere('finding_categories.category', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

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

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

    public function create()
    {
    	$priority = Finding::max('priority')+1;
    	$finding_categories = FindingCategory::select(['id', 'category'])->where('status', 1)->get();

        return view('findings.create', compact('priority', 'finding_categories'));
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:findings,name,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 = Finding::max('priority')+1;
        $data['priority'] = $priority;

        $finding = Finding::create($data);

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

    public function edit($id)
    {
        $data = Finding::find($id);
        $finding_categories = FindingCategory::select(['id', 'category'])->where('status', 1)->get();

        return view('findings.edit', compact('data', 'finding_categories'));
    }

    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:findings,name,'.$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'
        ]);

        $finding = Finding::find($id);

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

        $finding->update($data);

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

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

            $Redirect = 'findings';

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

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

        $Redirect = 'findings';

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

    public function importCreate()
    {
       return view('findings.import');
    }

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

        Session::put('FindingsData', $findings_data);

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

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

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

        } catch (\Exception $e) {

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

    public function importSessionDestroy(Request $request)
    {
        $findings_data = Session::get('FindingsData');

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

        Session::put('FindingsData', $findings_data);

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

    public function importStore(Request $request)
    {
        $data = Session::get('FindingsData');

        if($data){

            foreach ($data as $row){

                $category = FindingCategory::select('id')->where('category', $row[1])->first();

                if(!$category) {
                    $priority = FindingCategory::max('priority')+1;
                    $finding_category = ([
                        'category' => $row[1],
                        'priority' => $priority,
                    ]);

                    $category = FindingCategory::create($finding_category);
                }

                $priority = Finding::max('priority')+1;

                $findings = ([
                    'name'                => $row[0],
                    'finding_category_id' => $category->id,
                    'description'         => $row[2],
                    'priority'            => $priority,
                ]);

                $exist_findings = Finding::where('name', $row[0])->exists();

                if(!$exist_findings){
                    Finding::create($findings);
                }
            }

            return redirect()->route('findings.index')
                ->with('success','Findings uploaded successfully');
        }else{
           return redirect()->back()
                ->with('error','Empty file uploaded');
        }
    }
}
