<?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, 'escalations', 'view', $pdo)) {
    http_response_code(403);
    die('Access denied.');
}

?>

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

<h3>Job Escalation Monitor</h3>

<div class="card p-3 mb-3 bg-light">
    <h5>Total Alerts: <span id="alertCount">0</span></h5>
</div>

<table class="table table-bordered table-striped">
    <thead class="table-danger">
        <tr>
            <th>Breakdown ID</th>
            <th>Issue Type</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody id="alertTable"></tbody>
</table>

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

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

        if (!data.success) return;

        document.getElementById('alertCount').innerText =
            data.data.count ?? 0;

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

        alerts.forEach(a => {

            rows += `
                <tr>
                    <td>${a.breakdown_id}</td>
                    <td>
                        <span class="badge bg-danger">
                            ${escapeHtml(a.type)}
                        </span>
                    </td>
                    <td>${escapeHtml(a.status)}</td>
                </tr>
            `;
        });

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

/* Auto-refresh every 15 seconds */
setInterval(loadEscalations, 15000);
loadEscalations();
</script>

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