<?php
session_start();

require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../libs/phpqrcode/qrlib.php";

/* ==========================
   SECURITY
========================== */
if (
    !isset($_SESSION['user_id']) ||
    $_SESSION['role'] !== 'admin'
) {
    header("Location: ../items.php");
    exit();
}

/* ==========================
   GET EQUIPMENT
========================== */
$id = intval($_GET['id'] ?? 0);

if ($id <= 0) {
    die("Invalid equipment ID");
}

$stmt = mysqli_prepare(
    $conn,
    "SELECT id, qr_code
     FROM equipment
     WHERE id = ?"
);

mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);

$result = mysqli_stmt_get_result($stmt);
$equipment = mysqli_fetch_assoc($result);

if (!$equipment) {
    die("Equipment not found");
}

/* ==========================
   DELETE OLD QR (OPTIONAL)
========================== */
if (!empty($equipment['qr_code'])) {

    $oldFile =
        __DIR__ .
        "/../assets/qr_codes/" .
        $equipment['qr_code'];

    if (file_exists($oldFile)) {
        unlink($oldFile);
    }
}

/* ==========================
   GENERATE NEW QR
========================== */

$baseURL = "https://qrcare.priorisys.com/";

$qrData =
    $baseURL .
    "equipment/equipment_details.php?id=" .
    $id;

/* use timestamp so browser won't cache old QR */
$qrFileName =
    "equipment_" .
    $id .
    "_" .
    time() .
    ".png";

$qrFilePath =
    __DIR__ .
    "/../assets/qr_codes/" .
    $qrFileName;

QRcode::png(
    $qrData,
    $qrFilePath,
    QR_ECLEVEL_H,
    6
);

/* ==========================
   UPDATE DATABASE
========================== */

$update = mysqli_prepare(
    $conn,
    "UPDATE equipment
     SET qr_code = ?
     WHERE id = ?"
);

mysqli_stmt_bind_param(
    $update,
    "si",
    $qrFileName,
    $id
);

mysqli_stmt_execute($update);

/* ==========================
   RETURN
========================== */

header(
    "Location: equipment_details.php?id=" .
    $id .
    "&qr=regenerated"
);

exit();