<?php

namespace App\Http\Controllers\MedicalSetting;

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

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

    public function index(Request $request)
    {
        $data = DischargeType::select([
                    'discharge_types.id',
                    'discharge_types.name',
                    'discharge_types.code',
                    'discharge_types.priority',
                    'discharge_types.is_default',
                    'discharge_types.status',
                ]);

        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('discharge_types.name', 'like', '%'.$search_query.'%')
                ->orWhere('discharge_types.code', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

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

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

    public function create()
    {
    	$max_priority = DischargeType::max('priority');
    	$priority = ($max_priority ?? 0)+1;

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

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

        $max_priority = DischargeType::max('priority');
        $priority = ($max_priority ?? 0) + 1;

        $data['priority'] = $priority;

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

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

        $type = DischargeType::create($data);

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

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

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

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

        $data['code'] = strtoupper(str_replace(' ', '_', $request->name));

        $type = DischargeType::find($id);

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

        $type->update($data);

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

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

            $Redirect = 'discharge-types';

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

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

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

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

    public function destroy(Request $request)
    {
        $about = DischargeType::find($request->id);

        if ($about->is_default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $about->delete();

        $Redirect = 'discharge-types';

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