<?php

namespace App\Http\Controllers\Doctor;

use App\Http\Controllers\Controller;
use App\Models\MedicalRecord;
use App\Models\Patient;
use Illuminate\Http\Request;

class ArchiveController extends Controller
{
    public function index(Request $request)
    {
        $doctorId = session('doctor_id');

        $patients = Patient::with(['user','medicalRecords' => fn($q) =>
                $q->where('doctor_id',$doctorId)->latest()->take(1)
            ])
            ->whereHas('medicalRecords', fn($q) => $q->where('doctor_id',$doctorId))
            ->when($request->search, fn($q) =>
                $q->whereHas('user', fn($u) =>
                    $u->where('name','like',"%{$request->search}%")
                      ->orWhere('phone','like',"%{$request->search}%")
                )
            )
            ->latest()->paginate(12)->withQueryString();

        return view('doctor.archive.index', compact('patients'));
    }

    public function patient($id)
    {
        $doctorId = session('doctor_id');
        $patient  = Patient::with('user')->findOrFail($id);

        $records = MedicalRecord::where('doctor_id',$doctorId)
            ->where('patient_id',$id)
            ->latest('visit_date')->paginate(10);

        return view('doctor.archive.patient', compact('patient','records'));
    }

    public function record($id)
    {
        $record = MedicalRecord::with(['patient.user','doctor.user'])
            ->where('doctor_id',session('doctor_id'))
            ->findOrFail($id);

        return view('doctor.archive.record', compact('record'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'patient_id'                    => 'required|exists:patients,id',
            'appointment_id'                => 'nullable|exists:appointments,id',
            'visit_date'                    => 'required|date',
            'chief_complaint'               => 'nullable|string|max:500',
            'diagnosis'                     => 'required|string|max:1000',
            'symptoms'                      => 'nullable|string|max:500',
            'examination_notes'             => 'nullable|string|max:1000',
            'prescriptions'                 => 'nullable|array',
            'prescriptions.*.medicine'      => 'nullable|string',
            'prescriptions.*.dose'          => 'nullable|string',
            'prescriptions.*.times'         => 'nullable|string',
            'prescriptions.*.duration'      => 'nullable|string',
            'prescriptions.*.instructions'  => 'nullable|string',
            'prescriptions.*.medicine_id'   => 'nullable|integer',
            'lab_tests'                     => 'nullable|array',
            'lab_tests.*.test'              => 'nullable|string',
            'lab_tests.*.instructions'      => 'nullable|string',
            'lab_tests.*.test_id'           => 'nullable|integer',
            'instructions'                  => 'nullable|string|max:1000',
            'follow_up_notes'               => 'nullable|string|max:500',
            'next_visit_date'               => 'nullable|date|after:today',
            'blood_pressure'                => 'nullable|string|max:20',
            'temperature'                   => 'nullable|numeric|between:30,45',
            'pulse'                         => 'nullable|integer|between:20,300',
            'oxygen_saturation'             => 'nullable|integer|between:50,100',
            'weight'                        => 'nullable|numeric',
        ]);

        $prescriptions = collect($request->prescriptions ?? [])
            ->filter(fn($p) => !empty($p['medicine']))
            ->values()->toArray();

        $labTests = collect($request->lab_tests ?? [])
            ->filter(fn($t) => !empty($t['test']))
            ->values()->toArray();

        $doctorId              = session('doctor_id');
        $data['doctor_id']     = $doctorId;
        $data['prescriptions'] = $prescriptions;
        $data['lab_tests']     = $labTests;

        $record = MedicalRecord::create($data);

        // زيادة عداد الأدوية
        $medicineIds = collect($prescriptions)->pluck('medicine_id')->filter()->unique();
        if ($medicineIds->isNotEmpty()) {
            \App\Models\DoctorMedicine::whereIn('id', $medicineIds)
                ->where('doctor_id', $doctorId)
                ->increment('usage_count');
        }

        // زيادة عداد التحاليل
        $testIds = collect($labTests)->pluck('test_id')->filter()->unique();
        if ($testIds->isNotEmpty()) {
            \App\Models\DoctorTest::whereIn('id', $testIds)
                ->where('doctor_id', $doctorId)
                ->increment('usage_count');
        }

        if ($request->boolean('print_after')) {
            return redirect()->route('doctor.archive.print', $record->id);
        }

        return redirect()->route('doctor.archive.record', $record->id)
            ->with('success', 'تم حفظ السجل الطبي بنجاح');
    }

    public function update(Request $request, $id)
    {
        $record = MedicalRecord::where('doctor_id', session('doctor_id'))->findOrFail($id);

        $data = $request->validate([
            'chief_complaint'               => 'nullable|string|max:500',
            'diagnosis'                     => 'required|string|max:1000',
            'symptoms'                      => 'nullable|string|max:500',
            'examination_notes'             => 'nullable|string|max:1000',
            'prescriptions'                 => 'nullable|array',
            'prescriptions.*.medicine'      => 'nullable|string',
            'prescriptions.*.dose'          => 'nullable|string',
            'prescriptions.*.times'         => 'nullable|string',
            'prescriptions.*.duration'      => 'nullable|string',
            'prescriptions.*.instructions'  => 'nullable|string',
            'instructions'                  => 'nullable|string|max:1000',
            'follow_up_notes'               => 'nullable|string|max:500',
            'next_visit_date'               => 'nullable|date',
            'blood_pressure'                => 'nullable|string|max:20',
            'temperature'                   => 'nullable|numeric|between:30,45',
            'pulse'                         => 'nullable|integer|between:20,300',
            'oxygen_saturation'             => 'nullable|integer|between:50,100',
            'weight'                        => 'nullable|numeric',
        ]);

        $data['prescriptions'] = collect($request->prescriptions ?? [])
            ->filter(fn($p) => !empty($p['medicine']))
            ->values()->toArray();

        $record->update($data);

        return redirect()->route('doctor.archive.record', $id)
            ->with('success', 'تم تحديث السجل الطبي');
    }

    public function print($id)
    {
        $record = MedicalRecord::with([
            'patient.user',
            'patient',
            'doctor.user',
        ])->where('doctor_id', session('doctor_id'))->findOrFail($id);

        return view('doctor.archive.print', compact('record'));
    }
}
