<?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: /admin/login.php');
    exit;
}

$user  = $_SESSION['user'];
$token = $_SESSION['api_token'];

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

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

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

<div class="container">

<h3>Platform Analytics Dashboard</h3>

<div class="row mb-3">
    <div class="col-md-2">
        <input type="date" id="dateFrom" class="form-control">
    </div>
    <div class="col-md-2">
        <input type="date" id="dateTo" class="form-control">
    </div>
    <div class="col-md-2">
        <button class="btn btn-primary" onclick="loadDashboard()">Apply</button>
    </div>
</div>

<div class="row text-center mb-4">

    <div class="col-md-3">
        <div class="card shadow">
            <div class="card-body">
                <h6>Total Jobs</h6>
                <h3 id="totalJobs">-</h3>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card shadow">
            <div class="card-body">
                <h6>Total Travel KM</h6>
                <h3 id="totalTravel">-</h3>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card shadow">
            <div class="card-body">
                <h6>Total Billable KM</h6>
                <h3 id="totalBillable">-</h3>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card shadow">
            <div class="card-body">
                <h6>Avg Total Duration (min)</h6>
                <h3 id="avgDuration">-</h3>
            </div>
        </div>
    </div>

</div>

<h5>Top Performing Service Providers</h5>

<table class="table table-bordered table-striped">
    <thead class="table-dark">
        <tr>
            <th>Rank</th>
            <th>SP</th>
            <th>Jobs</th>
            <th>Avg Accept</th>
            <th>Avg Duration</th>
        </tr>
    </thead>
    <tbody id="rankingTable"></tbody>
</table>

</div>

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

function buildQuery() {
    const params = new URLSearchParams();
    const date_from = document.getElementById('dateFrom').value;
    const date_to   = document.getElementById('dateTo').value;

    if (date_from) params.append('date_from', date_from);
    if (date_to)   params.append('date_to', date_to);

    return params.toString();
}

function fetchJSON(url) {
    return fetch(url, {
        headers: {
            'Authorization': 'Bearer ' + token
        }
    }).then(res => res.json());
}

function loadDashboard() {

    const query = buildQuery();

    fetchJSON('/api/admin/get_overview.php?' + query)
        .then(data => {
            if (!data.success) return;

            const summary = data.data.summary || {};
            document.getElementById('totalJobs').innerText = summary.total_jobs ?? 0;
            document.getElementById('totalTravel').innerText = summary.total_travel_km ?? 0;
            document.getElementById('totalBillable').innerText = summary.total_billable_km ?? 0;
        });

    fetchJSON('/api/admin/get_sla_analytics.php?' + query)
        .then(data => {
            if (!data.success) return;
            const avg = data.data.averages || {};
            document.getElementById('avgDuration').innerText = avg.avg_total_duration_min ?? 0;
        });

    fetchJSON('/api/admin/get_sp_rankings.php?' + query)
        .then(data => {
            if (!data.success) return;

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

            rankings.slice(0, 5).forEach(r => {
                rows += `
                    <tr>
                        <td>${r.rank}</td>
                        <td>${r.sp_name}</td>
                        <td>${r.completed_jobs}</td>
                        <td>${r.avg_time_to_accept_min}</td>
                        <td>${r.avg_total_duration_min}</td>
                    </tr>
                `;
            });

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

loadDashboard();
</script>

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