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

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

if (!in_array($bahagian, audit_bahagian_list(), true)) {
    header('Location: capaian_pengguna.php?error=invalid_unit');
    exit();
}

$currentPermissions = [];
$currentStmt = $conn->prepare("
    SELECT module_key, can_create, can_read, can_update, can_delete, can_rollback
    FROM department_access_permissions
    WHERE jabatan = ?
");
$currentStmt->bind_param('s', $bahagian);
$currentStmt->execute();
foreach ($currentStmt->get_result()->fetch_all(MYSQLI_ASSOC) as $row) {
    $currentPermissions[$row['module_key']] = [
        'can_create' => (int) $row['can_create'],
        'can_read' => (int) $row['can_read'],
        'can_update' => (int) $row['can_update'],
        'can_delete' => (int) $row['can_delete'],
        'can_rollback' => (int) $row['can_rollback'],
    ];
}

$snapshot = [];
foreach ($modules as $moduleKey => $moduleLabel) {
    $snapshot[$moduleKey] = $currentPermissions[$moduleKey] ?? [
        'can_create' => 0,
        'can_read' => 0,
        'can_update' => 0,
        'can_delete' => 0,
        'can_rollback' => 0,
    ];
}
$snapshotJson = json_encode($snapshot);
$updatedBy = current_user_id();

$conn->begin_transaction();

$rollbackStmt = $conn->prepare("
    INSERT INTO department_access_permission_rollbacks (jabatan, snapshot, created_by)
    VALUES (?, ?, ?)
");
$rollbackStmt->bind_param('ssi', $bahagian, $snapshotJson, $updatedBy);
$rollbackStmt->execute();

$stmt = $conn->prepare("
    INSERT INTO department_access_permissions
        (jabatan, 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)
");

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('ssiiiiii', $bahagian, $moduleKey, $canCreate, $canRead, $canUpdate, $canDelete, $canRollback, $updatedBy);
    $stmt->execute();
}

$conn->commit();

add_current_user_log($conn, 'Mengemaskini capaian pengguna untuk bahagian ' . $bahagian);

header('Location: capaian_pengguna.php?bahagian=' . urlencode($bahagian) . '&success=saved');
exit();
