<?php

namespace App\Http\Controllers\Doctor;

use App\Http\Controllers\Controller;
use App\Models\MedicalReferral;
use App\Models\DoctorTest;
use Illuminate\Http\Request;

class ReferralController extends Controller
{
    // ===== إنشاء تحويل جديد =====
    public function store(Request $request)
    {
        $data = $request->validate([
            'medical_record_id' => 'required|exists:medical_records,id',
            'patient_id'        => 'required|exists:patients,id',
            'referral_type'     => 'required|in:lab,xray,ultrasound,mri,ct,ecg,other',
            'title'             => 'required|string|max:200',
            'items'             => 'required|array|min:1',
            'items.*.name'      => 'required|string|max:200',
            'items.*.instructions' => 'nullable|string|max:300',
            'items.*.urgent'    => 'nullable|boolean',
            'items.*.test_id'   => 'nullable|integer',
            'clinical_notes'    => 'nullable|string|max:500',
            'is_urgent'         => 'nullable|boolean',
        ]);

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

        // تنقية العناصر الفارغة
        $data['items'] = collect($request->items)
            ->filter(fn($i) => !empty($i['name']))
            ->values()->toArray();

        $referral = MedicalReferral::create($data);

        // زيادة عداد التحاليل المستخدمة
        $testIds = collect($data['items'])->pluck('test_id')->filter()->unique();
        if ($testIds->isNotEmpty()) {
            DoctorTest::whereIn('id', $testIds)
                ->where('doctor_id', $doctorId)
                ->each(fn($t) => $t->incrementUsage());
        }

        // إذا طُلبت الطباعة مباشرة
        if ($request->boolean('print_now')) {
            return redirect()->route('doctor.referral.print', $referral->id);
        }

        return back()->with('success', 'تم حفظ التحويل بنجاح');
    }

    // ===== طباعة التحويل =====
    public function print($id)
    {
        $referral = MedicalReferral::with([
            'patient.user',
            'patient',
            'doctor.user',
        ])->where('doctor_id', session('doctor_id'))->findOrFail($id);

        $referral->update(['is_printed' => true, 'printed_at' => now()]);

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

    // ===== حذف تحويل =====
    public function destroy($id)
    {
        MedicalReferral::where('doctor_id', session('doctor_id'))
            ->findOrFail($id)->delete();
        return back()->with('success', 'تم حذف التحويل');
    }
}
