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

$canEdit = can($user, 'service_providers', 'edit', $pdo);

?>

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

<h3>Service Provider Configuration</h3>

<table class="table table-bordered table-striped">
    <thead class="table-dark">
        <tr>
            <th>Company</th>
            <th>RSP</th>
            <th>Base Lat</th>
            <th>Base Lng</th>
            <th>Radius (KM)</th>
            <th>Penalty</th>
            <?php if ($canEdit): ?>
                <th>Actions</th>
            <?php endif; ?>
        </tr>
    </thead>
    <tbody id="spTable"></tbody>
</table>

<script>
const token   = '<?= htmlspecialchars($_SESSION['api_token'], ENT_QUOTES, 'UTF-8') ?>';
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 loadSPs() {

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

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

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

        profiles.forEach(p => {

            rows += `
            <tr>
                <td>${escapeHtml(p.company_name)}</td>
                <td>${escapeHtml(p.rsp_name)}</td>
                <td>
                    <input 
                        value="${p.base_lat ?? ''}" 
                        id="lat_${p.company_id}" 
                        class="form-control form-control-sm"
                        ${canEdit ? '' : 'disabled'}
                    >
                </td>
                <td>
                    <input 
                        value="${p.base_lng ?? ''}" 
                        id="lng_${p.company_id}" 
                        class="form-control form-control-sm"
                        ${canEdit ? '' : 'disabled'}
                    >
                </td>
                <td>
                    <input 
                        value="${p.coverage_radius_km ?? 25}" 
                        id="rad_${p.company_id}" 
                        class="form-control form-control-sm"
                        ${canEdit ? '' : 'disabled'}
                    >
                </td>
                <td>${p.penalty_count ?? 0}</td>
            `;

            if (canEdit) {
                rows += `
                    <td>
                        <button class="btn btn-sm btn-success"
                            onclick="saveProfile(${p.company_id})">
                            Save
                        </button>
                    </td>
                `;
            }

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

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

function saveProfile(company_id) {

    if (!canEdit) return;

    const base_lat = document.getElementById('lat_' + company_id).value.trim();
    const base_lng = document.getElementById('lng_' + company_id).value.trim();
    const radius   = document.getElementById('rad_' + company_id).value.trim();

    if (!base_lat || !base_lng || !radius) {
        alert('All fields are required.');
        return;
    }

    if (isNaN(base_lat) || isNaN(base_lng) || isNaN(radius)) {
        alert('Invalid numeric values.');
        return;
    }

    const payload = {
        company_id,
        base_lat: parseFloat(base_lat),
        base_lng: parseFloat(base_lng),
        coverage_radius_km: parseInt(radius)
    };

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

loadSPs();
</script>

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