<?php

namespace App\Http\Controllers\OpdAppointment;

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

class OPDScheduleTypeController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:opd-schedule-type-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = OpdScheduleType::select([
                    'opd_schedule_types.id',
                    'opd_schedule_types.name',
                    'opd_schedule_types.code',
                    'opd_schedule_types.details',
                    'opd_schedule_types.priority',
                    'opd_schedule_types.is_default',
                    'opd_schedule_types.status',
                ])
                ->paginate(10);

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

            $data = OpdScheduleType::select([
                'opd_schedule_types.id',
                'opd_schedule_types.name',
                'opd_schedule_types.code',
                'opd_schedule_types.details',
                'opd_schedule_types.priority',
                'opd_schedule_types.is_default',
                'opd_schedule_types.status',
                ])
                    ->when(!empty($search_query), function ($query) use ($search_query) {
                        return $query->where('opd_schedule_types.name', 'like', '%'.$search_query.'%');
                        // ->orWhere('enquiry_sources.enquiry_source_code', 'like', '%'.$search_query.'%');
                    })
                        ->paginate($sort_by);

            return view('opd-schedule-type.table', compact('data'));
        }
        else
        {
            return view('opd-schedule-type.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = OpdScheduleType::max('priority');
        $priority = $priority != '' ? $priority : 0;
        return view('opd-schedule-type.create',compact('priority'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:opd_schedule_types',
        ]);

        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 = OpdScheduleType::where(['is_default' => 1,'status' => 1])->first();

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

        $source = OpdScheduleType::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Appointment Schedule Created successfully',
                'data'    => $source
            ]);
        }

        return redirect()->route('opd-schedule-type.index')->with('success','Appointment Schedule 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)
    {
        $opdscheduletypes = OpdScheduleType::find($id);

        return view('opd-schedule-type.edit',compact('opdscheduletypes'));
    }

    /**
     * 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(), [
            'name'      => 'required|unique:opd_schedule_types,name,'.$id,
        ]);

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

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

        $source = OpdScheduleType::find($id);

        if (!$source) {
            return redirect()->route('opd-schedule-type.index')
                ->with('error','Appointment Schedule not found!');
        }

        $source->update($data);

        return redirect()->route('opd-schedule-type.index')
            ->with('success','Appointment Schedule updated successfully');
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $about = OpdScheduleType::find($request->id);

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

        $about->delete();

        $Redirect = 'opd-schedule-type';

        return response()->json([
            'success' => true,
            'message' => ['Opd Schedule Type Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }
    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $Update = OpdScheduleType::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Appointment Schedule status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } 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  = OpdScheduleType::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Opd Schedule Type!'],
                    'data'    => []
                ]);
            }

            $Update = OpdScheduleType::where('id', '=', $request->id)->update($data);

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



}
