<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Surgery;
use App\Models\SurgeryType;
use App\Models\Designation;
use App\Models\AnesthesiaType;
use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\AccountAddress;
use App\Models\AccountBank;
use App\Models\SurgeryTeam;
use App\Models\AccountLicense;
use App\Models\MasterType;
use App\Models\SaleInvoice;
use App\Models\MasterCategory;
use App\Models\AccountingGroup;
use App\Models\TaxRegisterCategory;
use App\Models\AccountPayment;
use App\Models\AccountAttachment;
use App\Models\AccountImage;
use App\Models\Country;
use App\Models\CompanyAddress;
use App\Models\AccountContact;
use App\Models\Gender;
use App\Models\MaritalStatus;
use App\Models\BloodGroup;
use App\Models\User;
use App\Models\AccountTitle;
use App\Models\AccountRelativesDetail;
use App\Models\LicenseType;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Carbon\Carbon;
use App\Models\RelationType;
use App\Models\StudentHouse;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\AccountsExport;
use App\Models\AccountSettlementType;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Models\AppointmentShift;
use App\Models\Doctor;
use App\Models\DoctorFee;
use App\Models\IpdAdmission;
use Illuminate\Support\Facades\DB;


class SurgeriesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        $surgery_types = SurgeryType::all();
        $ipd_id        = $id;

        return view('ipd-admission-surgeries.create' , compact('surgery_types', 'ipd_id'));   
    }

    /**
     * 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(), [
            'ipd_id'          => 'nullable',
            'doctor_id'       => 'required',
            'surgery_type_id' => 'required',
            'notes'           => 'nullable',
            'scheduled_date'  => 'required',
            'scheduled_time'  => 'required',
            'duration'        => 'required',
        ]);


        if ($validator->fails()) {
            return response()->json([
                'success'  => false,
                'message'  => $validator->getMessageBag()->first(),
                'data'     => [
                'redirect' => ''],
            ]);
        }

        $data = $request->except([
            '_token',
            '_method',
        ]);
     
            $surgeries = [
                'ipd_id'              => $id ??  null, 
                'surgent_ac_id'       => $request->doctor_id,
                'surgery_type_id'     => $request->surgery_type_id,
                'notes'               => $request->notes,
                'scheduled_date_time' => $request->scheduled_date . ' ' . $request->scheduled_time,
                'duration'            => $request->duration,
            ];


        $surgeries = Surgery::create($surgeries);


        return response()->json([
            'success'  => true,
            'message'  => 'Surgery Created successfully',
            'data'     => [
            'redirect' => '', 
            ]
        ]);


    }

    /**
     * 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)
{
    // Retrieve the Surgery model or fail if not found
    $surgery = Surgery::findOrFail($id);

    // Retrieve all SurgeryType records
    $surgery_types = SurgeryType::all(); 

    // Initialize doctor variable
    $doctor = null;

    // Fetch doctor details if a surgeon account ID is present
    if ($surgery->surgent_ac_id) {
        $doctor = Account::getAccount([
            'account_types.type_code' => 'DOCTOR',
            'accounts.id' => $surgery->surgent_ac_id
        ]);
        
        // Format doctor's full name if doctor is found
        if ($doctor) {
            $doctor->full_name = $doctor->name .
                ($doctor->code ? ', ' . $doctor->code : '') .
                ($doctor->gender ? ', ' . $doctor->gender : '') .
                ($doctor->age ? ', ' . $doctor->age . ' yrs' : '') .
                ($doctor->phone_no ? ', ' . $doctor->phone_no : '');
        }
    }

    // Return the view with the relevant data
    return view('ipd-admission-surgeries.edit', compact('surgery', 'surgery_types', 'doctor'));
}



    /**
     * 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(), [
        'ipd_id'              => 'nullable',
        'doctor_id'           => 'required',
        'surgery_type_id'     => 'required',
        'notes'               => 'nullable',
        'scheduled_date_time' => 'required',
        'duration'            => 'required',
    ]);

    if ($validator->fails()) {
        return response()->json(['success' => false, 'message' => $validator->getMessageBag()->first()]);
    }

    // Find the record to update
    $surgeries = Surgery::find($id);

    if (!$surgeries) {
        return response()->json(['success' => false, 'message' => 'Surgery not found.']);
    }


    // Update the surgeries data
     $surgeries->update([
        'surgent_ac_id'       => $request->doctor_id,
        'surgery_type_id'     => $request->surgery_type_id,
        'notes'               => $request->notes,
        'scheduled_date_time' => $request->scheduled_date_time,
        'duration'            => $request->duration,
    ]);

    return response()->json([
        'success' => true,
        'message' => 'Surgery was updated successfully',
        'data'     => [
        'redirect' => '', 
        ]
    ]);
    }

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

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


    public function surgeries($id)
    {
        $surgeries = Surgery::leftjoin('surgery_types' , 'surgery_types.id' , '=' , 'surgeries.surgery_type_id')
            ->leftjoin('accounts' , 'accounts.id' , '=' , 'surgeries.surgent_ac_id')
            ->where('ipd_id', $id)
            ->select(
                'surgeries.id as id',
                'accounts.name as surgent_name',
                'surgery_types.name as surgery_type_name' ,
                'surgeries.notes as note' ,
                'surgeries.scheduled_date_time as scheduled_date_time' ,
                'surgeries.duration as duration_time' ,
                'surgeries.status as status' ,
            )
            ->get();

        return view('ipd-admission-surgeries.table', compact('surgeries'));
    }



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

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


    public function assignTeam(Request $request , $id){

        $surgery_team = SurgeryTeam::leftJoin('surgeries' , 'surgeries.id' , '=' , 'surgery_teams.surgery_id')
            ->leftjoin('designations' , 'designations.id' , '=' , 'surgery_teams.designation_id')
            ->leftjoin('accounts' , 'surgery_teams.team_account_id' , '=' , 'accounts.id')
            ->where('surgeries.id' , $id)
            ->select(
                'surgeries.id as id' ,
                'surgery_teams.id as id' ,
                'accounts.name as surgent_name' ,
                'designations.name as designation_name' ,
                'surgery_teams.responsibility as responsibility' ,
            )
            ->get();

        $designations = Designation::all();


        // Retrieve the Surgery model or fail if not found
        $surgery = Surgery::findOrFail($id);

        // Initialize doctor variable
        $doctor = null;

        // Fetch doctor details if a surgeon account ID is present
        if ($surgery->surgent_ac_id) {
            $doctor = Account::getAccount([
                'account_types.type_code' => 'DOCTOR',
                'accounts.id'             => $surgery->surgent_ac_id
            ]);
            
            // Format doctor's full name if doctor is found
            if ($doctor) {
                $doctor->full_name = $doctor->name .
                ($doctor->code ? ', ' . $doctor->code : '') .
                ($doctor->gender ? ', ' . $doctor->gender : '') .
                ($doctor->age ? ', ' . $doctor->age . ' yrs' : '') .
                ($doctor->phone_no ? ', ' . $doctor->phone_no : '');
            }
        }

        return view('ipd-admission-surgeries.create-surgery-team', compact('surgery_team', 'id', 'designations', 'doctor', 'surgery'));
    }



    public function storeSurgeryTeam(Request $request , $id){

       $validator = \Validator::make($request->all(), [
            'surgery_id'     => 'nullable',
            'doctor_id'      => 'required',
            'designation_id' => 'required',
            'responsibility' => 'required',
            
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success'  => false,
                'message'  => $validator->getMessageBag()->first(),
                'data'     => [
                'redirect' => ''],
            ]);
        }

        $data = $request->except([
            '_token',
            '_method',
        ]);
     
            $surgery_team = [
                'surgery_id'      => $id ??  null, 
                'team_account_id' => $request->doctor_id,
                'designation_id'  => $request->designation_id,
                'responsibility'  => $request->responsibility,
            ];


        $surgery_team = SurgeryTeam::create($surgery_team);


        $surgery_team_list = SurgeryTeam::leftJoin('surgeries' , 'surgeries.id' , '=' , 'surgery_teams.surgery_id')
            ->leftjoin('designations' , 'designations.id' , '=' , 'surgery_teams.designation_id')
            ->leftjoin('accounts' , 'surgery_teams.team_account_id' , '=' , 'accounts.id')
            ->where('surgeries.id' , $id)
            ->select(
                'surgeries.id as id' ,
                'surgery_teams.id as id' ,
                'accounts.name as surgent_name' ,
                'designations.name as designation_name' ,
                'surgery_teams.responsibility as responsibility' ,
            )
            ->get();

        return response()->json([
            'success'  => true,
            'message'  => 'Surgery Team Created successfully',
            'data'     => $surgery_team_list 
        ]);
    }



    public function destroyAssignTeam($id)
    {
        SurgeryTeam::find($id)->delete();

        $surgery_team = SurgeryTeam::leftJoin('surgeries' , 'surgeries.id' , '=' , 'surgery_teams.surgery_id')
            ->leftjoin('designations' , 'designations.id' , '=' , 'surgery_teams.designation_id')
            ->leftjoin('accounts' , 'surgery_teams.team_account_id' , '=' , 'accounts.id')
            ->select(
                'surgeries.id as id' ,
                'surgery_teams.id as id' ,
                'accounts.name as surgent_name' ,
                'designations.name as designation_name' ,
                'surgery_teams.responsibility as responsibility' ,
            )
            ->get();

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

    public function anesthesiaCreate($id)
    {
        $surgery = Surgery::find($id);
        $anesthesia_types = AnesthesiaType::all();

        return view('ipd-admission-surgeries.anesthesia.create' , compact('anesthesia_types', 'surgery','id'));   
    }

    public function storeSurgeryAnesthesia(Request $request, $id)
    {
       $validator = \Validator::make($request->all(), [
            'anesthesia_name'     => 'required',
            'anesthesia_doctor'   => 'required',
            // 'anesthesia_type'     => 'required',
            // 'anesthesia_quantity' => 'required',
            // 'anesthesia_form'     => 'required',
            // 'anesthesia_time'     => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success'  => false,
                'message'  => $validator->getMessageBag()->first(),
                'data'     => [
                'redirect' => ''],
            ]);
        }

        $data = [
            'anesthesia_name'     => $request->anesthesia_name,
            'anesthesia_doctor'   => $request->anesthesia_doctor,
            'anesthesia_type'     => $request->anesthesia_type ?? '',
            'anesthesia_quantity' => $request->anesthesia_quantity ?? '',
            'anesthesia_form'     => $request->anesthesia_form ?? '',
            'anesthesia_time'     => $request->anesthesia_time ?? null,
        ];

        $surgery = Surgery::find($id);

        if (!$surgery) {
            return response()->json([
                'success'  => false,
                'message'  => 'Invalid surgery ID',
                'data'     => [
                'redirect' => ''],
            ]);
        }

        $surgery->update($data);

        return response()->json([
            'success'  => true,
            'message'  => 'Anesthesia stored successfully.'
        ]);
    }
}
