<?php

namespace App\Http\Controllers\Patients;

use App\DataTables\PatientsDataTable;
use App\Http\Controllers\Controller;
use App\Models\Branches;
use App\Models\Clinic;
use App\Models\DoctorProfiles;
use App\Models\Patient;
use App\Models\Patients;
use App\Models\Prescriptions;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PatientController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(PatientsDataTable $dataTable)
    {

        return $dataTable->render('admin.patients.index');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.patients.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $user = Auth::user();

        $data = $request->validate([
            'first_name' => ['required', 'string', 'max:255'],
            'last_name'  => ['nullable', 'string', 'max:255'],
            'gender'     => ['nullable', 'in:male,female'],
            'birth_date' => ['nullable', 'date'],
            'phone'      => ['required', 'string', 'max:30'],
            'phone_alt'  => ['nullable', 'string', 'max:30'],
            'email'      => ['nullable', 'email', 'max:255'],
            'national_id'=> ['nullable', 'string', 'max:50'],
            'address'    => ['nullable', 'string', 'max:500'],
            'notes'      => ['nullable', 'string'],
        ]);

        $data['clinic_id'] = $user->clinic_id ?? Clinic::first()->id;
        $data['branch_id'] = $user->branch_id ?? Branches::first()->id;

        $data['code'] = 'PAT-' . str_pad((Patients::max('id') + 1), 4, '0', STR_PAD_LEFT);

        Patients::create($data);

        return redirect()
            ->route('patients.index')
            ->with('success', 'تم إضافة المريض بنجاح.');
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        $user = Auth::user();

        $patient = Patients::with([
            'medicalRecord',
            'appointments.doctor.user',
            'visits.doctor.specialty',
            'prescriptions.doctor.user',
            'attachments',
            'invoices' => function ($q) {
                $q->orderByDesc('date');
            },
            'invoices.payments',
        ])
            ->where('clinic_id', $user->clinic_id)
            ->findOrFail($id);

        $doctors = DoctorProfiles::with('user', 'specialty')

            ->get();

        return view('admin.patients.show', compact('patient', 'doctors'));
    }


    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $patient = Patients::find($id);
        $this->authorizePatient($patient);
        return view('admin.patients.edit', compact('patient'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request)
    {

        $data = $request->validate([
            'first_name' => ['required', 'string', 'max:255'],
            'last_name'  => ['nullable', 'string', 'max:255'],
            'gender'     => ['nullable', 'in:male,female'],
            'birth_date' => ['nullable', 'date'],
            'phone'      => ['required', 'string', 'max:30'],
            'phone_alt'  => ['nullable', 'string', 'max:30'],
            'email'      => ['nullable', 'email', 'max:255'],
            'national_id'=> ['nullable', 'string', 'max:50'],
            'address'    => ['nullable', 'string', 'max:500'],
            'notes'      => ['nullable', 'string'],
        ]);

        $patient = Patients::findorfail($request->id);

        $patient->update($data);

        return redirect()
            ->route('patients.index')
            ->with('success', 'تم تعديل بيانات المريض بنجاح.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $patient = Patients::find($id);
        $this->authorizePatient($patient);
        $patient->delete(); // لو الموديل فيه SoftDeletes هيتعمله soft delete

        return redirect()
            ->route('patients.index')
            ->with('success', 'تم حذف المريض بنجاح.');
    }

    public function print(Prescriptions $prescription)
    {
        $patient = $prescription->patient;

        $user = Auth::user();

        if (!$user || !$user->clinic_id) {
            abort(403, 'غير مصرح لك بالوصول إلى هذا المريض.');
        }

        if ($patient->clinic_id !== $user->clinic_id) {
            abort(404);
        }

        if ($user->role !== 'owner' && $user->branch_id && $patient->branch_id !== $user->branch_id) {
            abort(404);
        }

        $prescription->load([
            'patient',
            'doctor.user',
            'doctor.specialty',
            'items.medication',
        ]);

        return view('admin.patients.print', compact('prescription'));
    }


    protected function authorizePatient(Patients $patient): void
    {
        $user = Auth::user();

        if (!$user || !$user->clinic_id) {
            abort(403, 'غير مصرح لك بالوصول إلى هذا المريض.');
        }

        if ($patient->clinic_id !== $user->clinic_id) {
            abort(404);
        }

        if ($user->role !== 'owner' && $user->branch_id && $patient->branch_id !== $user->branch_id) {
            abort(404);
        }
    }


    public function ajaxSearch(Request $request)
    {
        $search = $request->input('q');

        $patients = Patients::query()
            ->where(function ($qBuilder) use ($search) {
                $qBuilder->where('first_name', 'LIKE', "%$search%")
                    ->orWhere('last_name', 'LIKE', "%$search%")
                    ->orWhere('phone', 'LIKE', "%$search%")
                    ->orWhere('code', 'LIKE', "%$search%");
            })
            ->limit(20)
            ->get();

        return response()->json(
            $patients->map(function ($p) {

                return [
                    'id'    => $p->id,
                    'text'  => "{$p->first_name} {$p->last_name} — ({$p->phone}) — كود: {$p->code}",
                    'name'  => "{$p->first_name} {$p->last_name}",
                    'phone' => $p->phone,
                    'code'  => $p->code,
                ];
            })
        );
    }

}
