<?php
// --- Auth gate: PDF standalone, sin sesión no se sirve ---
if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
if (empty($_SESSION['user_id'])) { header('Location: index.php?view=login'); exit; }
// --- end auth gate ---
/**
 * Cotizacion PDF "Split" - 2 hojas:
 *   Hoja 1: solo Monto Particular
 *   Hoja 2: solo Monto Facturado (Seguro)
 *
 * Diferente del original `cotizacion_pdf.php` que lista insumos por dia.
 */

require_once __DIR__ . '/core/autoload.php';
require_once __DIR__ . "/core/app/model/CotizacionData.php";;
require_once __DIR__ . "/core/app/model/PacientData.php";;
require_once __DIR__ . "/core/app/model/MedicData.php";;


if (!isset($_GET['id'])) {
    die('Cotizacion ID required');
}

$c = CotizacionData::getById(intval($_GET['id'] ?? 0));
if (!$c) {
    die('Cotizacion not found');
}

$profesional = $c->getProfessional();
$patient = $c->getPatient();
$detalles = CotizacionData::getDetalles($c->id);

// Totales por tipo
$totales = ['particular' => 0, 'facturado' => 0];
foreach ($detalles as $d) {
    $bt = $d->billing_type ?? 'particular';
    if (isset($totales[$bt])) {
        $totales[$bt] += floatval($d->subtotal);
    }
}

// Si no hay items de un tipo, el total queda en 0; igual imprimimos la hoja (puede ser $0)

require_once 'tcpdf/tcpdf.php';

$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

$pdf->SetCreator('Cedimik');
$pdf->SetAuthor('Cedimik');
$pdf->SetTitle('Cotizacion #' . $c->id . ' - Desglose');
$pdf->SetSubject('Cotizacion - Hojas separadas por tipo');

$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(15, 20, 15);
$pdf->SetAutoPageBreak(true, 20);
$pdf->SetFont('helvetica', '', 10);

$tipos = [
    'particular' => 'PARTICULAR',
    'facturado'  => 'FACTURADO (SEGURO)',
];

$oc_label = 'SJ-' . str_pad($c->id, 5, '0', STR_PAD_LEFT) . '/2026';

foreach ($tipos as $tipo_key => $tipo_label) {
    $total = $totales[$tipo_key];

    $pdf->AddPage();

    // --- Header (logo solo en hoja FACTURADO/seguro) ---
    if ($tipo_key === 'facturado') {
        $logo = 'assets/images/logo/logo.png';
        if (file_exists($logo)) {
            $pdf->Image($logo, 15, 10, 50, 25, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
        }
    }

    // Title
    $pdf->SetFont('helvetica', 'B', 18);
    $pdf->SetXY(70, 12);
    $pdf->Cell(125, 8, $tipo_label, 0, 0, 'R');

    $pdf->SetFont('helvetica', '', 10);
    $pdf->SetXY(70, 22);
    $pdf->Cell(125, 5, 'Nro: ' . $oc_label, 0, 0, 'R');
    $pdf->SetFont('helvetica', '', 8);
    $pdf->SetXY(70, 27);
    $pdf->Cell(125, 4, 'Cedimik', 0, 0, 'R');

    // --- Datos de la OC ---
    $pdf->SetY(50);
    $pdf->SetFont('helvetica', 'B', 11);
    $pdf->Cell(95, 6, 'ORDEN DE COBRO #' . $c->id, 0, 1, 'L');

    $pdf->SetFont('helvetica', '', 10);

    $prof_name = $profesional ? ($profesional->name ?? '') . ' ' . ($profesional->lastname ?? '') : '-';
    $pat_name  = $patient       ? ($patient->name       ?? '') . ' ' . ($patient->lastname       ?? '') : '-';

    $pdf->Cell(45, 5, 'Paciente:', 0, 0);
    $pdf->SetFont('helvetica', 'B', 10);
    $pdf->Cell(0, 5, $pat_name, 0, 1);

    $pdf->SetFont('helvetica', '', 10);
    $pdf->Cell(45, 5, 'Médico:', 0, 0);
    $pdf->SetFont('helvetica', 'B', 10);
    $pdf->Cell(0, 5, $prof_name, 0, 1);

    $pdf->SetFont('helvetica', '', 10);
    $pdf->Cell(45, 5, 'Fecha:', 0, 0);
    $pdf->Cell(0, 5, date('d/m/Y', strtotime($c->date)), 0, 1);

    $pdf->Cell(45, 5, 'Validez:', 0, 0);
    $pdf->Cell(0, 5, date('d/m/Y', strtotime($c->validity_date)), 0, 1);

    // --- Tipo destacado ---
    $pdf->Ln(8);
    $pdf->SetFont('helvetica', 'B', 14);
    $pdf->Cell(0, 8, 'TIPO DE COBRO: ' . $tipo_label, 0, 1, 'L');

    // --- Detalle del cobro (items del tipo correspondiente) ---
    $pdf->SetFont('helvetica', 'B', 10);
    $pdf->SetFillColor(220, 220, 220);
    $pdf->Cell(25, 7, 'Fecha', 1, 0, 'C', true);
    $pdf->Cell(95, 7, 'Insumo', 1, 0, 'C', true);
    $pdf->Cell(25, 7, 'Cant', 1, 0, 'C', true);
    $pdf->Cell(35, 7, 'Subtotal', 1, 1, 'C', true);

    $pdf->SetFont('helvetica', '', 9);
    $fillRow = false;
    $detalles_tipo = array_filter($detalles, function ($d) use ($tipo_key) {
        return ($d->billing_type ?? 'particular') === $tipo_key;
    });
    foreach ($detalles_tipo as $d) {
        $insumo = '-';
        if (!empty($d->item_name)) {
            $insumo = $d->item_name;
            if (!empty($d->item_code)) {
                $insumo .= ' [' . $d->item_code . ']';
            }
        } elseif (!empty($d->quirofano_name)) {
            $insumo = 'Cama: ' . $d->quirofano_name;
        } elseif (!empty($d->custom_description)) {
            $insumo = $d->custom_description;
        } elseif (!empty($d->notes)) {
            $insumo = $d->notes;
        }

        $fecha = !empty($d->fecha_uso) ? date('d/m/Y', strtotime($d->fecha_uso)) : '';
        $cant  = number_format(floatval($d->quantity), 2);
        $sub   = number_format(floatval($d->subtotal), 2);

        $pdf->SetFillColor(248, 248, 248);
        $pdf->Cell(25, 6, $fecha, 1, 0, 'C', $fillRow);
        $pdf->Cell(95, 6, $insumo, 1, 0, 'L', $fillRow);
        $pdf->Cell(25, 6, $cant, 1, 0, 'R', $fillRow);
        $pdf->Cell(35, 6, 'Bs ' . $sub, 1, 1, 'R', $fillRow);
        $fillRow = !$fillRow;
    }

    // --- Total (caja destacada) ---
    $pdf->Ln(5);
    $pdf->SetFillColor(230, 240, 255);
    $pdf->SetFont('helvetica', 'B', 24);
    $pdf->Cell(0, 25, '  Total ' . $tipo_label . ':  Bs ' . number_format($total, 2), 0, 1, 'L', true);

    $pdf->Ln(10);

    // --- Pie ---
    $pdf->SetFont('helvetica', 'I', 9);
    $pdf->SetTextColor(120, 120, 120);
    $pdf->Cell(0, 5, 'Documento generado electrónicamente - ' . date('d/m/Y H:i'), 0, 1, 'R');
    $pdf->SetTextColor(0, 0, 0);
}

// Output
$pdf->Output('cotizacion_' . $c->id . '_desglose.pdf', 'I');
