<?php

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

header('Content-Type: application/json');

if (($_SESSION['role'] ?? '') !== 'admin' || $_SERVER['REQUEST_METHOD'] !== 'POST' || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? ''))
{
    echo json_encode(['success' => false, 'message' => 'Invalid request.']);
    exit();
}

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

if ($id <= 0)
{
    echo json_encode(['success' => false, 'message' => 'Invalid unit.']);
    exit();
}

$check = mysqli_prepare($conn, 'SELECT id FROM unit_equipment WHERE unit_id=? LIMIT 1');
mysqli_stmt_bind_param($check, 'i', $id);
mysqli_stmt_execute($check);
$inUse = mysqli_num_rows(mysqli_stmt_get_result($check)) > 0;
mysqli_stmt_close($check);

if ($inUse)
{
    echo json_encode(['success' => false, 'message' => 'This unit has equipment assignments and cannot be deleted.']);
    exit();
}

$getUnit = mysqli_prepare(
    $conn,
    'SELECT unit_name, is_required
     FROM unit_master
     WHERE id=?'
);

mysqli_stmt_bind_param($getUnit, 'i', $id);
mysqli_stmt_execute($getUnit);

$unit = mysqli_fetch_assoc(
    mysqli_stmt_get_result($getUnit)
);

mysqli_stmt_close($getUnit);

if (!$unit)
{
    echo json_encode([
        'success'=>false,
        'message'=>'Unit not found.'
    ]);
    exit();
}

if ($unit['is_required'] === 'Yes')
{
    echo json_encode([
        'success'=>false,
        'message'=>'System units cannot be deleted.'
    ]);
    exit();
}

$stmt = mysqli_prepare($conn, 'DELETE FROM unit_master WHERE id=?');
mysqli_stmt_bind_param($stmt, 'i', $id);
$saved = mysqli_stmt_execute($stmt);
if ($saved)
{
    logActivity(
        $conn,
        'Unit Management',
        'Delete Unit',
        'Deleted unit "' .
        $unit['unit_name'] .
        '"'
    );
}
mysqli_stmt_close($stmt);

echo json_encode(['success' => $saved, 'message' => $saved ? 'Unit deleted successfully.' : 'Unable to delete the unit.']);

