<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/includes/conn.php';
require_once __DIR__ . '/includes/functions.php';

requireRole('admin');

// Ensure PDO connection exists
if (!isset($pdo) || !($pdo instanceof PDO)) {
    die('Database connection not initialized.');
}

$user_id = (int)($_GET['id'] ?? 0);
$action  = $_GET['action'] ?? '';

if ($user_id <= 0 || !in_array($action, ['disable', 'enable'], true)) {
    header('Location: users.php?error=invalid');
    exit;
}

// Prevent admin from disabling own account
if ($user_id === (int)$_SESSION['user_id']) {
    header('Location: users.php?error=self_disable');
    exit;
}

$status = ($action === 'disable') ? 'disabled' : 'active';

$stmt = $pdo->prepare(
    "UPDATE users SET status = :status WHERE id = :id"
);

$stmt->execute([
    ':status' => $status,
    ':id'     => $user_id
]);

header('Location: admin.php');
exit;