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

<h3>Companies Management</h3>

<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>

<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>

<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>
            <th>Action</th>
        </tr>
    </thead>
    <tbody id="companyTable"></tbody>
</table>

<script>
const token = '<?= $_SESSION['api_token'] ?>';

function loadRSPs() {
    fetch('/api/admin/get_rsps.php', {
        headers: { 'Authorization': 'Bearer ' + token }
    })
    .then(res => res.json())
    .then(data => {
        let options = '<option value="">All RSPs</option>';
        let createOptions = '';
        data.data.rsps.forEach(r => {
            options += `<option value="${r.id}">${r.name}</option>`;
            createOptions += `<option value="${r.id}">${r.name}</option>`;
        });

        document.getElementById('rspFilter').innerHTML = options;
        document.getElementById('companyRsp').innerHTML = createOptions;
    });
}

function loadCompanies() {
    const rsp_id = document.getElementById('rspFilter').value;
    let url = '/api/admin/get_companies.php';
    if (rsp_id) url += '?rsp_id=' + rsp_id;

    fetch(url, {
        headers: { 'Authorization': 'Bearer ' + token }
    })
    .then(res => res.json())
    .then(data => {
        let rows = '';
        data.data.companies.forEach(c => {
            rows += `
                <tr>
                    <td>${c.id}</td>
                    <td>${c.company_name}</td>
                    <td>${c.type}</td>
                    <td>${c.rsp_name}</td>
                    <td>
                        <span class="badge ${c.status === 'active' ? 'bg-success' : 'bg-danger'}">
                            ${c.status}
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-warning"
                            onclick="toggleStatus(${c.id})">
                            Toggle
                        </button>
                    </td>
                </tr>
            `;
        });

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

function createCompany() {
    const name = document.getElementById('companyName').value;
    const type = document.getElementById('companyType').value;
    const rsp_id = document.getElementById('companyRsp').value;

    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) {
    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'; ?>