<?php
session_start();
include 'php/db_connection.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

require __DIR__ . '/vendor-barcode/autoload.php';
require __DIR__ . '/pdf/fpdf.php';

use Picqer\Barcode\BarcodeGeneratorPNG;

$con->set_charset("utf8mb4");

$search = $_GET['search'] ?? '';
if (!$search) {
    die("Provide Product ID. Example: ?search=2503");
}

$stmt = $con->prepare(
    "SELECT Product_id AS id, name AS product_name 
     FROM product WHERE Product_id = ?"
);
$stmt->bind_param("s", $search);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    die("No product found");
}

$product = $res->fetch_assoc();

/* ===== Label Size ===== */
$labelWidth  = 38.1;   // 1.5 inch (width)
$labelHeight = 25.4;   // 1 inch (height)

/* ===== Safe Margin ===== */
$margin = 0; // margin in mm

/* ===== Create PDF in Landscape ===== */
$pdf = new FPDF('L', 'mm', [$labelWidth, $labelHeight]);
$pdf->SetMargins(0, 0, 0);
$pdf->SetAutoPageBreak(false);
$pdf->AddPage();

/* ===== Content Area ===== */
$contentWidth  = $labelWidth - 2 * $margin;
$contentHeight = $labelHeight - 2 * $margin;

/* ===== Font Settings ===== */
$pdf->SetFont('Arial', '', 9);

/* ===== Barcode Generation ===== */
$generator = new BarcodeGeneratorPNG();
$barcodeData = $generator->getBarcode(
    $product['id'],
    $generator::TYPE_CODE_128
);

$tempBarcode = __DIR__ . '/temp_barcode.png';
file_put_contents($tempBarcode, $barcodeData);

/* ===== Layout Heights ===== */
$nameHeight = 6;   // Product Name height
$idHeight   = 6;   // Product ID height
$spacing    = 1;   // Space between barcode and text

$barcodeHeight = $contentHeight - ($nameHeight + $idHeight + 2 * $spacing);
if ($barcodeHeight < 5) $barcodeHeight = 5; // Minimum barcode height

/* ===== Start Y ===== */
$startY = $margin;

/* ===== Product Name ===== */
$pdf->SetXY($margin, $startY);
$pdf->MultiCell($contentWidth, $nameHeight, $product['product_name'], 0, 'C');

/* ===== Barcode ===== */
$barcodeWidth = $contentWidth * 0.80; // 95% width to fit inside
$barcodeX = $margin + ($contentWidth - $barcodeWidth) / 2; // Center barcode X
$pdf->Image(
    $tempBarcode,
    $barcodeX,
    $pdf->GetY() + $spacing,
    $barcodeWidth,
    $barcodeHeight
);

/* ===== Product ID ===== */
$pdf->SetY($pdf->GetY() + $barcodeHeight + $spacing);
$pdf->Cell($contentWidth, $idHeight, "ID: ".$product['id'], 0, 0, 'C');

/* ===== Cleanup ===== */
unlink($tempBarcode);

/* ===== Output PDF ===== */
$pdf->Output('I', 'barcode_label.pdf');
exit;
?>