<?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 ---
/**
 * solicitudcompra-pdf.php - PDF Individual de Solicitud de Compra
 * Parametros:
 *   id = ID de la solicitud de compra
 */

include __DIR__ . '/core/autoload.php';
include __DIR__ . '/core/app/model/UserData.php';

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

$id = intval($_GET['id']);
if ($id <= 0) {
    die('Invalid ID');
}

$con = Database::getCon();

// Obtener solicitud con datos del solicitante
$sql = "SELECT s.*, 
               u.name as sol_name, 
               u.lastname as sol_lastname,
               cb.name as cb_name,
               cb.lastname as cb_lastname
        FROM solicitud_compra s
        LEFT JOIN user u ON s.solicitado_por = u.id
        LEFT JOIN user cb ON s.created_by = cb.id
        WHERE s.id = $id";

$res = $con->query($sql);
$solicitud = $res ? $res->fetch_object() : null;

if (!$solicitud) {
    die('Solicitud no encontrada');
}

// Obtener items con JOIN a inventory segun inv_table
$sqlItems = "SELECT sci.*,
                    inv_item.name as item_name,
                    inv_item.code as item_code,
                    inv_item.presentation,
                    inv_med.name as med_name,
                    inv_med.code as med_code,
                    inv_med.presentation as med_presentation,
                    inv_med.liname_id,
                    inv_dev.name as dev_name,
                    inv_dev.code as dev_code,
                    inv_dev.presentation as dev_presentation,
                    inv_dev.linadime_id
             FROM solicitud_compra_item sci
             LEFT JOIN inventory_item inv_item ON sci.inventory_item_id = inv_item.id
             LEFT JOIN inventory_medication inv_med ON sci.inv_table = 'inventory_medication' AND sci.inv_id = inv_med.id
             LEFT JOIN inventory_device inv_dev ON sci.inv_table = 'inventory_device' AND sci.inv_id = inv_dev.id
             WHERE sci.solicitud_compra_id = $id
             ORDER BY sci.id ASC";

$resItems = $con->query($sqlItems);
$items = [];
while ($row = $resItems->fetch_object()) {
    $items[] = $row;
}

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

// Crear PDF
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);

$pdf->SetCreator('Cedimik');
$pdf->SetAuthor('Cedimik');
$pdf->SetTitle('Solicitud de Compra #' . $id);
$pdf->SetSubject('Solicitud de Compra');

// Configurar header/footer
$pdf->setPrintHeader(true);
$pdf->setPrintFooter(true);
$pdf->SetHeaderMargin(5);
$pdf->SetFooterMargin(10);
$pdf->SetMargins(15, 28, 15);
$pdf->SetAutoPageBreak(true, 20);

// Agregar pagina
$pdf->AddPage();

// Header con logo
$pdf->Image('assets/images/logo/logo.png', 15, 10, 22, 12, 'PNG');
$pdf->SetXY(40, 10);
$pdf->SetFont('helvetica', 'B', 14);
$pdf->SetTextColor(102, 126, 234); // #667eea
$pdf->Cell(0, 8, 'SOLICITUD DE COMPRA', 0, 1, 'L');

$pdf->SetTextColor(0, 0, 0);
$pdf->SetFont('helvetica', '', 9);
$pdf->SetXY(40, 18);
$pdf->Cell(0, 5, 'Cedimik', 0, 1, 'L');

$pdf->SetXY(40, 23);
$pdf->SetFont('helvetica', '', 8);
$pdf->Cell(0, 5, date('d/m/Y H:i'), 0, 1, 'L');

// Numero de solicitud a la derecha
$pdf->SetXY(140, 10);
$pdf->SetFont('helvetica', 'B', 11);
$pdf->Cell(55, 8, '#' . $id, 0, 1, 'R');

// Badge de estado
$estado_badges = array(
    'pendiente' => array(255, 193, 7, 0, 0, 0),
    'aprobada'  => array(13, 110, 253, 255, 255, 255),
    'completada' => array(25, 135, 84, 255, 255, 255),
    'anulada'   => array(108, 117, 125, 255, 255, 255)
);
$estado_labels = array(
    'pendiente' => 'PENDIENTE',
    'aprobada'  => 'APROBADA',
    'completada' => 'COMPLETADA',
    'anulada'   => 'ANULADA'
);

$estado = $solicitud->estado ?? 'pendiente';
$rgb = $estado_badges[$estado] ?? array(108, 117, 125, 255, 255, 255);
$pdf->SetXY(140, 19);
$pdf->SetFillColor($rgb[0], $rgb[1], $rgb[2]);
$pdf->SetTextColor($rgb[3], $rgb[4], $rgb[5]);
$pdf->SetFont('helvetica', 'B', 8);
$pdf->Cell(30, 7, $estado_labels[$estado] ?? strtoupper($estado), 0, 0, 'C', true);
$pdf->SetTextColor(0, 0, 0);

// Linea separadora
$pdf->SetY(33);
$pdf->SetDrawColor(102, 126, 234);
$pdf->Line(15, $pdf->GetY(), 195, $pdf->GetY());

// Datos de la solicitud
$pdf->SetY(36);
$pdf->SetFont('helvetica', 'B', 9);
$pdf->Cell(0, 6, 'DATOS DE LA SOLICITUD', 0, 1, 'L');

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

// Fila 1
$pdf->Cell(25, 5, 'Fecha:', 0, 0, 'L');
$pdf->SetFont('helvetica', '', 9);
$fechaSol = date('d/m/Y', strtotime($solicitud->fecha_solicitud));
$pdf->Cell(70, 5, $fechaSol, 0, 0, 'L');

$pdf->SetFont('helvetica', 'B', 9);
$pdf->Cell(25, 5, 'Proveedor:', 0, 0, 'L');
$pdf->SetFont('helvetica', '', 9);
$pdf->Cell(0, 5, $solicitud->proveedor ?: '-', 0, 1, 'L');

// Fila 2
$pdf->SetFont('helvetica', 'B', 9);
$pdf->Cell(25, 5, 'Solicitado por:', 0, 0, 'L');
$pdf->SetFont('helvetica', '', 9);
$solicitante = trim(($solicitud->sol_name ?? '') . ' ' . ($solicitud->sol_lastname ?? ''));
$pdf->Cell(70, 5, $solicitante ?: '-', 0, 0, 'L');

$pdf->SetFont('helvetica', 'B', 9);
$pdf->Cell(25, 5, 'Total Estimado:', 0, 0, 'L');
$pdf->SetFont('helvetica', '', 9);
$pdf->Cell(0, 5, number_format($solicitud->total_estimado, 2) . ' Bs', 0, 1, 'L');

// Notas
if (!empty($solicitud->notas)) {
    $pdf->SetFont('helvetica', 'B', 9);
    $pdf->Cell(25, 5, 'Notas:', 0, 0, 'L');
    $pdf->SetFont('helvetica', '', 9);
    $pdf->MultiCell(0, 5, $solicitud->notas, 0, 'L');
}

// Linea separadora
$pdf->SetY($pdf->GetY() + 3);
$pdf->SetDrawColor(200, 200, 200);
$pdf->Line(15, $pdf->GetY(), 195, $pdf->GetY());

// Tabla de items
$pdf->SetY($pdf->GetY() + 4);
$pdf->SetFont('helvetica', 'B', 9);
$pdf->Cell(0, 6, 'ITEMS SOLICITADOS', 0, 1, 'L');

// Header de tabla
$pdf->SetFillColor(240, 240, 240);
$pdf->SetFont('helvetica', 'B', 8);

$colWidths = array(10, 28, 22, 55, 30, 18, 18, 14);
$headers = array('#', 'Tipo', 'Codigo', 'Nombre', 'Presentacion', 'Cant.', 'P.Unit.', 'Subtotal');

$pdf->Cell($colWidths[0], 7, $headers[0], 1, 0, 'C', true);
$pdf->Cell($colWidths[1], 7, $headers[1], 1, 0, 'C', true);
$pdf->Cell($colWidths[2], 7, $headers[2], 1, 0, 'C', true);
$pdf->Cell($colWidths[3], 7, $headers[3], 1, 0, 'C', true);
$pdf->Cell($colWidths[4], 7, $headers[4], 1, 0, 'C', true);
$pdf->Cell($colWidths[5], 7, $headers[5], 1, 0, 'C', true);
$pdf->Cell($colWidths[6], 7, $headers[6], 1, 0, 'C', true);
$pdf->Cell($colWidths[7], 7, $headers[7], 1, 1, 'C', true);

// Filas de items
$pdf->SetFont('helvetica', '', 8);
$linea = 1;

foreach ($items as $item) {
    // Determinar tipo y datos segun inv_table
    if ($item->inv_table === 'inventory_medication') {
        $tipo = 'Medicamento';
        $codigo = $item->liname_id ?? $item->med_code ?? '-';
        $nombre = $item->med_name ?? $item->item_name ?? '-';
        $presentacion = $item->med_presentation ?? '-';
    } elseif ($item->inv_table === 'inventory_device') {
        $tipo = 'Dispositivo';
        $codigo = $item->linadime_id ?? $item->dev_code ?? '-';
        $nombre = $item->dev_name ?? $item->item_name ?? '-';
        $presentacion = $item->dev_presentation ?? '-';
    } else {
        $tipo = 'Legacy';
        $codigo = $item->item_code ?? '-';
        $nombre = $item->item_name ?? '-';
        $presentacion = $item->presentation ?? '-';
    }

    $cantidad = number_format($item->cantidad_solicitada, 2);
    $costoUnit = number_format($item->costo_unitario_estimado, 2);
    $subtotal = number_format($item->subtotal_estimado, 2);

    $rowHeight = 12;

    $pdf->Cell($colWidths[0], $rowHeight, $linea, 1, 0, 'C');
    
    // Badge de tipo
    $pdf->SetFillColor(102, 126, 234);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->Cell($colWidths[1], $rowHeight, $tipo, 1, 0, 'C', true);
    $pdf->SetTextColor(0, 0, 0);
    
    $pdf->Cell($colWidths[2], $rowHeight, $codigo, 1, 0, 'C');
    $pdf->Cell($colWidths[3], $rowHeight, substr($nombre, 0, 30), 1, 0, 'L');
    $pdf->Cell($colWidths[4], $rowHeight, substr($presentacion, 0, 18), 1, 0, 'L');
    $pdf->Cell($colWidths[5], $rowHeight, $cantidad, 1, 0, 'C');
    $pdf->Cell($colWidths[6], $rowHeight, $costoUnit, 1, 0, 'R');
    $pdf->Cell($colWidths[7], $rowHeight, $subtotal, 1, 1, 'R');
    
    $linea++;
}

// Si esta completada, mostrar tabla de items recibidos
if ($estado === 'completada' && count($items) > 0) {
    $pdf->SetY($pdf->GetY() + 4);
    $pdf->SetDrawColor(200, 200, 200);
    $pdf->Line(15, $pdf->GetY(), 195, $pdf->GetY());
    
    $pdf->SetY($pdf->GetY() + 4);
    $pdf->SetFont('helvetica', 'B', 9);
    $pdf->Cell(0, 6, 'ITEMS RECIBIDOS', 0, 1, 'L');
    
    // Header
    $pdf->SetFillColor(240, 240, 240);
    $pdf->SetFont('helvetica', 'B', 8);
    $pdf->Cell(10, 7, '#', 1, 0, 'C', true);
    $pdf->Cell(60, 7, 'Nombre', 1, 0, 'C', true);
    $pdf->Cell(25, 7, 'Cant. Recibida', 1, 0, 'C', true);
    $pdf->Cell(30, 7, 'Costo Unit. Real', 1, 0, 'C', true);
    $pdf->Cell(30, 7, 'Costo Total Real', 1, 0, 'C', true);
    $pdf->Cell(40, 7, 'Estado', 1, 1, 'C', true);
    
    // Filas
    $pdf->SetFont('helvetica', '', 8);
    $linea = 1;
    
    foreach ($items as $item) {
        // Determinar nombre
        if ($item->inv_table === 'inventory_medication') {
            $nombre = $item->med_name ?? $item->item_name ?? '-';
        } elseif ($item->inv_table === 'inventory_device') {
            $nombre = $item->dev_name ?? $item->item_name ?? '-';
        } else {
            $nombre = $item->item_name ?? '-';
        }
        
        $cantRec = number_format($item->cantidad_recibida ?? 0, 2);
        $costoReal = number_format($item->costo_unitario_real ?? 0, 2);
        $costoTotalReal = number_format(($item->cantidad_recibida ?? 0) * ($item->costo_unitario_real ?? 0), 2);
        
        // Badge de estado del item
        $itemStatus = ($item->cantidad_recibida ?? 0) >= $item->cantidad_solicitada ? 'Completo' : 'Parcial';
        $itemRgb = ($item->cantidad_recibida ?? 0) >= $item->cantidad_solicitada 
            ? array(25, 135, 84) 
            : array(255, 193, 7);
        
        $pdf->Cell(10, 10, $linea, 1, 0, 'C');
        $pdf->Cell(60, 10, substr($nombre, 0, 35), 1, 0, 'L');
        $pdf->Cell(25, 10, $cantRec, 1, 0, 'C');
        $pdf->Cell(30, 10, $costoReal, 1, 0, 'R');
        $pdf->Cell(30, 10, $costoTotalReal, 1, 0, 'R');
        
        $pdf->SetFillColor($itemRgb[0], $itemRgb[1], $itemRgb[2]);
        $pdf->SetTextColor(255, 255, 255);
        $pdf->Cell(40, 10, $itemStatus, 1, 1, 'C', true);
        $pdf->SetTextColor(0, 0, 0);
        
        $linea++;
    }
}

// Footer
$pdf->SetY(-25);
$pdf->SetDrawColor(102, 126, 234);
$pdf->Line(15, $pdf->GetY(), 195, $pdf->GetY());

$pdf->SetY($pdf->GetY() + 3);
$pdf->SetFont('helvetica', 'I', 8);
$pdf->SetTextColor(100, 100, 100);
$generatedBy = 'Generado por: ' . trim(($solicitud->cb_name ?? 'Sistema') . ' ' . ($solicitud->cb_lastname ?? '')) . ' | ' . date('d/m/Y H:i:s');
$pdf->Cell(0, 5, $generatedBy, 0, 1, 'C');
$pdf->Cell(0, 5, 'Cedimik', 0, 1, 'C');

// Output
$pdf->Output('SolicitudCompra-' . $id . '.pdf', 'I');
