<?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: add_equipment.php");
    exit();
}

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

if ($equipment_name == '')
{
    header("Location: add_equipment.php");
    exit();
}

/*
|--------------------------------------------------------------------------
| Check Duplicate Equipment
|--------------------------------------------------------------------------
*/

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

mysqli_stmt_bind_param(
    $check,
    "s",
    $equipment_name
);

mysqli_stmt_execute($check);

$result = mysqli_stmt_get_result($check);

if (mysqli_num_rows($result) > 0)
{
    header("Location: add_equipment.php?exists=1");
    exit();
}

mysqli_stmt_close($check);

/*
|--------------------------------------------------------------------------
| Save Equipment
|--------------------------------------------------------------------------
*/

$stmt = mysqli_prepare(
    $conn,
    "INSERT INTO equipment_master
    (
        equipment_name,
        display_order,
        status
    )
    VALUES
    (?,?,?)"
);

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

mysqli_stmt_bind_param(
    $stmt,
    "sis",
    $equipment_name,
    $display_order,
    $status
);

if (mysqli_stmt_execute($stmt))
{
    header("Location: manage_equipment.php?added=1");
    exit();
}
else
{
    die("Save Failed : " . mysqli_stmt_error($stmt));
}

mysqli_stmt_close($stmt);
mysqli_close($conn);

?>