<?php

namespace App\Http\Controllers\Tenant;

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

class ClinicalEvolutionController extends Controller
{
    public function create(Customer $patient): View
    {
        $history = $patient->clinicalHistory()->firstOrCreate([], [
            'opening_date'   => now(),
            'history_number' => $this->generateHistoryNumber(),
            'created_by'     => auth()->id(),
        ]);

        $employees = Employee::where('is_active', true)->get();

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

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

        $data = $request->validate([
            'employee_id'        => ['nullable', 'exists:employees,id'],
            'consultation_reason'=> ['required', 'string'],
            'current_illness'    => ['nullable', 'string'],
            'physical_exam'      => ['nullable', 'string'],
            'vital_signs'        => ['nullable', 'array'],
            'vital_signs.*'      => ['nullable', 'string'],
            'diagnosis_notes'    => ['nullable', 'string'],
            'treatment_plan'     => ['nullable', 'string'],
            'recommendations'    => ['nullable', 'string'],
            'next_control_date'  => ['nullable', 'date'],
            'diagnoses'          => ['nullable', 'array'],
            'diagnoses.*.name'   => ['required_with:diagnoses.*', 'string', 'max:255'],
            'diagnoses.*.cie10_code' => ['nullable', 'string', 'max:20'],
            'diagnoses.*.type'   => ['nullable', 'in:primary,secondary,impression'],
        ]);

        $evolution = $history->evolutions()->create([
            'company_id'          => $history->company_id,
            'customer_id'         => $patient->id,
            'employee_id'         => $data['employee_id'] ?? null,
            'consultation_reason' => $data['consultation_reason'],
            'current_illness'     => $data['current_illness'] ?? null,
            'physical_exam'       => $data['physical_exam'] ?? null,
            'vital_signs'         => $this->filterVitalSigns($data['vital_signs'] ?? []),
            'diagnosis_notes'     => $data['diagnosis_notes'] ?? null,
            'treatment_plan'      => $data['treatment_plan'] ?? null,
            'recommendations'     => $data['recommendations'] ?? null,
            'next_control_date'   => $data['next_control_date'] ?? null,
            'status'              => 'draft',
            'created_by'          => auth()->id(),
        ]);

        if (! empty($data['diagnoses'])) {
            foreach ($data['diagnoses'] as $diag) {
                if (! empty($diag['name'])) {
                    ClinicalDiagnosis::create([
                        'company_id'            => $history->company_id,
                        'clinical_history_id'   => $history->id,
                        'clinical_evolution_id' => $evolution->id,
                        'customer_id'           => $patient->id,
                        'cie10_code'            => $diag['cie10_code'] ?? null,
                        'name'                  => $diag['name'],
                        'type'                  => $diag['type'] ?? 'primary',
                        'created_by'            => auth()->id(),
                    ]);
                }
            }
        }

        activity()
            ->causedBy(auth()->user())
            ->performedOn($evolution)
            ->log('Evolución clínica creada');

        return redirect()->route('tenant.patients.show', $patient)
            ->with('success', 'Evolución clínica registrada.');
    }

    public function show(Customer $patient, ClinicalEvolution $evolution): View
    {
        abort_unless($evolution->customer_id === $patient->id, 404);

        $evolution->load(['employee', 'diagnoses', 'prescriptions.items', 'orders', 'signer']);

        return view('tenant.evolutions.show', compact('patient', 'evolution'));
    }

    public function sign(Customer $patient, ClinicalEvolution $evolution): RedirectResponse
    {
        abort_unless($evolution->customer_id === $patient->id, 404);
        abort_if($evolution->isSigned(), 403, 'La evolución ya está firmada.');

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

        activity()
            ->causedBy(auth()->user())
            ->performedOn($evolution)
            ->log('Evolución clínica firmada');

        return back()->with('success', 'Evolución firmada y bloqueada para edición.');
    }

    private function filterVitalSigns(array $signs): ?array
    {
        $filtered = array_filter($signs, fn ($v) => $v !== null && $v !== '');

        return ! empty($filtered) ? $filtered : null;
    }

    private function generateHistoryNumber(): string
    {
        $year = now()->format('Y');
        $count = \App\Models\ClinicalHistory::withoutGlobalScopes()
            ->whereYear('created_at', $year)->count() + 1;

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