<?php
include 'config.php';
checkLogin();
require_once 'tcpdf/tcpdf.php';

/**
 * bulk_print_selected.php
 * Prints selected serial IDs on 2-up labels:
 * - Label size: 37.5mm x 25mm
 * - Page size: 75mm x 25mm (2 labels side by side)
 * - Left label = serial N
 * - Right label = serial N+1 (if exists)
 */

if (!isset($_GET['ids']) || trim($_GET['ids']) === '') {
    die("No serials selected");
}

/* ===============================
   PARSE AND SANITIZE IDS
================================ */
$raw_ids = explode(',', $_GET['ids']);
$ids = [];

foreach ($raw_ids as $rid) {
    $id = (int)$rid;
    if ($id > 0) {
        $ids[] = $id;
    }
}

if (empty($ids)) {
    die("No valid serial IDs");
}

$id_list = implode(',', $ids);

/* ===============================
   FETCH SERIALS IN ORDER
================================ */
$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 for printing");
}

$rows = [];
while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
}

/* ===============================
   TCPDF SETTINGS (75mm x 25mm 2-UP)
================================ */
$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);

$style = [
    'align'    => 'C',
    'stretch'  => true,
    'fitwidth' => true,
    'border'   => false,
];

/* ===============================
   RENDER PAGES (2-UP: LEFT & RIGHT)
================================ */
$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 ----------
    // Border (optional)
    $pdf->Rect(0.5, 0.5, 36.5, 24);

    // Model text
    $pdf->SetFont('helvetica', 'B', 7);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->SetXY(0, 3);
    $pdf->Cell(37.5, 4, strtoupper($left['brand'] . ' ' . $left['model']), 0, 0, 'C');

    // Barcode
    $pdf->write1DBarcode(
        $left['serial_number'],
        'C128',
        2,      // X
        10,     // Y
        33,     // width
        6,      // height
        0.30,   // thickness
        $style,
        'N'
    );

    // Serial text
    $pdf->SetFont('helvetica', 'B', 7);
    $pdf->SetXY(0, 17);
    $pdf->Cell(37.5, 5, $left['serial_number'], 0, 0, 'C');

    // ---------- RIGHT LABEL (if exists) ----------
    if ($right) {
        // Border (optional)
        $pdf->Rect(38, 0.5, 36.5, 24); // 37.5 + 0.5 offset

        // Model text
        $pdf->SetFont('helvetica', 'B', 7);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->SetXY(37.5, 3);
        $pdf->Cell(37.5, 4, strtoupper($right['brand'] . ' ' . $right['model']), 0, 0, 'C');

        // Barcode
        $pdf->write1DBarcode(
            $right['serial_number'],
            'C128',
            39.5,   // X
            10,     // Y
            33,     // width
            6,      // height
            0.30,   // thickness
            $style,
            'N'
        );

        // Serial text
        $pdf->SetFont('helvetica', 'B', 7);
        $pdf->SetXY(37.5, 17);
        $pdf->Cell(37.5, 5, $right['serial_number'], 0, 0, 'C');
    }
}

/* ===============================
   MARK ALL AS PRINTED
================================ */
$id_list_for_update = implode(',', $ids);
$conn->query(
    "UPDATE laptop_serials
     SET printed = 1, printed_at = NOW()
     WHERE id IN ($id_list_for_update)"
);

/* ===============================
   OUTPUT PDF (PREVIEW IN BROWSER)
================================ */
$pdf->Output('bulk_labels_2up_37_5x25.pdf', 'I');
