<?php
session_start();
require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../libs/phpqrcode/qrlib.php";

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

/* ===============================
   GET FORM DATA
=================================*/
$name           = trim($_POST['equipment_name'] ?? "");
$serial         = trim($_POST['serial_number'] ?? "");
$category       = trim($_POST['category'] ?? "");
$other_category = trim($_POST['other_category'] ?? "");
$department_id  = intval($_POST['department_id'] ?? 0);
$location       = trim($_POST['location'] ?? "");
$status         = trim($_POST['status'] ?? "Active");
$purchase_date  = $_POST['purchase_date'] ?? null;
$next_due_date  = $_POST['next_due_date'] ?? null;
$description    = trim($_POST['description'] ?? "");

/* ===============================
   BASIC VALIDATION
=================================*/
if (
    $name === "" ||
    $serial === "" ||
    $location === "" ||
    $status === "" ||
    $category === "" ||
    $department_id <= 0
) {
    $_SESSION['add_equipment_error'] = "Required fields are missing.";
    header("Location: ../items.php");
    exit();
}

/* ===============================
   HANDLE OTHER CATEGORY
=================================*/
if (str_starts_with($category, "Other_")) {
    if ($other_category === "") {
        $_SESSION['add_equipment_error'] = "Please specify the category.";
        header("Location: ../items.php");
        exit();
    }
    $finalCategory = $other_category;
} else {
    $finalCategory = $category;
}

/* ===============================
   CHECK DUPLICATE SERIAL
=================================*/
$check = mysqli_prepare($conn, "SELECT id FROM equipment WHERE serial_number = ?");
mysqli_stmt_bind_param($check, "s", $serial);
mysqli_stmt_execute($check);
mysqli_stmt_store_result($check);

if (mysqli_stmt_num_rows($check) > 0) {
    $_SESSION['add_equipment_error'] = "Serial number already exists.";
    header("Location: ../items.php");
    exit();
}

/* ===============================
   HANDLE IMAGE UPLOAD
=================================*/
$image_name = "placeholder.png";

if (isset($_FILES['equipment_image']) && $_FILES['equipment_image']['error'] === UPLOAD_ERR_OK) {

    $fileTmpPath = $_FILES['equipment_image']['tmp_name'];
    $fileName    = $_FILES['equipment_image']['name'];
    $fileSize    = $_FILES['equipment_image']['size'];
    $fileExt     = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    $allowedExt  = ['jpg','jpeg','png','gif'];

    if (!in_array($fileExt, $allowedExt)) {
        $_SESSION['add_equipment_error'] = "Invalid image format.";
        header("Location: ../items.php");
        exit();
    }

    if ($fileSize > 2 * 1024 * 1024) {
        $_SESSION['add_equipment_error'] = "Image must be under 2MB.";
        header("Location: ../items.php");
        exit();
    }

    $newFileName = "equipment_" . time() . "." . $fileExt;
    $destPath = __DIR__ . "/../assets/images/" . $newFileName;

    if (move_uploaded_file($fileTmpPath, $destPath)) {
        $image_name = $newFileName;
    }
}

/* ===============================
   INSERT EQUIPMENT
=================================*/
$stmt = mysqli_prepare($conn, "
    INSERT INTO equipment 
    (equipment_name, category, purchase_date, next_due_date, description,
     serial_number, location, status, department_id, image)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");

mysqli_stmt_bind_param(
    $stmt,
    "ssssssssis",
    $name,
    $finalCategory,
    $purchase_date,
    $next_due_date,
    $description,
    $serial,
    $location,
    $status,
    $department_id,
    $image_name
);

if (!mysqli_stmt_execute($stmt)) {
    $_SESSION['add_equipment_error'] = "Database error: " . mysqli_stmt_error($stmt);
    header("Location: ../items.php");
    exit();
}

$equipment_id = mysqli_insert_id($conn);

/* ===============================
   GENERATE QR CODE (FIXED)
=================================*/
$qr_folder = __DIR__ . "/../assets/qr_codes/";
if (!is_dir($qr_folder)) {
    mkdir($qr_folder, 0777, true);
}

/* ✅ FIXED BASE URL */
$baseURL = "https://qrcare.priorisys.com/";

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

$qr_file_name = "equipment_" . $equipment_id . ".png";
$qr_file_path = $qr_folder . $qr_file_name;

QRcode::png($qr_data, $qr_file_path, QR_ECLEVEL_H, 6);

/* ===============================
   UPDATE QR FIELD
=================================*/
$update = mysqli_prepare($conn, "UPDATE equipment SET qr_code = ? WHERE id = ?");
mysqli_stmt_bind_param($update, "si", $qr_file_name, $equipment_id);
mysqli_stmt_execute($update);

/* ===============================
   SUCCESS
=================================*/
$_SESSION['add_equipment_success'] = "Equipment added successfully.";
header("Location: ../items.php");
exit();
?>