<?php
require_once __DIR__ . '/db.php';
require_login();
require_roles(['Pengguna Biasa', 'Admin Audit', 'Pentadbir Sistem']);
require_department_access($conn, 'senarai_pengguna', 'update');

$currentUserId = (int) ($_SESSION['user_id'] ?? 0);
$targetUserId = (int) ($_POST['user_id'] ?? 0);
$targetStatus = trim($_POST['target_status'] ?? '');

if ($targetUserId <= 0 || !in_array($targetStatus, ['active', 'inactive'], true)) {
    header('Location: senarai_pengguna.php?error=invalid');
    exit();
}

if ($targetUserId === $currentUserId) {
    header('Location: senarai_pengguna.php?error=self_status');
    exit();
}

$stmt = $conn->prepare("SELECT nama, approval_status FROM users WHERE id = ? LIMIT 1");
$stmt->bind_param('i', $targetUserId);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    header('Location: senarai_pengguna.php?error=not_found');
    exit();
}

if ($targetStatus === 'active' && ($user['approval_status'] ?? '') !== 'active') {
    header('Location: senarai_pengguna.php?error=approval_required');
    exit();
}

if ($targetStatus === 'active') {
    $update = $conn->prepare("UPDATE users SET account_status = 'active', deactivated_at = NULL WHERE id = ?");
    $update->bind_param('i', $targetUserId);
} else {
    $update = $conn->prepare("UPDATE users SET account_status = 'inactive', deactivated_at = NOW() WHERE id = ?");
    $update->bind_param('i', $targetUserId);
}

$update->execute();
add_current_user_log($conn, 'Mengubah status pengguna ' . ($user['nama'] ?? 'Tidak Diketahui') . ' kepada ' . ($targetStatus === 'active' ? 'Aktif' : 'Tidak Aktif'));
header('Location: senarai_pengguna.php?success=status_updated');
exit();
