<?php

declare(strict_types=1);

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

/* ----------------------------------------------------------
   SESSION AUTH CHECK
---------------------------------------------------------- */

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

$user = $_SESSION['user'];

/* ----------------------------------------------------------
   RBAC CHECK
---------------------------------------------------------- */

if (!can($user, 'rsps', 'view', $pdo)) {
    http_response_code(403);
    die('Access denied.');
}

$canCreate = can($user, 'rsps', 'create', $pdo);
$canEdit   = can($user, 'rsps', 'edit', $pdo);

?>

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

<h3>RSP Management</h3>

<?php if ($canCreate): ?>
<div class="row mb-3">
    <div class="col-md-4">
        <input type="text" id="rspName" class="form-control" placeholder="New RSP Name">
    </div>
    <div class="col-md-2">
        <button class="btn btn-primary" onclick="createRSP()">Create</button>
    </div>
</div>
<?php endif; ?>

<table class="table table-bordered table-striped">
    <thead class="table-dark">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Status</th>
            <th>Companies</th>
            <?php if ($canEdit): ?>
                <th>Action</th>
            <?php endif; ?>
        </tr>
    </thead>
    <tbody id="rspTable"></tbody>
</table>

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

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 loadRSPs() {

    fetch('/api/admin/get_rsps.php', {
        headers: { 'Authorization': 'Bearer ' + token }
    })
    .then(res => res.json())
    .then(data => {

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

        let rows = '';
        const rsps = data.data.rsps || [];

        rsps.forEach(r => {

            rows += `
                <tr>
                    <td>${r.id}</td>
                    <td>${escapeHtml(r.name)}</td>
                    <td>
                        <span class="badge ${r.status === 'active' ? 'bg-success' : 'bg-danger'}">
                            ${escapeHtml(r.status)}
                        </span>
                    </td>
                    <td>${r.companies}</td>
            `;

            if (canEdit) {
                rows += `
                    <td>
                        <button class="btn btn-sm btn-warning"
                            onclick="toggleStatus(${r.id})">
                            Toggle
                        </button>
                    </td>
                `;
            }

            rows += `</tr>`;
        });

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

function createRSP() {

    if (!canCreate) return;

    const name = document.getElementById('rspName').value.trim();
    if (!name) {
        alert('RSP name required.');
        return;
    }

    fetch('/api/admin/create_rsp.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        },
        body: JSON.stringify({ name })
    })
    .then(res => res.json())
    .then(data => {
        if (!data.success) return alert(data.message);
        document.getElementById('rspName').value = '';
        loadRSPs();
    });
}

function toggleStatus(id) {

    if (!canEdit) return;

    fetch('/api/admin/toggle_rsp_status.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        },
        body: JSON.stringify({ rsp_id: id })
    })
    .then(res => res.json())
    .then(data => {
        if (!data.success) return alert(data.message);
        loadRSPs();
    });
}

loadRSPs();
</script>

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