<?php

declare(strict_types=1);

require_once __DIR__ . '/../core/web_bootstrap.php';
require_once __DIR__ . '/../core/permissions.php';

/* SESSION CHECK */
if (empty($_SESSION['user']) || empty($_SESSION['api_token'])) {
    header('Location: login.php');
    exit;
}

$user = $_SESSION['user'];

/* RBAC CHECK */
if (!can($user, 'role_permissions', 'edit', $pdo)) {
    http_response_code(403);
    die('Access denied.');
}

/* LOAD ROLES & MODULES */
$roles = $pdo->query("
    SELECT role_key, role_name 
    FROM roles 
    ORDER BY role_name
")->fetchAll(PDO::FETCH_ASSOC);

$modules = $pdo->query("
    SELECT module_key, module_name 
    FROM modules 
    ORDER BY module_name
")->fetchAll(PDO::FETCH_ASSOC);

?>

<?php require 'partials/header.php'; ?>
<?php require 'partials/nav.php'; ?>

<h3>Role Permission Editor</h3>

<select id="roleSelect" class="form-select mb-3" onchange="loadPermissions()">
<?php foreach ($roles as $r): ?>
<option value="<?= htmlspecialchars($r['role_key']) ?>">
    <?= htmlspecialchars($r['role_name']) ?>
</option>
<?php endforeach; ?>
</select>

<table class="table table-bordered">
<thead>
<tr>
<th>Module</th>
<th>View</th>
<th>Create</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="permissionTable"></tbody>
</table>

<button class="btn btn-success" onclick="savePermissions()">Save Changes</button>

<script>
const token = '<?= htmlspecialchars($_SESSION['api_token'], ENT_QUOTES, 'UTF-8') ?>';

function escapeHtml(text) {
    if (!text) return '';
    return text
        .toString()
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

function loadPermissions() {

    const role = document.getElementById('roleSelect').value;

    fetch('/api/admin/get_role_permissions.php?role=' + encodeURIComponent(role), {
        headers: { 'Authorization': 'Bearer ' + token }
    })
    .then(r => r.json())
    .then(data => {

        if (!data.success) {
            alert(data.message);
            return;
        }

        let rows = '';

        data.data.permissions.forEach(p => {

            rows += `
            <tr>
                <td>${escapeHtml(p.module_name)}</td>
                <td><input type="checkbox" data-module="${p.module_key}" data-type="view" ${p.can_view ? 'checked':''}></td>
                <td><input type="checkbox" data-module="${p.module_key}" data-type="create" ${p.can_create ? 'checked':''}></td>
                <td><input type="checkbox" data-module="${p.module_key}" data-type="edit" ${p.can_edit ? 'checked':''}></td>
                <td><input type="checkbox" data-module="${p.module_key}" data-type="delete" ${p.can_delete ? 'checked':''}></td>
            </tr>
            `;
        });

        document.getElementById('permissionTable').innerHTML = rows;
    });
}

function savePermissions() {

    const role = document.getElementById('roleSelect').value;
    const rows = document.querySelectorAll('#permissionTable input');

    const updates = {};

    rows.forEach(cb => {
        const module = cb.dataset.module;
        const type = cb.dataset.type;

        if (!updates[module]) updates[module] = {};
        updates[module][type] = cb.checked ? 1 : 0;
    });

    fetch('/api/admin/save_role_permissions.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        },
        body: JSON.stringify({ role, updates })
    })
    .then(r => r.json())
    .then(data => {
        alert(data.message);
    });
}

loadPermissions();
</script>

<?php require 'partials/footer.php'; ?>