<?php
session_start();
require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../config/app.php"; // BASE_URL

// 🔒 Security check
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: " . BASE_URL . "login.php");
    exit();
}

// 🔎 Validate ID
$id = intval($_GET['id'] ?? 0);

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

// 🔍 Check if equipment exists
$stmt = mysqli_prepare($conn, "SELECT id, status 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.");
}

// ⚠️ Already active check
if ($equipment['status'] === 'Active') {
    header("Location: equipment_details.php?id=$id&already_active=1");
    exit();
}

// 🔄 Update status to Active
$update = mysqli_prepare($conn, "
    UPDATE equipment 
    SET status = 'Active' 
    WHERE id = ?
");

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

if (mysqli_stmt_execute($update)) {
    header("Location: equipment_details.php?id=$id&reactivated=1");
    exit();
} else {
    die("Failed to reactivate equipment.");
}