<?php

namespace App\Http\Controllers\OpdAppointment;

use App\Models\AppointmentShift;

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

class AppointmentShiftController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:appointment-shift-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = AppointmentShift::select([
            'id',
            'name',
            'patient_quantity',
            'time_from',
            'time_to',
            'color',
            'code',
            'bg_color',
            'priority',
            'status'
        ])
            ->paginate(10);

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

            $data = AppointmentShift::select([
                'id',
                'name',
                'patient_quantity',
                'time_from',
                'time_to',
                'color',
                'code',
                'bg_color',
                'priority',
                'status'
            ])
                ->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->where('name', 'like', '%' . $search_query . '%');
                })
                ->paginate($sort_by);

            return view('appointment-shift.table', compact('data'));
        } else {
            return view('appointment-shift.index', compact('data'));
        }
    }

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

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

        $quality = AppointmentShift::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Appointment Shift created successfully',
                'data' => $quality
            ]);
        }
        return redirect()->route('appointment-shift.index')
            ->with('success', 'Appointment Shift 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)
    {
        $shift = AppointmentShift::find($id);
        return view('appointment-shift.edit', compact('shift'));
    }

    /**
     * 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:appointment_shifts,name,' . $id,
            'patient_quantity'  => 'required',
        ]);

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

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

        $shift = AppointmentShift::find($id);

        if (!$shift) {
            return redirect()->route('appointment-shift.index')
                ->with('error', 'Appointment Shift not found!');
        }

        $shift->update($data);

        return redirect()->route('appointment-shift.index')
            ->with('success', 'Appointment Shift updated successfully');
    }

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

        $Redirect = 'appointment-shift';

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

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

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Appointment Shift 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('default' => $request->status);
            $count = AppointmentShift::where(['default' => $request->status])->count();

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

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

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