<?php

namespace App\Http\Controllers\OpdAppointment;

use App\Models\Account;
use App\Models\AppointmentShift;
use App\Models\Doctor;
use App\Models\DoctorFee;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class DoctorFeeController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:doctor-fee-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = DoctorFee::select([
            'doctor_fees.id',
            'doctor_fees.doctor_id',
            'doctor_fees.shift_id',
            'doctor_fees.consulting_fees',
            'doctor_fees.status',
            ])


            // ->groupBy('appointment_doctor_schedules.doctor_id')
            // ->groupBy('appointment_doctor_schedules.shift_id')
            ->with('getDoctor')
            ->with('getShift')
            ->paginate(10);
        if ($request->ajax()) {
            $sort_by = $request->get('sortby') ?? 10;
            $sort_type = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = DoctorFee::select([
                'doctor_fees.id',
                'doctor_fees.doctor_id',
                'doctor_fees.consulting_fees',
                'doctor_fees.shift_id',
                'doctor_fees.status',
            ])
                ->with('getDoctor')
                ->with('getShift')
                ->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->whereHas('getAccount', function ($accountQuery) use ($search_query) {
                        $accountQuery->where('name', 'like', '%' . $search_query . '%');
                    });
                })

                ->paginate($sort_by);

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

        $account = Doctor::with('getAccount')->get();
        $shift = AppointmentShift::select('id', 'name')->get();
        return view('doctor-fee.create', compact('account', 'shift'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $doctor_id = $request->doctor_id;
        $validator = \Validator::make($request->all(), [
            'doctor_id'             => 'required',
            'shift_id'                   => [
                'required',
                Rule::unique('doctor_fees')->where(function ($query) use ($doctor_id) {
                    return $query->where('doctor_id', $doctor_id)
                        ->where('deleted_at', NULL);
                }),
            ],
        ]);
        $customMessages = [
            'shift_id.unique' => 'The Shift is Already Taken.',
        ];
        $validator->setCustomMessages($customMessages);
        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',
            // 'shift_id'
        ]);

        // foreach ($request->shift_id as $key => $value) {
        //     $data['shift_id'] = $value;

        // }
        $schedule = DoctorFee::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Doctor Fee Created Successfully',
                'data' => $schedule
            ]);
        }
        return redirect()->route('doctor-fee.index')
            ->with('success', 'Doctor Fee 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)
    {
        $fee = DoctorFee::find($id);
        $account = Doctor::with('getAccount')->get();
        $shift = AppointmentShift::select('id', 'name')->get();
        return view('doctor-fee.edit', compact('account', 'fee','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)
    {
        $doctor_id = $request->doctor_id;
        $validator = \Validator::make($request->all(), [
            'shift_id'              => [
                'required',
                Rule::unique('doctor_fees')->where(function ($query) use ($doctor_id) {
                    return $query->where('doctor_id', $doctor_id)
                        ->where('deleted_at', NULL);
                }),
            ],
        ]);
        $customMessages = [
            'shift_id.unique' => 'The Shift is Already Taken.',
        ];
        $validator->setCustomMessages($customMessages);

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

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

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

        if (!$source) {
            return redirect()->route('doctor-fee.index')
                ->with('error','Doctor Fee not found!');
        }

        $source->update($data);

        return redirect()->route('doctor-fee.index')
            ->with('success','Doctor Fee updated successfully');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        // $doctorId = $request->id;
        // $dat = DoctorFee::where('doctor_id', $doctorId)->delete();

        DoctorFee::find($request->id)->delete();


        $Redirect = 'doctor-fee';

        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 = DoctorFee::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Doctor Fee status successfully change'],
                    'data' => [
                        'redirect' => '/users/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }
    public function searchDoctors(Request $request)
    {
        $searchTerm = $request->search_text;
        $results = Doctor::join('accounts', 'doctors.account_id', '=', 'accounts.id')
        ->where('accounts.name', 'LIKE', '%' . $searchTerm . '%')
        ->select('doctors.id','accounts.name')
        ->get();
        return response()->json(['result' => $results, 'status' => true]);
    }

}
