<?php

namespace App\Http\Controllers\OpdAppointment;

use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\AppointmentDoctorFees;
use App\Models\AppointmentDoctorShift;
use App\Models\AppointmentShift;
use App\Models\Doctor;
use App\Models\Product;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Validation\Rule;

class AppointmentDoctorFeesController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $doctor_id, $shift_id)
    {
        $doctor_name = Doctor::with('getAccount')->find($doctor_id);
        $data = AppointmentDoctorFees::select([
            'id',
            'doctor_id',
            'shift_id',
            'product_id',
            'status'
        ])
            ->where(['doctor_id' => $doctor_id, 'shift_id' => $shift_id,'chamber_id'=>$doctor_name->doctors_chamber_id])
            ->with('getProduct')
            ->with('getDoctor');
        $doctorName = '';
        $shift_name = AppointmentShift::select('name')->where('id', $shift_id)->first();
        

        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->whereHas('getProduct', function ($subQuery) use ($search_query) {
                    $subQuery->where('name', 'like', '%' . $search_query . '%');
                });
            })
                ->paginate($sort_by);

            return view('appointment-doctor-fees.table', compact('data'));
        } else {
            $data = $data->paginate(10);
            $doctorName = $doctor_name->getAccount->name ?? '';

            return view('appointment-doctor-fees.index', compact('data', 'doctor_id', 'shift_id', 'doctorName', 'shift_name'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $product_id = Product::select('id', 'name');
        return view('appointment-doctor-fees.create', compact('product_id'));
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // dd($request->all());
        $doctor_id = $request->input('doctor_id');
        $shift_id  = $request->input('shift_id');
        $doctor    = Doctor::find($doctor_id);
        $chamber_id = $doctor->doctors_chamber_id;

        $validator = \Validator::make($request->all(), [
            'product_id' => [
                'required',
                Rule::unique('appointment_doctor_fees')->where(function ($query) use ($doctor_id, $shift_id,$chamber_id) {
                    return $query->where('doctor_id', $doctor_id)
                        ->where('shift_id', $shift_id)
                        ->where('chamber_id',$chamber_id)
                        ->where('deleted_at', NULL);
                }),
            ],
        ]);

        $customMessages = [
            'product_id.unique' => 'The Product 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',
        ]);
        $data['doctor_id'] = $doctor_id;
        $data['shift_id'] = $shift_id;
        $data['chamber_id'] = $chamber_id;

        $schedule = AppointmentDoctorFees::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Doctor Fee Created Successfully',
                'data' => $schedule
            ]);
        }
        return Redirect::back()->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)
    {
        $product_id = Product::select('id', 'name');
        $fees = AppointmentDoctorFees::find($id);

        return view('appointment-doctor-fees.edit', compact('product_id', 'fees'));
    }

    /**
     * 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->input('doctor_id');
        $shift_id = $request->input('shift_id');

        $doctor    = Doctor::find($doctor_id);
        $chamber_id = $doctor->doctors_chamber_id;


        $validator = \Validator::make($request->all(), [
            'product_id' => [
                'required',
                Rule::unique('appointment_doctor_fees')->where(function ($query) use ($doctor_id, $shift_id,$chamber_id,$id) {
                    return $query->where('doctor_id', $doctor_id)
                                ->where('shift_id', $shift_id)
                                ->where('chamber_id',$chamber_id)
                                ->where('id','!=',$id)
                                ->where('deleted_at', NULL);
                }),
            ],
        ]);

        $customMessages = [
            'product_id.unique' => 'The Product 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',
        ]);
        $data['doctor_id']  = $doctor_id;
        $data['shift_id']   = $shift_id;
        $data['chamber_id'] = $chamber_id;

        $schedule = AppointmentDoctorFees::where('id', $id)->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Doctor Fee Updated Successfully',
                'data' => $schedule
            ]);
        }
        return Redirect::back()->with('success', 'Doctor Fee Updated Successfully');
    }

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

        $Redirect = 'address-types';

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

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Appointment Doctor Fees status successfully change'],
                    'data' => [
                        'redirect' => '',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }
    public function searchProduct(Request $request)
    {
        $searchTerm = $request->search_text;
        $results = [];
        if($searchTerm!=''){
            $results = Product::select('products.id', 'products.name', 'product_prices.mrp')
            ->leftJoin('product_prices', 'products.id', '=', 'product_prices.product_id')
            ->where('products.name', 'LIKE', '%' . $searchTerm . '%')
            ->where('product_prices.status', 1)
            ->get();
        }
       
       
        return response()->json(['result' => $results, 'status' => true]);
    }
}
