<?php

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/db.php';

if ($_SESSION['role'] != 'admin')
{
    die("Access Denied");
}

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

if ($id <= 0)
{
    header("Location: manage_equipment.php");
    exit();
}

/*
|--------------------------------------------------------------------------
| Check Equipment Exists
|--------------------------------------------------------------------------
*/

$check = mysqli_prepare(
    $conn,
    "SELECT id
     FROM equipment_master
     WHERE id=?"
);

mysqli_stmt_bind_param(
    $check,
    "i",
    $id
);

mysqli_stmt_execute($check);

$result = mysqli_stmt_get_result($check);

if (mysqli_num_rows($result) == 0)
{
    mysqli_stmt_close($check);

    header("Location: manage_equipment.php");
    exit();
}

mysqli_stmt_close($check);

/*
|--------------------------------------------------------------------------
| Delete Equipment
|--------------------------------------------------------------------------
*/

$stmt = mysqli_prepare(
    $conn,
    "DELETE FROM equipment_master
     WHERE id=?"
);

if (!$stmt)
{
    die("Prepare Error : " . mysqli_error($conn));
}

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

if (mysqli_stmt_execute($stmt))
{
    mysqli_stmt_close($stmt);
    mysqli_close($conn);

    header("Location: manage_equipment.php?deleted=1");
    exit();
}
else
{
    die("Delete Failed : " . mysqli_stmt_error($stmt));
}
?>