<?php
// Invoice PDF Generator
// --- Auth gate (invoice_pdf) ---
// Mismo patron que lab-resultado-pdf.php: se arranca la sesion explicitamente y
// se exige un usuario logueado ANTES de cualquier acceso a la base de datos, de
// modo que los llamados sin autenticacion no puedan sondear ids de cotizacion.
// Diferencia documentada: el redirect va a "index.php?view=login" y no a
// "?view=login". "Location: ?view=login" resuelve contra el propio
// invoice_pdf.php (no contra /cedimik/), lo que produce un loop de 50
// redirecciones en lugar de llegar al login (verificado con curl -L sobre
// lab-resultado-pdf.php).
if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
if (empty($_SESSION['user_id'])) { header('Location: index.php?view=login'); exit; }
// --- end auth gate ---
include __DIR__ . '/core/autoload.php';
include __DIR__ . '/core/app/model/CotizacionData.php';
include __DIR__ . '/core/app/model/CotizacionPagoData.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';

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

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

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

// Get insumos separately for the second page
$insumos = array();
$total_insumos = 0;
foreach ($detalles as $d) {
    if (!empty($d->inventory_item_id)) {
        $item = InventoryItemData::getById($d->inventory_item_id);
        $d->item_info = $item;
        $insumos[] = $d;
        $total_insumos += $d->subtotal;
    }
}

// Include TCPDF
require_once __DIR__ . '/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('Orden de Cobro #' . $c->id);
$pdf->SetSubject('Orden de Cobro 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 page 1 - Order Header
$pdf->AddPage();

// Logo on left
if (file_exists(__DIR__ . '/assets/images/logo/logo.png')) {
    $pdf->Image(__DIR__ . '/assets/images/logo/logo.png', 15, 10, 40, 20, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
}

// Header - Centered title (move right of logo)
$pdf->SetFont('helvetica', 'B', 12);
$pdf->SetXY(60, 10);
$pdf->Cell(0, 6, 'CEDIMIK S.R.L.', 0, 1, 'C');

$pdf->SetFont('helvetica', 'B', 11);
$pdf->SetXY(60, 16);
$pdf->Cell(0, 6, 'DETALLE DE SERVICIOS', 0, 1, 'C');

$pdf->SetFont('helvetica', '', 10);
$pdf->SetXY(60, 22);
$pdf->Cell(0, 6, 'PARTICULAR', 0, 1, 'C');

// Left side info
$pdf->SetY(35);
$pdf->SetFont('helvetica', '', 8);

// Get patient name
$patient_name = $patient ? $patient->name . ' ' . $patient->lastname : '____________________';
// Get doctor name
$doctor_name = $profesional ? $profesional->name . ' ' . $profesional->lastname : '____________________';

$pdf->Cell(0, 4, 'PACIENTE: ' . $patient_name, 0, 1, 'L');
$pdf->Cell(0, 4, 'MEDICO TRATANTE: ' . $doctor_name, 0, 1, 'L');
$pdf->Cell(0, 4, 'DIAGNOSTICO DE INGRESO: ____________________', 0, 1, 'L');
$pdf->Cell(0, 4, 'PROCEDIMIENTO: ____________________', 0, 1, 'L');
$pdf->Cell(0, 4, 'FECHA INGRESO: ____________ HORA INICIO: ____________', 0, 1, 'L');
$pdf->Cell(0, 4, 'CONCLUSION: ____________ FECHA DE ALTA: ____________', 0, 1, 'L');

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

// Table Header (total width: 100+25+35+30 = 190)
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(240, 240, 240);
$pdf->Cell(100, 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 - only non-insumos
$pdf->SetFont('helvetica', '', 9);
foreach ($detalles as $d) {
    if (!empty($d->inventory_item_id)) {
        continue;
    }
    
    $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';
    } 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(100, 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');
}

// MEDICAMENTOS E INSUMOS row (from page 2)
if ($total_insumos > 0) {
    $pdf->SetFont('helvetica', '', 9);
    $pdf->Cell(100, 12, 'MEDICAMENTOS E INSUMOS', 1, 0, 'L');
    $pdf->Cell(25, 12, '1.00', 1, 0, 'C');
    $pdf->Cell(35, 12, number_format($total_insumos, 2) . ' Bs', 1, 0, 'R');
    $pdf->Cell(30, 12, number_format($total_insumos, 2) . ' Bs', 1, 1, 'R');
}

// Total row
$pdf->SetFont('helvetica', 'B', 11);
$pdf->SetFillColor(220, 220, 220);
$pdf->Cell(145, 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');
}

// --- Pagos recibidos + saldo pendiente (seccion de reimpresion) ---
// Misma fuente de verdad que invoice-payment-view.php: CotizacionPagoData.
// Sin timestamps ni numeros de recibo: el documento sigue siendo idempotente
// (mismo id -> mismo contenido).
$pagosOc = CotizacionPagoData::getByCotizacion(intval($c->id));
$totalPagadoOc = 0.0;
foreach ($pagosOc as $pg) {
    $totalPagadoOc += floatval($pg->amount);
}
$saldoOc = round(floatval($c->total) - $totalPagadoOc, 2);

$pdf->SetY($pdf->GetY() + 5);
$pdf->SetFont('helvetica', 'B', 10);
$pdf->SetFillColor(240, 240, 240);
$pdf->Cell(190, 8, 'PAGOS RECIBIDOS', 1, 1, 'C', true);

if (count($pagosOc) > 0) {
    $pdf->SetFont('helvetica', 'B', 8);
    $pdf->SetFillColor(245, 245, 245);
    $pdf->Cell(30, 7, 'FECHA', 1, 0, 'C', true);
    $pdf->Cell(45, 7, 'METODO', 1, 0, 'L', true);
    $pdf->Cell(75, 7, 'REFERENCIA', 1, 0, 'L', true);
    $pdf->Cell(40, 7, 'MONTO', 1, 1, 'R', true);

    $pdf->SetFont('helvetica', '', 8);
    foreach ($pagosOc as $pg) {
        $fecha = !empty($pg->created_at) ? date('d/m/Y', strtotime($pg->created_at)) : '-';
        $metodo = !empty($pg->payment_method) ? strtoupper($pg->payment_method) : '-';
        $ref = !empty($pg->reference_number) ? $pg->reference_number : '-';
        $pdf->Cell(30, 7, $fecha, 1, 0, 'C');
        $pdf->Cell(45, 7, $metodo, 1, 0, 'L');
        $pdf->Cell(75, 7, $ref, 1, 0, 'L');
        $pdf->Cell(40, 7, number_format($pg->amount, 2) . ' Bs', 1, 1, 'R');
    }
} else {
    $pdf->SetFont('helvetica', 'I', 8);
    $pdf->Cell(190, 8, 'Sin pagos registrados contra esta Orden de Cobro.', 1, 1, 'C');
}

$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(220, 220, 220);
$pdf->Cell(145, 8, 'TOTAL PAGADO:', 1, 0, 'R', true);
$pdf->Cell(45, 8, number_format($totalPagadoOc, 2) . ' Bs', 1, 1, 'R', true);

if ($saldoOc > 0) {
    $pdf->SetFillColor(255, 220, 220); // pendiente
} else {
    $pdf->SetFillColor(212, 237, 218); // saldado
}
$pdf->Cell(145, 8, 'SALDO PENDIENTE:', 1, 0, 'R', true);
$pdf->Cell(45, 8, number_format(max(0, $saldoOc), 2) . ' Bs', 1, 1, 'R', true);

if ($saldoOc < 0) {
    // La OC esta pagada por encima de su total: no tiene sentido presentar un
    // saldo negativo como "pendiente". Se muestra el excedente registrado.
    $pdf->SetFillColor(209, 236, 241);
    $pdf->Cell(145, 8, 'EXCEDENTE PAGADO:', 1, 0, 'R', true);
    $pdf->Cell(45, 8, number_format(abs($saldoOc), 2) . ' Bs', 1, 1, 'R', true);
}
// --- fin seccion de pagos ---

// Page 2 - Insumos
if (count($insumos) > 0) {
    // ----------------------------------------------------------------
    // Group by AREA first, then by DATE within each area.
    // This matches the medical billing format: area is the primary
    // categorization, date is the secondary detail.
    // ----------------------------------------------------------------
    $area_groups = array();
    $area_order = array('piso_preqx', 'quirofano', 'utin', 'piso', null);
    $area_labels = array(
        'piso_preqx' => 'PISO PREQX',
        'quirofano'  => 'QUIROFANO',
        'utin'       => 'UTIN',
        'piso'       => 'PISO',
        null         => 'SIN CLASIFICAR'
    );
    // Soft-tinted backgrounds matching the Bootstrap badge palette
    $area_colors = array(
        'piso_preqx' => array(255, 243, 205), // warning yellow
        'quirofano'  => array(248, 215, 218), // danger pink/red
        'utin'       => array(209, 236, 241), // info blue
        'piso'       => array(212, 237, 218), // success green
        null         => array(233, 236, 239)  // gray
    );

    foreach ($insumos as $d) {
        $area = !empty($d->insumo_area) ? $d->insumo_area : null;
        $date_key = !empty($d->fecha_uso) ? $d->fecha_uso : $c->date;
        if (!isset($area_groups[$area])) {
            $area_groups[$area] = array('subtotal' => 0, 'dates' => array());
        }
        if (!isset($area_groups[$area]['dates'][$date_key])) {
            $area_groups[$area]['dates'][$date_key] = array('items' => array(), 'subtotal' => 0);
        }
        $area_groups[$area]['dates'][$date_key]['items'][] = $d;
        $area_groups[$area]['dates'][$date_key]['subtotal'] += $d->subtotal;
        $area_groups[$area]['subtotal'] += $d->subtotal;
    }

    // Sort dates inside each area
    foreach ($area_groups as &$ag) {
        ksort($ag['dates']);
    }
    unset($ag);

    $current_y = $pdf->GetY();

    // Render in fixed order: piso_preqx, quirofano, utin, piso, then uncategorized last
    foreach ($area_order as $area) {
        if (!isset($area_groups[$area])) continue;
        $ag = $area_groups[$area];
        $label = $area_labels[$area];
        $rgb = $area_colors[$area];

        // Page break check before the area header
        if ($current_y > 230) {
            $pdf->AddPage();
            if (file_exists(__DIR__ . '/assets/images/logo/logo.png')) {
                $pdf->Image(__DIR__ . '/assets/images/logo/logo.png', 15, 10, 40, 20, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            }
            $pdf->SetFont('helvetica', 'B', 12);
            $pdf->SetXY(60, 10);
            $pdf->Cell(0, 6, 'CEDIMIK S.R.L.', 0, 1, 'C');
            $pdf->SetFont('helvetica', 'B', 11);
            $pdf->SetXY(60, 16);
            $pdf->Cell(0, 6, 'DETALLE DE SERVICIOS', 0, 1, 'C');
            $pdf->SetFont('helvetica', '', 10);
            $pdf->SetXY(15, 27);
            $pdf->Cell(0, 6, 'PARTICULAR', 0, 1, 'C');
            $pdf->SetY(35);
            $current_y = 35;
        }

        // Area header band (larger, color-tinted)
        $pdf->SetFont('helvetica', 'B', 11);
        $pdf->SetFillColor($rgb[0], $rgb[1], $rgb[2]);
        $pdf->Cell(165, 9, 'AREA: ' . $label, 1, 0, 'L', true);
        $pdf->Cell(25, 9, number_format($ag['subtotal'], 2) . ' Bs', 1, 1, 'R', true);
        $current_y = $pdf->GetY();

        // Per-date sub-tables within this area
        foreach ($ag['dates'] as $gdate => $date_group) {
            if ($current_y > 240) {
                $pdf->AddPage();
                if (file_exists(__DIR__ . '/assets/images/logo/logo.png')) {
                    $pdf->Image(__DIR__ . '/assets/images/logo/logo.png', 15, 10, 40, 20, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
                }
                $pdf->SetFont('helvetica', 'B', 12);
                $pdf->SetXY(60, 10);
                $pdf->Cell(0, 6, 'CEDIMIK S.R.L.', 0, 1, 'C');
                $pdf->SetFont('helvetica', 'B', 11);
                $pdf->SetXY(60, 16);
                $pdf->Cell(0, 6, 'DETALLE DE SERVICIOS', 0, 1, 'C');
                $pdf->SetFont('helvetica', '', 10);
                $pdf->SetXY(15, 27);
                $pdf->Cell(0, 6, 'PARTICULAR', 0, 1, 'C');
                $pdf->SetY(35);
                $current_y = 35;
            }

            // Date band (smaller, gray)
            $display_date = date('d/m/Y', strtotime($gdate));
            $pdf->SetFont('helvetica', 'B', 8);
            $pdf->SetFillColor(220, 220, 220);
            $pdf->Cell(165, 6, 'Fecha: ' . $display_date, 1, 0, 'L', true);
            $pdf->Cell(25, 6, number_format($date_group['subtotal'], 2) . ' Bs', 1, 1, 'R', true);

            // Table header
            $pdf->SetFont('helvetica', 'B', 8);
            $pdf->SetFillColor(240, 240, 240);
            $pdf->Cell(20, 6, 'FECHA', 1, 0, 'C', true);
            $pdf->Cell(61, 6, 'MEDICAMENTOS Y DISPOSITIVOS', 1, 0, 'C', true);
            $pdf->Cell(35, 6, 'FORMA FARMACEUTICA', 1, 0, 'C', true);
            $pdf->Cell(25, 6, 'CONCENTRACION', 1, 0, 'C', true);
            $pdf->Cell(11, 6, 'CANT', 1, 0, 'C', true);
            $pdf->Cell(15, 6, 'P.UNIT', 1, 0, 'C', true);
            $pdf->Cell(16, 6, 'TOTAL', 1, 1, 'C', true);

            // Table body for this date
            $pdf->SetFont('helvetica', '', 8);
            foreach ($date_group['items'] as $d) {
                $item = $d->item_info;
                $name = $item ? $item->name : ($d->item_name ?: 'Insumo #' . $d->inventory_item_id);
                $forma = $item ? $item->presentation : '';
                $concentracion = '';
                $qty = number_format($d->quantity, 0);
                $precio = number_format($d->hourly_rate, 2);
                $total_str = number_format($d->subtotal, 2);

                $pdf->Cell(20, 7, $display_date, 1, 0, 'C');
                $pdf->Cell(61, 7, $name, 1, 0, 'L');
                $pdf->Cell(35, 7, $forma, 1, 0, 'L');
                $pdf->Cell(25, 7, $concentracion, 1, 0, 'L');
                $pdf->Cell(11, 7, $qty, 1, 0, 'C');
                $pdf->Cell(15, 7, $precio, 1, 0, 'R');
                $pdf->Cell(16, 7, $total_str, 1, 1, 'R');
            }

            // Date subtotal row
            $pdf->SetFont('helvetica', 'B', 8);
            $pdf->SetFillColor(245, 245, 245);
            $pdf->Cell(165, 5, 'Subtotal ' . $display_date . ':', 1, 0, 'R', true);
            $pdf->Cell(25, 5, number_format($date_group['subtotal'], 2) . ' Bs', 1, 1, 'R', true);

            $pdf->SetY($pdf->GetY() + 2);
            $current_y = $pdf->GetY();
        }

        // Area subtotal
        $pdf->SetFont('helvetica', 'B', 10);
        $pdf->SetFillColor($rgb[0], $rgb[1], $rgb[2]);
        $pdf->Cell(165, 7, 'SUBTOTAL ' . $label . ':', 1, 0, 'R', true);
        $pdf->Cell(25, 7, number_format($ag['subtotal'], 2) . ' Bs', 1, 1, 'R', true);

        $pdf->SetY($pdf->GetY() + 4);
        $current_y = $pdf->GetY();
    }

    // Grand total of all insumos
    $pdf->SetFont('helvetica', 'B', 11);
    $pdf->SetFillColor(180, 180, 180);
    $pdf->Cell(165, 8, 'TOTAL INSUMOS:', 1, 0, 'R', true);
    $pdf->Cell(25, 8, number_format($total_insumos, 2) . ' Bs', 1, 1, 'R', true);
}





    // Footer on last page
$pdf->SetY(-30);
$pdf->SetFont('helvetica', 'I', 8);
$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('OC-' . str_pad($c->id, 5, '0', STR_PAD_LEFT) . '.pdf', 'I');
