<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\ClinicalEvolution;
use App\Models\ClinicalOrder;
use App\Models\Customer;
use App\Models\Prescription;
use App\Support\Tenant;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Response;

class ClinicalPdfController extends Controller
{
    public function prescription(Customer $patient, Prescription $prescription): Response
    {
        abort_unless($prescription->customer_id === $patient->id, 404);

        activity()->causedBy(auth()->user())->performedOn($prescription)->log('PDF receta descargado');

        $prescription->load(['items', 'employee.user', 'signer']);
        $company = Tenant::current();

        $pdf = Pdf::loadView('pdf.prescription', compact('patient', 'prescription', 'company'))
            ->setPaper('letter', 'portrait');

        return $pdf->download("receta-{$prescription->prescription_number}.pdf");
    }

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

        activity()->causedBy(auth()->user())->performedOn($evolution)->log('PDF evolución descargado');

        $evolution->load(['employee.user', 'diagnoses', 'signer']);
        $company = Tenant::current();

        $pdf = Pdf::loadView('pdf.evolution', compact('patient', 'evolution', 'company'))
            ->setPaper('letter', 'portrait');

        return $pdf->download("evolucion-{$evolution->id}.pdf");
    }

    public function order(Customer $patient, ClinicalOrder $order): Response
    {
        abort_unless($order->customer_id === $patient->id, 404);

        activity()->causedBy(auth()->user())->performedOn($order)->log('PDF orden descargado');

        $order->load(['employee.user', 'signer']);
        $company = Tenant::current();

        $pdf = Pdf::loadView('pdf.clinical-order', compact('patient', 'order', 'company'))
            ->setPaper('letter', 'portrait');

        return $pdf->download("orden-{$order->id}.pdf");
    }

    public function fullHistory(Customer $patient): Response
    {
        $patient->load([
            'clinicalHistory.backgrounds',
            'clinicalHistory.evolutions.employee',
            'clinicalHistory.evolutions.diagnoses',
            'clinicalHistory.prescriptions.items',
            'clinicalHistory.orders',
            'clinicalHistory.consents',
        ]);

        $company = Tenant::current();

        activity()->causedBy(auth()->user())
            ->performedOn($patient->clinicalHistory)
            ->log('Historia clínica completa descargada en PDF');

        $pdf = Pdf::loadView('pdf.clinical-history', compact('patient', 'company'))
            ->setPaper('letter', 'portrait');

        return $pdf->download("historia-clinica-{$patient->id}.pdf");
    }
}
