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

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

/* RSP filter allowed only if user can view RSPs */
$canFilterByRsp = can($user, 'rsps', 'view', $pdo);

?>

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

<h3>Companies Management</h3>

<?php if ($canFilterByRsp): ?>
<div class="row mb-3">
    <div class="col-md-3">
        <select id="rspFilter" class="form-select" onchange="loadCompanies()">
            <option value="">All RSPs</option>
        </select>
    </div>
</div>
<?php endif; ?>

<?php if ($canCreate): ?>
<div class="card mb-4 p-3">
    <h5>Create Company</h5>
    <div class="row">
        <div class="col-md-3">
            <input type="text" id="companyName" class="form-control" placeholder="Company Name">
        </div>
        <div class="col-md-3">
            <select id="companyType" class="form-select">
                <option value="fleet">Fleet</option>
                <option value="sp">Service Provider</option>
            </select>
        </div>
        <div class="col-md-3">
            <select id="companyRsp" class="form-select"></select>
        </div>
        <div class="col-md-2">
            <button class="btn btn-primary" onclick="createCompany()">Create</button>
        </div>
    </div>
</div>
<?php endif; ?>

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

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

    if (!canFilterByRsp) return;

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

        if (!data.success) return;

        let options = '<option value="">All RSPs</option>';
        let createOptions = '';

        const rsps = data.data.rsps || [];

        rsps.forEach(r => {
            options += `<option value="${r.id}">${escapeHtml(r.name)}</option>`;
            createOptions += `<option value="${r.id}">${escapeHtml(r.name)}</option>`;
        });

        document.getElementById('rspFilter').innerHTML = options;

        if (canCreate) {
            document.getElementById('companyRsp').innerHTML = createOptions;
        }
    });
}

function loadCompanies() {

    let url = '/api/admin/get_companies.php';

    if (canFilterByRsp) {
        const rsp_id = document.getElementById('rspFilter')?.value;
        if (rsp_id) url += '?rsp_id=' + rsp_id;
    }

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

        if (!data.success) return;

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

        companies.forEach(c => {

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

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

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

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

function createCompany() {

    if (!canCreate) return;

    const name   = document.getElementById('companyName').value.trim();
    const type   = document.getElementById('companyType').value;
    const rsp_id = document.getElementById('companyRsp')?.value;

    if (!name || !rsp_id) {
        alert('Please complete all fields.');
        return;
    }

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

function toggleStatus(id) {

    if (!canEdit) return;

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

loadRSPs();
loadCompanies();
</script>

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