<?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);
$currentUserRole = current_user_role();
$targetUserId = (int) ($_POST['user_id'] ?? 0);
$targetRole = trim($_POST['target_role'] ?? '');

if ($targetUserId <= 0 || $targetRole === '') {
    header('Location: senarai_pengguna.php?error=invalid_role');
    exit();
}

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

$allowedRoles = $currentUserRole === 'Pentadbir Sistem'
    ? ['Pengguna Biasa', 'Admin Audit', 'Pentadbir Sistem']
    : ['Pengguna Biasa', 'Admin Audit'];

if (!in_array($targetRole, $allowedRoles, true)) {
    header('Location: senarai_pengguna.php?error=invalid_role');
    exit();
}

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

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

if ($currentUserRole === 'Admin Audit' && ($targetUser['role'] ?? '') === 'Pentadbir Sistem') {
    header('Location: senarai_pengguna.php?error=protected_system_admin');
    exit();
}

$update = $conn->prepare("UPDATE users SET role = ? WHERE id = ?");
$update->bind_param('si', $targetRole, $targetUserId);
$update->execute();

add_current_user_log($conn, 'Mengubah role pengguna ' . ($targetUser['nama'] ?? 'Tidak Diketahui') . ' daripada ' . ($targetUser['role'] ?? '-') . ' kepada ' . $targetRole);

header('Location: senarai_pengguna.php?success=role_updated');
exit();
