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

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

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

$rollbackStmt = $conn->prepare("
    SELECT id, snapshot
    FROM department_access_permission_rollbacks
    WHERE jabatan = ? AND restored_at IS NULL
    ORDER BY id DESC
    LIMIT 1
");
$rollbackStmt->bind_param('s', $bahagian);
$rollbackStmt->execute();
$rollback = $rollbackStmt->get_result()->fetch_assoc();

if (!$rollback) {
    header('Location: capaian_pengguna.php?bahagian=' . urlencode($bahagian) . '&error=no_rollback');
    exit();
}

$snapshot = json_decode($rollback['snapshot'], true);
if (!is_array($snapshot)) {
    header('Location: capaian_pengguna.php?bahagian=' . urlencode($bahagian) . '&error=rollback_failed');
    exit();
}

$updatedBy = current_user_id();
$rollbackId = (int) $rollback['id'];

$conn->begin_transaction();

$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);
    $row = is_array($snapshot[$moduleKey] ?? null) ? $snapshot[$moduleKey] : [];
    $canCreate = in_array('create', $allowedActions, true) && !empty($row['can_create']) ? 1 : 0;
    $canRead = in_array('read', $allowedActions, true) && !empty($row['can_read']) ? 1 : 0;
    $canUpdate = in_array('update', $allowedActions, true) && !empty($row['can_update']) ? 1 : 0;
    $canDelete = in_array('delete', $allowedActions, true) && !empty($row['can_delete']) ? 1 : 0;
    $canRollback = in_array('rollback', $allowedActions, true) && !empty($row['can_rollback']) ? 1 : 0;
    $stmt->bind_param('ssiiiiii', $bahagian, $moduleKey, $canCreate, $canRead, $canUpdate, $canDelete, $canRollback, $updatedBy);
    $stmt->execute();
}

$markStmt = $conn->prepare("
    UPDATE department_access_permission_rollbacks
    SET restored_by = ?, restored_at = NOW()
    WHERE id = ?
");
$markStmt->bind_param('ii', $updatedBy, $rollbackId);
$markStmt->execute();

$conn->commit();

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

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