<?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 Generator
include __DIR__ . '/core/autoload.php';
include __DIR__ . '/core/app/model/CotizacionData.php';
include __DIR__ . '/core/app/model/PacientData.php';
include __DIR__ . '/core/app/model/MedicData.php';
include __DIR__ . '/core/app/model/InventoryItemData.php';
include __DIR__ . '/core/app/model/QuirofanoData.php';
// Nota: los modelos necesarios ya están incluidos arriba. Este bloque repetía
// CotizacionData/MedicData/PacientData con `include` (no `_once`) y provocaba
// "Cannot redeclare class" en cada request.

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);

// Include TCPDF
require_once 'tcpdf/tcpdf.php';

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

// Set document information
$pdf->SetCreator('Cedimik');
$pdf->SetAuthor('Cedimik');
$pdf->SetTitle('Cotización #' . $c->id);
$pdf->SetSubject('Cotización de Servicios');

// Remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

// Set margins
$pdf->SetMargins(15, 15, 15);

// Set auto page breaks
$pdf->SetAutoPageBreak(true, 15);

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

// Add a page
$pdf->AddPage();

// Header with logo
$pdf->Image('assets/images/logo/logo.png', 15, 10, 50, 25, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);

// Title
$pdf->SetFont('helvetica', 'B', 18);
$pdf->SetXY(70, 10);
$pdf->Cell(80, 8, 'COTIZACION', 0, 0, 'R');

$pdf->SetFont('helvetica', '', 10);
$pdf->SetXY(70, 18);
$pdf->Cell(80, 5, 'Nro: SJ-' . str_pad($c->id, 5, '0', STR_PAD_LEFT) . '/2026', 0, 0, 'R');

// Clinic name
$pdf->SetFont('helvetica', '', 8);
$pdf->SetXY(70, 23);
$pdf->Cell(80, 4, 'Cedimik', 0, 0, 'R');

// Date
$pdf->SetXY(150, 28);
$pdf->Cell(45, 5, 'Fecha: ' . date('d/m/Y', strtotime($c->date)), 0, 1, 'R');
$pdf->SetXY(150, 33);
$pdf->Cell(45, 5, 'Validez: ' . date('d/m/Y', strtotime($c->validity_date)), 0, 1, 'R');

// Status badge
$status_colors = array(
    'draft' => array(128, 128, 128),
    'sent' => array(0, 123, 255),
    'accepted' => array(40, 167, 69),
    'rejected' => array(220, 53, 69),
    'expired' => array(255, 193, 7)
);
$status_labels = array(
    'draft' => 'BORRADOR',
    'sent' => 'ENVIADA',
    'accepted' => 'ACEPTADA',
    'rejected' => 'RECHAZADA',
    'expired' => 'EXPIRADA'
);

$pdf->SetXY(15, 40);
$rgb = $status_colors[$c->status] ?? array(128, 128, 128);
$pdf->SetFillColor($rgb[0], $rgb[1], $rgb[2]);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(30, 8, $status_labels[$c->status] ?? $c->status, 0, 0, 'C', true);
$pdf->SetTextColor(0, 0, 0);

// Line
$pdf->SetY(52);
$pdf->Line(15, $pdf->GetY(), 195, $pdf->GetY());

// Professional and Patient info
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetY(55);
$pdf->Cell(90, 6, 'PROFESIONAL:', 0, 0, 'L');
$pdf->Cell(90, 6, 'PACIENTE:', 0, 1, 'L');

$pdf->SetFont('helvetica', '', 9);
$pdf->Cell(90, 5, ($profesional ? $profesional->name . ' ' . $profesional->lastname : 'No especificado'), 0, 0, 'L');
$pdf->Cell(90, 5, ($patient ? $patient->name . ' ' . $patient->lastname : 'No especificado'), 0, 1, 'L');

// Line
$pdf->SetY(70);
$pdf->Line(15, $pdf->GetY(), 195, $pdf->GetY());

// Table Header (total width: 90+25+35+30 = 180)
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(240, 240, 240);
$pdf->Cell(90, 8, 'DESCRIPCION', 1, 0, 'C', true);
$pdf->Cell(25, 8, 'CANT.', 1, 0, 'C', true);
$pdf->Cell(35, 8, 'P. UNIT.', 1, 0, 'C', true);
$pdf->Cell(30, 8, 'SUBTOTAL', 1, 1, 'C', true);

// Table Body
$pdf->SetFont('helvetica', '', 9);
foreach ($detalles as $d) {
    $is_insumo = !empty($d->inventory_item_id);
    $is_custom = !empty($d->is_custom);
    
    if ($is_custom) {
        $item_name = $d->custom_description ?: 'Item personalizado';
        $qty = number_format($d->quantity, 2);
        $precio = number_format($d->hourly_rate, 2) . ' Bs';
    } elseif ($is_insumo) {
        $item_name = $d->item_name ?: 'Insumo #' . $d->inventory_item_id;
        $qty = number_format($d->quantity, 2);
        $precio = number_format($d->hourly_rate, 2) . ' Bs';
    } else {
        $item_name = $d->quirofano_name ?: 'Quirófano #' . $d->cama_id;
        $qty = number_format($d->quantity, 2);
        $precio = number_format($d->hourly_rate, 2) . ' Bs';
    }
    $subtotal = number_format($d->subtotal, 2) . ' Bs';

    $pdf->Cell(90, 12, $item_name, 1, 0, 'L');
    $pdf->Cell(25, 12, $qty, 1, 0, 'C');
    $pdf->Cell(35, 12, $precio, 1, 0, 'R');
    $pdf->Cell(30, 12, $subtotal, 1, 1, 'R');
}

// Total row (total width: 135+45 = 180)
$pdf->SetFont('helvetica', 'B', 11);
$pdf->SetFillColor(220, 220, 220);
$pdf->Cell(135, 10, 'TOTAL:', 1, 0, 'R', true);
$pdf->Cell(45, 10, number_format($c->total, 2) . ' Bs', 1, 1, 'R', true);

// Notes
if ($c->notes) {
    $pdf->SetY($pdf->GetY() + 5);
    $pdf->SetFont('helvetica', 'B', 9);
    $pdf->Cell(0, 5, 'OBSERVACIONES:', 0, 1);
    $pdf->SetFont('helvetica', '', 9);
    $pdf->MultiCell(0, 5, $c->notes, 0, 'L');
}

// Footer
$pdf->SetY(-30);
$pdf->SetFont('helvetica', 'I', 8);
$pdf->Cell(0, 5, 'Este documento es una cotización y no representa una factura.', 0, 1, 'C');
$pdf->Cell(0, 5, 'Cedimik', 0, 1, 'C');
$pdf->Cell(0, 5, 'Tel: (591) 2 222-2222 | contacto@cedimik.com', 0, 1, 'C');

// Output PDF
$pdf->Output('SJ-' . str_pad($c->id, 5, '0', STR_PAD_LEFT) . '.pdf', 'I');
?>