<?php

namespace App\Http\Controllers\IpdAdmission;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\IpdDischargeTypeSetting;
use App\Models\DischargeType;
// use App\Models\IpdDischargeType;

class IpdDischargeTypeSettingsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request , $id = '')
    {

        $data = IpdDischargeTypeSetting::select([   
                'ipd_discharge_type_settings.id' , 
                'ipd_discharge_type_settings.field',
                'ipd_discharge_type_settings.type',
                'ipd_discharge_type_settings.priority',
                'ipd_discharge_type_settings.is_readonly',
                'ipd_discharge_type_settings.default_value',
                'ipd_discharge_type_settings.status',
                'ipd_discharge_type_settings.is_mandatory',
                'ipd_discharge_type_settings.select_options',
                'discharge_types.name as discharge_type_name',  
                'discharge_types.id'
            ])

            ->leftJoin('discharge_types','ipd_discharge_type_settings.discharge_type_id','=','discharge_types.id')

            ->when(!empty($id), function ($query) use ($id) {
                $query->where('ipd_discharge_type_settings.discharge_type_id', '=', $id);   
            });


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

        // dd($discharge_type);

        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('ipd_discharge_type_settings.field', 'like', '%'.$search_query.'%')
                            ->orWhere('ipd_discharge_type_settings.type', 'like', '%'.$search_query.'%')
                            ->orWhere('ipd_discharge_type_settings.default_value', 'like', '%'.$search_query.'%')
                            ->orWhere('ipd_discharge_type_settings.priority', 'like', '%'.$search_query.'%')
                            ->orWhere('ipd_discharge_type_settings.select_options', 'like', '%'.$search_query.'%');
                    })

                    ->paginate($sort_by);

            return view('ipd-discharge-type-settings.table', compact('data'));
        }

        else
        {
            $data = $data->paginate(10);

            return view('ipd-discharge-type-settings.index',compact('data' , 'discharge_type'));
        }

    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
         $discharge_type = DischargeType::select(   
                'ipd_discharge_type_settings.id' ,   
                'discharge_types.id as id'
            )
            ->leftJoin('ipd_discharge_type_settings','ipd_discharge_type_settings.discharge_type_id','=','discharge_types.id')
            ->where('discharge_types.id', $id)
            ->first();

        $data = DischargeType::select(['id','name'])->get();

        return view('ipd-discharge-type-settings.create',compact('data', 'discharge_type'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, $id = '')
    {

        $validator = \Validator::make($request->all(), [
            'field'             => 'required',
            'type'              => 'required',
            'select_options'    => 'required_if:type,radio,selection',
            'discharge_type_id' => 'required',
        ]);

        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['status'] = 1;

        IpdDischargeTypeSetting::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Setting has been created successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Setting has been created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $field = IpdDischargeTypeSetting::find($id);

        $dischargetype = DischargeType::select(['id','name'])->get();
        return view('ipd-discharge-type-settings.edit', compact('field','dischargetype'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'field'               => 'required',
            'type'                => 'required',
            'select_options'      => 'required_if:type,radio,checkbox,selection',
        ]);

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

        $field = IpdDischargeTypeSetting::find($id);

        if (!$field) {
            return redirect()->route('ipd-discharge-type-settings.index')
                ->with('error','Master Setting not found!');
        }

        $field->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Master Setting has been updated successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Master Setting updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request , $id)
    {
      

        $field = IpdDischargeTypeSetting::where('discharge_type_id' , $id)
        ->first();
        
        if (!$field) {
            return redirect()->route('ipd-discharge-type-settings.index')
                ->with('error','Master Setting not found!');
        }

        $field->delete();

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

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

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