<?php require_once __DIR__.'/layout/header.php'; ?>
<?php require_once __DIR__.'/layout/sidebar.php'; ?>

<style>

/* ===== MAIN ===== */

.main {
    margin-left: 200px;
    padding: 24px;
}

h1 {
    margin-top: 0;
}

/* ===== TOOLBAR ===== */

.toolbar {
    margin-bottom: 12px;
}

button {
    padding: 8px 14px;
    border: none;
    background: #2563eb;
    color: #fff;
    cursor: pointer;
    font-size: 14px;
}

button.secondary {
    background: #6b7280;
}

/* ===== TABLE ===== */

table {
    width: 100%;
    border-collapse: collapse;
    background: #fff;
}

th, td {
    padding: 10px;
    border-bottom: 1px solid #e5e7eb;
    text-align: left;
    font-size: 14px;
}

th {
    background: #f9fafb;
}

/* ===== MODAL ===== */

.modal {
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.4);
    display: flex;
    align-items: center;
    justify-content: center;
}

.modal.hidden {
    display: none;
}

.modal-content {
    background: #fff;
    padding: 20px;
    width: 420px;
}

.modal-content h3 {
    margin-top: 0;
}

.modal-content input,
.modal-content select {
    width: 100%;
    padding: 8px;
    margin-bottom: 10px;
    box-sizing: border-box;
}

</style>


<div class="main">

<h1>Companies</h1>

<div class="toolbar">
<button onclick="openModal()">+ Add Company</button>
</div>


<table>

<thead>

<tr>
<th>ID</th>
<th>Company Name</th>
<th>Contact Email</th>
<th>Status</th>
<th>Created</th>
<th>Action</th>
</tr>

</thead>

<tbody id="companiesBody"></tbody>

</table>

</div>


<!-- ===== MODAL ===== -->

<div id="modal" class="modal hidden">

<div class="modal-content">

<h3>Create Company</h3>

<input id="companyName" placeholder="Company Name">

<input id="contactEmail" placeholder="Contact Email">


<label>Product</label>

<select id="productSelect">

<option value="">Select Product</option>

<option value="1">Mining</option>

<option value="2">Assist</option>

</select>


<label>RSP (Leave blank to create RSP)</label>

<select id="rspSelect">

<option value="">Create as RSP</option>

</select>


<button onclick="createCompany()">Save</button>

<button class="secondary" onclick="closeModal()">Cancel</button>


<h3>Modules</h3>


<label>
<input type="checkbox" data-module="USERS">
Users Module
</label>


<label>
<input type="checkbox" data-module="AUDIT">
Audit Module
</label>


</div>

</div>



<script>

const API_BASE   = 'https://api.jb26.co.za/companies'

const LIST_API   = `${API_BASE}/list.php`

const CREATE_API = `${API_BASE}/create.php`

const DELETE_API = `${API_BASE}/delete.php`


let page = 1

const limit = 10


let CURRENT_COMPANY_ID = null


let currentUser = {

role_key: null,

role_rank: null,

product_id: null,

company_id: null

}


/* ================= CSRF ================= */

let CSRF_TOKEN = null


fetch('/auth/csrf_token.php', { credentials: 'include' })

.then(r => r.json())

.then(d => {

CSRF_TOKEN = d.csrf_token

})


function csrfFetch(url, options = {}) {

return fetch(url, {

...options,

credentials: 'include',

headers: {

...(options.headers || {}),

'X-CSRF-Token': CSRF_TOKEN

}

})

}



/* ================= CURRENT USER ================= */

function loadCurrentUser() {

return fetch('/system/me.php', { credentials: 'include' })

.then(r => r.json())

.then(res => {

if (res.status !== 'success') return

currentUser = res.data

enforceRoleUI()

loadRspList()

})

}



function enforceRoleUI() {

const toolbar = document.querySelector('.toolbar')

const productSelect = document.getElementById('productSelect')


if (!['super_admin','platform_admin','rsp_owner','rsp_admin'].includes(currentUser.role_key)) {

toolbar.style.display = 'none'

}


if (!['super_admin','platform_admin'].includes(currentUser.role_key)) {

productSelect.value = currentUser.product_id

productSelect.disabled = true

}

}



/* ================= RSP LIST ================= */

function loadRspList() {

const rspSelect = document.getElementById('rspSelect')


if (currentUser.role_key === 'rsp_admin') {

rspSelect.innerHTML =

`<option value="${currentUser.company_id}" selected>My RSP</option>`

rspSelect.disabled = true

return

}


fetch(`${LIST_API}?only_rsp=1`, { credentials: 'include' })

.then(r => r.json())

.then(res => {

if (res.status !== 'success') return


rspSelect.innerHTML = '<option value="">Create as RSP</option>'


(res.data.companies || []).forEach(c => {

rspSelect.innerHTML +=

`<option value="${c.id}">${c.company_name}</option>`

})

})

}



/* ================= MODAL ================= */

function openModal() {

modal.classList.remove('hidden')

}


function closeModal() {

modal.classList.add('hidden')

}



/* ================= LOAD COMPANIES ================= */

function loadCompanies() {

const params = new URLSearchParams({ page, limit })


fetch(`${LIST_API}?${params}`, {

credentials: 'include'

})

.then(r => r.json())

.then(res => {

if (res.status !== 'success') {

throw new Error(res.message || 'Load failed')

}

renderCompanies(res.data.companies || [])

})

.catch(err => {

console.error(err)

alert('Failed to load companies')

})

}



/* ================= MODULE TOGGLE ================= */

async function toggleModule(companyId, moduleKey, enabled) {

if (!companyId) {

alert('Please create a company first.')

return

}


await csrfFetch('/api/admin/company_modules_toggle.php', {

method: 'POST',

headers: { 'Content-Type': 'application/json' },

body: JSON.stringify({

company_id: companyId,

module_key: moduleKey,

enabled: enabled

})

})

}


document.querySelectorAll('input[data-module]').forEach(cb => {

cb.addEventListener('change', () => {

toggleModule(CURRENT_COMPANY_ID, cb.dataset.module, cb.checked)

})

})



/* ================= RENDER ================= */

function renderCompanies(companies) {

const tbody = document.getElementById('companiesBody')

tbody.innerHTML = ''


if (!companies.length) {

tbody.innerHTML = `<tr><td colspan="6">No companies found</td></tr>`

return

}


companies.forEach(c => {

const tr = document.createElement('tr')

tr.innerHTML = `

<td>${c.id}</td>

<td>${c.company_name}</td>

<td>${c.contact_email ?? '-'}</td>

<td>${c.rsp_id ? 'RSP Customer' : 'Direct'}</td>

<td>${new Date(c.created_at).toLocaleDateString()}</td>

<td>

<button onclick="deleteCompany(${c.id})">Delete</button>

</td>

`

tbody.appendChild(tr)

})

}



/* ================= CREATE ================= */

function createCompany() {

const company_name = companyName.value.trim()

const contact_email = contactEmail.value.trim()

const product_id = productSelect.value ? Number(productSelect.value) : null

const rsp_id = rspSelect.value ? Number(rspSelect.value) : null


if (!company_name) {

alert('Company name required')

return

}


csrfFetch(CREATE_API, {

method: 'POST',

credentials: 'include',

headers: { 'Content-Type': 'application/json' },

body: JSON.stringify({

company_name,

contact_email,

product_id,

rsp_id

})

})

.then(r => r.json())

.then(res => {

if (res.status !== 'success') {

throw new Error(res.message || 'Create failed')

}


CURRENT_COMPANY_ID = res.data.company_id


closeModal()

loadCompanies()

})

.catch(err => {

console.error(err)

alert('Failed to create company')

})

}



/* ================= DELETE ================= */

function deleteCompany(id) {

if (!confirm('Delete this company?')) return


csrfFetch(DELETE_API, {

method: 'POST',

credentials: 'include',

headers: { 'Content-Type': 'application/json' },

body: JSON.stringify({ id })

})

.then(r => r.json())

.then(res => {

if (res.status !== 'success') {

throw new Error(res.message || 'Delete failed')

}

loadCompanies()

})

.catch(err => {

console.error(err)

alert('Failed to delete company')

})

}



/* ================= INIT ================= */

document.addEventListener('DOMContentLoaded', () => {

loadCurrentUser().then(() => {

loadCompanies()

})

})

</script>


<?php require_once __DIR__.'/layout/footer.php'; ?>