<?php

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

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

if ($_SERVER['REQUEST_METHOD'] != 'POST')
{
    header("Location: manage_equipment.php");
    exit();
}

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

$equipment_name = trim($_POST['equipment_name'] ?? '');
$display_order  = (int)($_POST['display_order'] ?? 1);
$status         = trim($_POST['status'] ?? 'Active');

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

/*
|--------------------------------------------------------------------------
| Check duplicate equipment name
|--------------------------------------------------------------------------
*/

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

mysqli_stmt_bind_param(
    $check,
    "si",
    $equipment_name,
    $id
);

mysqli_stmt_execute($check);

$result = mysqli_stmt_get_result($check);

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

    echo "
    <script>
        alert('Equipment name already exists.');
        history.back();
    </script>
    ";
    exit();
}

mysqli_stmt_close($check);

/*
|--------------------------------------------------------------------------
| Update equipment
|--------------------------------------------------------------------------
*/

$stmt = mysqli_prepare(
    $conn,
    "UPDATE equipment_master
     SET
        equipment_name=?,
        display_order=?,
        status=?
     WHERE id=?"
);

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

mysqli_stmt_bind_param(
    $stmt,
    "sisi",
    $equipment_name,
    $display_order,
    $status,
    $id
);

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

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