<?php

namespace App\Http\Controllers\MedicalSetting;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\AnesthesiaType;

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

    public function index(Request $request)
    {
        $data = AnesthesiaType::select([
                    'anesthesia_types.id',
                    'anesthesia_types.name',
                    'anesthesia_types.code',
                    'anesthesia_types.priority',
                    'anesthesia_types.is_default',
                    'anesthesia_types.status',
                ])
                ->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('anesthesia_types.name', 'like', '%'.$search_query.'%')
                    ->orWhere('anesthesia_types.code', 'like', '%'.$search_query.'%');
            })
            ->orderBy('priority', 'ASC')
            ->paginate($sort_by);

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

            return view('anesthesia-types.index', compact('data'));
        }
    }

    public function create()
    {
        $priority = AnesthesiaType::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('anesthesia-types.create',compact('priority'));
    }

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

        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'
        ]);

        $default_check = AnesthesiaType::where(['is_default' => 1,'status' => 1])->first();

        if (!$default_check) {
            $data['is_default'] = 1;
        }

        $AnesthesiaType = AnesthesiaType::create($data);

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

    public function edit($id)
    {
        $data = AnesthesiaType::find($id);

        return view('anesthesia-types.edit', compact('data'));
    }

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

        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'
        ]);

        $AnesthesiaType = AnesthesiaType::find($id);

        if (!$AnesthesiaType) {
            return redirect()->route('anesthesia-types.index')
                ->with('error','Anesthesia type not found!');
        }

        $AnesthesiaType->update($data);

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

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

            $Redirect = 'special-cases';

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

    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status );
            $count  = AnesthesiaType::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default anesthesia type!'],
                    'data'    => []
                ]);
            } else {
                $Update = AnesthesiaType::where('id', '=', $request->id)->update($data);

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

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

        $Redirect = 'anesthesia-types';

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