<?php
include 'config.php';
checkLogin();
require_once 'tcpdf/tcpdf.php';

/**
 * bulk_print_selected.php
 * 2-UP labels (37.5mm x 25mm each)
 * Page size: 75mm x 25mm
 * Mode B: Left = N, Right = N+1
 * Supports ids in two formats:
 *  - ids=1,2,3
 *  - ids[]=1&ids[]=2
 */

/* ===============================
   READ IDS (CSV OR ARRAY)
================================ */
$ids = [];

if (isset($_GET['ids'])) {
    if (is_array($_GET['ids'])) {
        // ids[]=1&ids[]=2
        foreach ($_GET['ids'] as $rid) {
            $id = (int)$rid;
            if ($id > 0) $ids[] = $id;
        }
    } else {
        // ids=1,2,3
        $raw_ids = explode(',', $_GET['ids']);
        foreach ($raw_ids as $rid) {
            $id = (int)$rid;
            if ($id > 0) $ids[] = $id;
        }
    }
}

$ids = array_values(array_unique($ids));

if (empty($ids)) {
    die("No valid serial IDs");
}

$id_list = implode(',', $ids);

/* ===============================
   FETCH SERIAL DATA
================================ */
$sql = "
    SELECT s.id, s.serial_number, m.brand, m.model
    FROM laptop_serials s
    JOIN laptop_models m ON s.model_id = m.id
    WHERE s.id IN ($id_list)
    ORDER BY s.id ASC
";

$result = $conn->query($sql);
if (!$result || $result->num_rows == 0) {
    die("No serials found");
}

$rows = [];
while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
}

/* ===============================
   TCPDF SETTINGS
================================ */
$pdf = new TCPDF('L', 'mm', [75, 25], true, 'UTF-8', false);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(1, 1, 1);
$pdf->SetAutoPageBreak(false, 0);

/* Barcode style */
$style = [
    'align'    => 'C',
    'stretch'  => true,
    'fitwidth' => true,
    'border'   => false,
];

/* ===============================
   LAYOUT CONSTANTS
================================ */
$labelWidth  = 36.5;  // printable label area width
$labelHeight = 24;    // printable label area height
$gap = 2;             // ✅ space between columns (mm) - adjust here

/* ===============================
   PRINT 2-UP PAGES
================================ */
$count = count($rows);

for ($i = 0; $i < $count; $i += 2) {

    $left  = $rows[$i];
    $right = ($i + 1 < $count) ? $rows[$i + 1] : null;

    $pdf->AddPage();

    /* ---------- LEFT LABEL ---------- */
    $leftX = 0;

    // Border (optional)
    $pdf->Rect($leftX + 0.5, 0.5, $labelWidth, $labelHeight);

    // MODEL NAME (wrap to 2 lines automatically)
    $pdf->SetFont('helvetica', 'B', 7);
    $pdf->SetXY($leftX + 1, 2.5);
    $pdf->MultiCell(
        $labelWidth - 2,
        3.2,
        strtoupper($left['brand'] . ' ' . $left['model']),
        0,
        'C',
        false,
        1
    );

    // BARCODE
    $pdf->write1DBarcode(
        $left['serial_number'],
        'C128',
        $leftX + 2,
        10,
        33,
        6,
        0.30,
        $style,
        'N'
    );

    // SERIAL NUMBER
    $pdf->SetFont('helvetica', 'B', 7);
    $pdf->SetXY($leftX, 17);
    $pdf->Cell($labelWidth, 5, $left['serial_number'], 0, 0, 'C');

    /* ---------- RIGHT LABEL ---------- */
    if ($right) {
        $rightX = $labelWidth + $gap;

        // Border (optional)
        $pdf->Rect($rightX + 0.5, 0.5, $labelWidth, $labelHeight);

        // MODEL NAME (wrap to 2 lines automatically)
        $pdf->SetFont('helvetica', 'B', 7);
        $pdf->SetXY($rightX + 1, 2.5);
        $pdf->MultiCell(
            $labelWidth - 2,
            3.2,
            strtoupper($right['brand'] . ' ' . $right['model']),
            0,
            'C',
            false,
            1
        );

        // BARCODE
        $pdf->write1DBarcode(
            $right['serial_number'],
            'C128',
            $rightX + 2,
            10,
            33,
            6,
            0.30,
            $style,
            'N'
        );

        // SERIAL NUMBER
        $pdf->SetFont('helvetica', 'B', 7);
        $pdf->SetXY($rightX, 17);
        $pdf->Cell($labelWidth, 5, $right['serial_number'], 0, 0, 'C');
    }
}

/* ===============================
   MARK AS PRINTED
================================ */
$conn->query(
    "UPDATE laptop_serials
     SET printed = 1, printed_at = NOW()
     WHERE id IN ($id_list)"
);

/* ===============================
   OUTPUT (PREVIEW)
================================ */
// Ensure no extra output breaks PDF
if (ob_get_length()) { ob_end_clean(); }

$pdf->Output('bulk_labels_2up_37_5x25.pdf', 'I');
exit;
