<?php
include 'config.php';
checkLogin();
require_once 'tcpdf/tcpdf.php';

if (!isset($_GET['ids']) || trim($_GET['ids']) === '') {
    die("No serials selected");
}

$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);

$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;

$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'  => false,
    'fitwidth' => true,
    'border'   => false,
];

$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
    $pdf->Rect(0.5, 0.5, 36.5, 24);

    $left_text = strtoupper($left['brand'] . ' ' . $left['model']);
    $left_font = (strlen($left_text) > 28) ? 5.5 : 7;
    $pdf->SetFont('helvetica', 'B', $left_font);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->SetXY(0, 3);
    $pdf->Cell(37.5, 4, $left_text, 0, 0, 'C');

    $pdf->write1DBarcode($left['serial_number'], 'C128', 2, 10, 33, 6, 0.27, $style, 'N');

    $pdf->SetFont('helvetica', 'B', 7);
    $pdf->SetXY(0, 17);
    $pdf->Cell(37.5, 5, $left['serial_number'], 0, 0, 'C');

    // RIGHT LABEL
    if ($right) {
        $pdf->Rect(38, 0.5, 36.5, 24);

        $right_text = strtoupper($right['brand'] . ' ' . $right['model']);
        $right_font = (strlen($right_text) > 28) ? 5.5 : 7;
        $pdf->SetFont('helvetica', 'B', $right_font);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->SetXY(37.5, 3);
        $pdf->Cell(37.5, 4, $right_text, 0, 0, 'C');

        $pdf->write1DBarcode($right['serial_number'], 'C128', 39.5, 10, 33, 6, 0.27, $style, 'N');

        $pdf->SetFont('helvetica', 'B', 7);
        $pdf->SetXY(37.5, 17);
        $pdf->Cell(37.5, 5, $right['serial_number'], 0, 0, 'C');
    }
}

$id_list_for_update = implode(',', $ids);
$conn->query("UPDATE laptop_serials SET printed = 1, printed_at = NOW() WHERE id IN ($id_list_for_update)");

$pdf->Output('bulk_labels_2up_37_5x25.pdf', 'I');
