<?php
require_once __DIR__ . '/db.php';
require_login();
require_roles(['Pentadbir Sistem']);

$userId = (int) ($_POST['user_id'] ?? 0);
$bahagian = trim($_POST['bahagian'] ?? '');
$postedPermissions = $_POST['permissions'] ?? [];
$modules = access_module_options();

$userStmt = $conn->prepare("SELECT id, nama, jabatan FROM users WHERE id = ? LIMIT 1");
$userStmt->bind_param('i', $userId);
$userStmt->execute();
$selectedUser = $userStmt->get_result()->fetch_assoc();

if (!$selectedUser) {
    header('Location: capaian_pengguna.php?error=invalid_user');
    exit();
}

if ($bahagian === '') {
    $bahagian = (string) ($selectedUser['jabatan'] ?? '');
}

if (!in_array($bahagian, audit_bahagian_list(), true) || (string) ($selectedUser['jabatan'] ?? '') !== $bahagian) {
    header('Location: capaian_pengguna.php?bahagian=' . urlencode($bahagian) . '&error=invalid_user#capaian-user');
    exit();
}

$stmt = $conn->prepare("
    INSERT INTO user_access_permissions
        (user_id, module_key, can_create, can_read, can_update, can_delete, can_rollback, updated_by)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE
        can_create = VALUES(can_create),
        can_read = VALUES(can_read),
        can_update = VALUES(can_update),
        can_delete = VALUES(can_delete),
        can_rollback = VALUES(can_rollback),
        updated_by = VALUES(updated_by)
");

$updatedBy = current_user_id();
foreach ($modules as $moduleKey => $moduleLabel) {
    $allowedActions = access_module_allowed_actions($moduleKey);
    $modulePermissions = is_array($postedPermissions[$moduleKey] ?? null) ? $postedPermissions[$moduleKey] : [];
    $canCreate = in_array('create', $allowedActions, true) && !empty($modulePermissions['create']) ? 1 : 0;
    $canRead = in_array('read', $allowedActions, true) && !empty($modulePermissions['read']) ? 1 : 0;
    $canUpdate = in_array('update', $allowedActions, true) && !empty($modulePermissions['update']) ? 1 : 0;
    $canDelete = in_array('delete', $allowedActions, true) && !empty($modulePermissions['delete']) ? 1 : 0;
    $canRollback = in_array('rollback', $allowedActions, true) && !empty($modulePermissions['rollback']) ? 1 : 0;
    $stmt->bind_param('isiiiiii', $userId, $moduleKey, $canCreate, $canRead, $canUpdate, $canDelete, $canRollback, $updatedBy);
    $stmt->execute();
}

add_current_user_log($conn, 'Mengemaskini capaian khusus pengguna ' . ($selectedUser['nama'] ?? ('ID ' . $userId)) . ' untuk bahagian ' . $bahagian);

header('Location: capaian_pengguna.php?bahagian=' . urlencode($bahagian) . '&user_id=' . $userId . '&success=user_saved#capaian-user');
exit();
