<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\ClinicalEvolution;
use App\Models\Customer;
use App\Models\Employee;
use App\Models\Prescription;
use App\Models\PrescriptionItem;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class PrescriptionController extends Controller
{
    public function create(Customer $patient, ?ClinicalEvolution $evolution = null): View
    {
        $history = $patient->clinicalHistory;
        $employees = Employee::where('is_active', true)->get();

        return view('tenant.prescriptions.create', compact('patient', 'history', 'evolution', 'employees'));
    }

    public function store(Request $request, Customer $patient): RedirectResponse
    {
        $history = $patient->clinicalHistory()->firstOrCreate([], ['created_by' => auth()->id()]);

        $data = $request->validate([
            'employee_id'        => ['nullable', 'exists:employees,id'],
            'evolution_id'       => ['nullable', 'exists:clinical_evolutions,id'],
            'diagnosis_summary'  => ['nullable', 'string'],
            'notes'              => ['nullable', 'string'],
            'items'              => ['required', 'array', 'min:1'],
            'items.*.medication' => ['required', 'string', 'max:255'],
            'items.*.dose'       => ['nullable', 'string', 'max:100'],
            'items.*.frequency'  => ['nullable', 'string', 'max:100'],
            'items.*.duration'   => ['nullable', 'string', 'max:100'],
            'items.*.route'      => ['nullable', 'string', 'max:100'],
            'items.*.instructions' => ['nullable', 'string'],
        ]);

        $prescription = $history->prescriptions()->create([
            'company_id'            => $history->company_id,
            'customer_id'           => $patient->id,
            'clinical_evolution_id' => $data['evolution_id'] ?? null,
            'employee_id'           => $data['employee_id'] ?? null,
            'prescription_number'   => $this->generateNumber(),
            'diagnosis_summary'     => $data['diagnosis_summary'] ?? null,
            'notes'                 => $data['notes'] ?? null,
            'status'                => 'draft',
            'created_by'            => auth()->id(),
        ]);

        foreach ($data['items'] as $i => $item) {
            PrescriptionItem::create([
                'prescription_id' => $prescription->id,
                'company_id'      => $history->company_id,
                'medication'      => $item['medication'],
                'dose'            => $item['dose'] ?? null,
                'frequency'       => $item['frequency'] ?? null,
                'duration'        => $item['duration'] ?? null,
                'route'           => $item['route'] ?? null,
                'instructions'    => $item['instructions'] ?? null,
                'sort_order'      => $i,
            ]);
        }

        return redirect()->route('tenant.prescriptions.show', [$patient, $prescription])
            ->with('success', 'Receta creada. Revisa y firma cuando esté lista.');
    }

    public function show(Customer $patient, Prescription $prescription): View
    {
        abort_unless($prescription->customer_id === $patient->id, 404);
        $prescription->load(['items', 'employee.user', 'signer']);

        return view('tenant.prescriptions.show', compact('patient', 'prescription'));
    }

    public function sign(Customer $patient, Prescription $prescription): RedirectResponse
    {
        abort_unless($prescription->customer_id === $patient->id, 404);
        abort_if($prescription->isSigned(), 403, 'La receta ya está firmada.');

        $prescription->update([
            'status'    => 'signed',
            'signed_at' => now(),
            'signed_by' => auth()->id(),
        ]);

        activity()->causedBy(auth()->user())->performedOn($prescription)->log('Receta firmada');

        return back()->with('success', 'Receta firmada correctamente.');
    }

    public function index(Customer $patient): View
    {
        $prescriptions = $patient->prescriptions()
            ->with(['employee.user', 'items'])
            ->latest()
            ->paginate(10);

        return view('tenant.prescriptions.index', compact('patient', 'prescriptions'));
    }

    private function generateNumber(): string
    {
        $year = now()->format('Y');
        $count = Prescription::withoutGlobalScopes()->whereYear('created_at', $year)->count() + 1;

        return sprintf('RX-%s-%05d', $year, $count);
    }
}
