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

$id = (int)($_GET['id'] ?? 0);

$stmt = $conn->prepare(
    "SELECT s.serial_number, m.brand, m.model
     FROM laptop_serials s
     JOIN laptop_models m ON s.model_id = m.id
     WHERE s.id=?"
);
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($serial, $brand, $model);
$stmt->fetch();
$stmt->close();

if (!$serial) {
    die("Invalid serial");
}

$pdf = new TCPDF('L', 'mm', [34, 25], true, 'UTF-8', false);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(1.2, 1.2, 1.2);
$pdf->SetAutoPageBreak(false, 0);
$pdf->AddPage();

$pdf->Rect(0.8, 0.8, 32.4, 23.4);

/* LAPTOP MODEL */
$label_text = strtoupper($brand . ' ' . $model);
$font_size = (strlen($label_text) > 28) ? 5.5 : 7;
$pdf->SetFont('helvetica', 'B', $font_size);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetXY(1.2, 1.5);
$pdf->Cell(31.6, 5, $label_text, 0, 1, 'C');

if (strlen($label_text) > 36) {
    $pdf->SetFont('helvetica', 'B', 5);
    $pdf->SetXY(1.2, 1.5);
    $pdf->MultiCell(31.6, 3.5, $label_text, 0, 'C', false, 1, '', '', true);
}

/* BARCODE */
$style = [
    'align'    => 'C',
    'stretch'  => false,
    'fitwidth' => true,
    'border'   => false,
];

$pdf->write1DBarcode(
    $serial,
    'C128',
    1.5,
    8.0,
    31,
    6,
    0.27,
    $style,
    'N'
);

/* SERIAL NUMBER */
$pdf->SetFont('helvetica', 'B', 7);
$pdf->SetXY(1.2, 17);
$pdf->Cell(31.6, 5, $serial, 0, 0, 'C');

/* MARK AS PRINTED */
$update = $conn->prepare(
    "UPDATE laptop_serials
     SET printed = 1, printed_at = NOW()
     WHERE id = ?"
);
$update->bind_param("i", $id);
$update->execute();
$update->close();

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