<?php
session_start();
if (!isset($_SESSION['logged_in'])) {
    header('Location: login.php');
    exit;
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/helpers.php';

/* Permission */
if (!can('users','delete')) {
    die('Access Denied');
}

$user_id = (int)($_GET['id'] ?? 0);
if ($user_id <= 0) {
    die('Invalid User ID');
}

/* Fetch user */
$stmt = $pdo->prepare("
    SELECT user_id, role_id, status
    FROM users
    WHERE user_id = ?
");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    die('User not found');
}

/* 🚨 Protection: role_id = 1 cannot be disabled */
if ((int)$user['role_id'] === 1) {
    die('This user cannot be disabled (System Administrator)');
}

/* Toggle status */
$new_status = ($user['status'] === 'active') ? 'inactive' : 'active';

$upd = $pdo->prepare("
    UPDATE users
    SET status = ?
    WHERE user_id = ?
");
$upd->execute([$new_status, $user_id]);

/* (اختياري) تسجيل العملية في سجل العمليات */
if (function_exists('logOperation')) {
    logOperation(
        'users',
        $user_id,
        'status_change',
        'status',
        $user['status'],
        $new_status
    );
}

/* Redirect back */
header('Location: users.php');
exit;
