<?php
header("Content-Type: application/pdf");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

require_once dirname(__DIR__) . '/vendor/tcpdf/tcpdf.php';
require_once dirname(__DIR__) . '/config/database.php';

$database = new Database();
$db = $database->getConnection();

$id_orden = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id_orden <= 0) {
    http_response_code(400);
    echo "ID de orden es requerido.";
    exit;
}

$config = [];
try {
    $stmtConf = $db->query("SELECT clave, valor FROM configuracion");
    if ($stmtConf) {
        while ($row = $stmtConf->fetch(PDO::FETCH_ASSOC)) {
            $config[$row['clave']] = $row['valor'];
        }
    }
} catch (Exception $e) {}

date_default_timezone_set($config['zona_horaria'] ?? 'America/Puerto_Rico');
$empresa_nombre = $config['empresa_nombre'] ?? 'Lavanderia y Sastreria PR';

function h($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function clean_tag($v) {
    return preg_replace('/[^A-Za-z0-9\-]/', '', (string)$v);
}

try {
    $columnCheck = $db->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'order_items' AND COLUMN_NAME IN ('tag_code', 'garment_count')");
    $columns = $columnCheck ? $columnCheck->fetchAll(PDO::FETCH_COLUMN) : [];
    if (!in_array('tag_code', $columns, true)) {
        $db->exec("ALTER TABLE order_items ADD COLUMN tag_code VARCHAR(40) NULL AFTER descripcion_item");
    }
    if (!in_array('garment_count', $columns, true)) {
        $db->exec("ALTER TABLE order_items ADD COLUMN garment_count INT NOT NULL DEFAULT 1 AFTER tag_code");
    }
} catch (Exception $e) {}

$stmt = $db->prepare("
    SELECT o.*, c.full_name AS cliente_nombre, c.phone AS cliente_telefono
    FROM orders o
    JOIN customers c ON c.id = o.customer_id
    WHERE o.id = ?
");
$stmt->execute([$id_orden]);
$orden = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$orden) {
    http_response_code(404);
    echo "Orden no encontrada";
    exit;
}

$stmtItems = $db->prepare("
    SELECT oi.id, oi.quantity, oi.descripcion_item, oi.tag_code, oi.garment_count,
           s.service_name AS servicio_nombre, s.unit
    FROM order_items oi
    JOIN services s ON s.id = oi.service_id
    WHERE oi.order_id = ?
    ORDER BY oi.id ASC
");
$stmtItems->execute([$id_orden]);
$items = $stmtItems->fetchAll(PDO::FETCH_ASSOC);

$labels = [];
$line = 1;
foreach ($items as $item) {
    $baseTag = trim($item['tag_code'] ?? '');
    if ($baseTag === '') {
        $baseTag = $orden['order_number'] . '-' . str_pad((string)$line, 2, '0', STR_PAD_LEFT);
        $upd = $db->prepare("UPDATE order_items SET tag_code = ? WHERE id = ?");
        $upd->execute([$baseTag, $item['id']]);
    }
    $count = max(1, (int)($item['garment_count'] ?? 1));
    for ($i = 1; $i <= $count; $i++) {
        $pieceTag = clean_tag($baseTag . '-P' . str_pad((string)$i, 2, '0', STR_PAD_LEFT));
        $labels[] = [
            'piece_tag' => $pieceTag,
            'base_tag' => clean_tag($baseTag),
            'line_number' => $line,
            'piece_number' => $i,
            'piece_total' => $count,
            'service' => $item['servicio_nombre'] ?? '',
            'note' => $item['descripcion_item'] ?? ''
        ];
    }
    $line++;
}

$size = $_GET['size'] ?? 'compact';
$isCompact = $size !== 'full';

// Compact laundry tags: 11/16" x 1/4" = 17.46mm x 6.35mm.
if ($isCompact) {
    $labelW = 17.46;
    $labelH = 6.35;
    $pdf = new TCPDF('L', 'mm', [$labelW, $labelH], true, 'UTF-8', false);
    $pdf->SetCreator('Laundry App');
    $pdf->SetTitle('Etiquetas de Prendas');
    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);
    $pdf->SetMargins(0, 0, 0);
    $pdf->SetAutoPageBreak(false);
    $perPage = 1;
} else {
    $pdf = new TCPDF('P', 'mm', 'LETTER', true, 'UTF-8', false);
    $pdf->SetCreator('Laundry App');
    $pdf->SetTitle('Etiquetas de Prendas');
    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);
    $pdf->SetMargins(8, 8, 8);
    $pdf->SetAutoPageBreak(false);
    $pdf->AddPage();

    $labelW = 63;
    $labelH = 31;
    $gapX = 4;
    $gapY = 4;
    $startX = 8;
    $startY = 8;
    $cols = 3;
    $rows = 8;
    $perPage = $cols * $rows;
}

if (count($labels) === 0) {
    $pdf->SetFont('helvetica', 'B', 14);
    $pdf->Cell(0, 10, 'No hay prendas para etiquetar.', 0, 1, 'C');
    $pdf->Output('etiquetas_prendas_'.$orden['order_number'].'.pdf', 'I');
    exit;
}

foreach ($labels as $idx => $label) {
    if ($isCompact) {
        $pdf->AddPage();
        $x = 0;
        $y = 0;
    } else if ($idx > 0 && $idx % $perPage === 0) {
        $pdf->AddPage();
    }
    if (!$isCompact) {
        $pos = $idx % $perPage;
        $col = $pos % $cols;
        $row = intdiv($pos, $cols);
        $x = $startX + $col * ($labelW + $gapX);
        $y = $startY + $row * ($labelH + $gapY);

        $pdf->SetDrawColor(11, 27, 63);
        $pdf->SetLineWidth(0.25);
        $pdf->Rect($x, $y, $labelW, $labelH);
    }

    if ($isCompact) {
        $orderShort = substr(str_replace('ORD-', '', $orden['order_number']), -5);
        $globalPiece = $idx + 1;
        $globalTotal = count($labels);
        $short = $orderShort . '-' . $globalPiece . '/' . $globalTotal;
        $barcodeValue = clean_tag($orderShort . '-' . $globalPiece . 'OF' . $globalTotal);
        $pdf->SetTextColor(11, 27, 63);
        $pdf->SetFont('helvetica', 'B', 3.7);
        $pdf->SetXY($x + 0.4, $y + 0.2);
        $pdf->Cell($labelW - 0.8, 1.7, $short, 0, 0, 'C');
        $style = [
            'position' => '',
            'align' => 'C',
            'stretch' => false,
            'fitwidth' => true,
            'cellfitalign' => '',
            'border' => false,
            'hpadding' => 'auto',
            'vpadding' => 'auto',
            'fgcolor' => [11, 27, 63],
            'bgcolor' => false,
            'text' => false
        ];
        $pdf->write1DBarcode($barcodeValue, 'C128', $x + 0.8, $y + 2.1, $labelW - 1.6, 3.65, 0.11, $style, 'N');
    } else {
        $pdf->SetFillColor(11, 27, 63);
        $pdf->Rect($x, $y, $labelW, 6, 'F');
        $pdf->SetTextColor(255, 255, 255);
        $pdf->SetFont('helvetica', 'B', 7);
        $pdf->SetXY($x + 2, $y + 1.2);
        $pdf->Cell($labelW - 4, 4, strtoupper($empresa_nombre), 0, 0, 'C');

        $pdf->SetTextColor(11, 27, 63);
        $pdf->SetFont('helvetica', 'B', 11);
        $pdf->SetXY($x + 2, $y + 7.5);
        $pdf->Cell($labelW - 4, 5, $label['piece_tag'], 0, 0, 'C');

        $pdf->SetFont('helvetica', '', 6.6);
        $pdf->SetXY($x + 2, $y + 12.5);
        $pdf->Cell($labelW - 4, 3.5, 'Orden: '.$orden['order_number'].' | Pieza '.$label['piece_number'].'/'.$label['piece_total'], 0, 0, 'C');
        $pdf->SetXY($x + 2, $y + 16);
        $pdf->Cell($labelW - 4, 3.5, 'Cliente: '.substr($orden['cliente_nombre'], 0, 28), 0, 0, 'C');
        $pdf->SetXY($x + 2, $y + 19.5);
        $pdf->Cell($labelW - 4, 3.5, substr($label['service'], 0, 32), 0, 0, 'C');

        $style = [
            'position' => '',
            'align' => 'C',
            'stretch' => false,
            'fitwidth' => true,
            'cellfitalign' => '',
            'border' => false,
            'hpadding' => 'auto',
            'vpadding' => 'auto',
            'fgcolor' => [11, 27, 63],
            'bgcolor' => false,
            'text' => false
        ];
        $pdf->write1DBarcode($label['piece_tag'], 'C128', $x + 5, $y + 23.5, $labelW - 10, 6, 0.22, $style, 'N');
    }
}

$pdf->Output('etiquetas_prendas_'.$orden['order_number'].'.pdf', 'I');
exit;
?>
