<?php

namespace App\Http\Controllers\Doctor;

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

class MedicineController extends Controller
{
    // ===== صفحة إدارة الأدوية والتحاليل =====
    public function index()
    {
        $doctorId = session('doctor_id');

        $medicines = DoctorMedicine::where('doctor_id', $doctorId)
            ->orderByDesc('usage_count')
            ->orderBy('sort_order')
            ->get()
            ->groupBy('category');

        $tests = DoctorTest::where('doctor_id', $doctorId)
            ->orderByDesc('usage_count')
            ->orderBy('sort_order')
            ->get()
            ->groupBy('category');

        return view('doctor.medicines.index', compact('medicines', 'tests'));
    }

    // ===== API: جلب الأدوية للـ autocomplete =====
    public function getMedicines()
    {
        $medicines = DoctorMedicine::where('doctor_id', session('doctor_id'))
            ->popular(50)
            ->get(['id','name','name_en','category','form',
                   'default_dose','default_times','default_duration',
                   'default_instructions','usage_count','auto_suggest']);

        return response()->json($medicines);
    }

    // ===== API: الأدوية المقترحة تلقائياً (استُخدمت 3+ مرات) =====
    public function getAutoSuggest()
    {
        $medicines = DoctorMedicine::where('doctor_id', session('doctor_id'))
            ->autoSuggest(20)
            ->get(['id','name','name_en','form',
                   'default_dose','default_times','default_duration',
                   'default_instructions','usage_count']);

        return response()->json($medicines);
    }

    // ===== API: جلب التحاليل =====
    public function getTests()
    {
        $tests = DoctorTest::where('doctor_id', session('doctor_id'))
            ->popular(50)
            ->get(['id','name','name_en','category','referral_type','instructions','usage_count']);

        return response()->json($tests);
    }

    // ===== إضافة دواء =====
    public function storeMedicine(Request $request)
    {
        $data = $request->validate([
            'name'                 => 'required|string|max:150',
            'name_en'              => 'nullable|string|max:150',
            'category'             => 'nullable|string|max:80',
            'form'                 => 'nullable|string|max:50',
            'default_dose'         => 'nullable|string|max:100',
            'default_times'        => 'nullable|string|max:100',
            'default_duration'     => 'nullable|string|max:100',
            'default_instructions' => 'nullable|string|max:500',
        ]);

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

        DoctorMedicine::create($data);

        return back()->with('success', 'تم إضافة الدواء: ' . $data['name']);
    }

    // ===== تعديل دواء =====
    public function updateMedicine(Request $request, $id)
    {
        $med = DoctorMedicine::where('doctor_id', session('doctor_id'))->findOrFail($id);

        $data = $request->validate([
            'name'                 => 'required|string|max:150',
            'name_en'              => 'nullable|string|max:150',
            'category'             => 'nullable|string|max:80',
            'form'                 => 'nullable|string|max:50',
            'default_dose'         => 'nullable|string|max:100',
            'default_times'        => 'nullable|string|max:100',
            'default_duration'     => 'nullable|string|max:100',
            'default_instructions' => 'nullable|string|max:500',
        ]);

        $med->update($data);

        return back()->with('success', 'تم تحديث الدواء');
    }

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

    // ===== إضافة تحليل =====
    public function storeTest(Request $request)
    {
        $data = $request->validate([
            'name'         => 'required|string|max:150',
            'name_en'      => 'nullable|string|max:150',
            'category'     => 'nullable|string|max:80',
            'instructions' => 'nullable|string|max:500',
        ]);

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

        DoctorTest::create($data);

        return back()->with('success', 'تم إضافة التحليل: ' . $data['name']);
    }

    // ===== تعديل تحليل =====
    public function updateTest(Request $request, $id)
    {
        $test = DoctorTest::where('doctor_id', session('doctor_id'))->findOrFail($id);

        $data = $request->validate([
            'name'         => 'required|string|max:150',
            'name_en'      => 'nullable|string|max:150',
            'category'     => 'nullable|string|max:80',
            'instructions' => 'nullable|string|max:500',
        ]);

        $test->update($data);
        return back()->with('success', 'تم تحديث التحليل');
    }

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