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

<style>

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

h1 {
    margin-top: 0;
}

.toolbar {
    margin-bottom: 12px;
}

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

button.secondary {
    background: #6b7280;
}

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 {
    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 {
    width: 100%;
    padding: 8px;
    margin-bottom: 10px;
    box-sizing: border-box;
}

</style>


<main class="main">

<h1>Subscriptions</h1>

<div class="toolbar">

<select id="companySelect"></select>

<button onclick="openModal()">Assign Module</button>

</div>


<table>

<thead>

<tr>
<th>Module</th>
<th>Status</th>
<th>Start</th>
<th>End</th>
<th>Action</th>
</tr>

</thead>

<tbody id="subsBody"></tbody>

</table>

</main>


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

<div class="modal-content">

<h3>Assign Module</h3>

<select id="moduleSelect"></select>

<br><br>

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

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

</div>

</div>


<script>

/* =========================
CONFIG
========================= */

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

const COMP_API=`${API_BASE}/companies/list.php`
const MOD_API=`${API_BASE}/company/modules.php`
const SUB_API=`${API_BASE}/subscriptions/admin.php`

let companyId=null


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

function openModal(){

modal.classList.remove('hidden')

}

function closeModal(){

modal.classList.add('hidden')

}


/* ================= 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
}

})

}


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

function loadCompanies(){

fetch(COMP_API,{credentials:'include'})

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

.then(res=>{

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

throw new Error(res.message||'Failed to load companies')

}

companySelect.innerHTML=''

const companies=res.data?.companies??[]

if(!companies.length){

const o=document.createElement('option')
o.disabled=true
o.textContent='No companies'

companySelect.appendChild(o)

return

}

companies.forEach(c=>{

const o=document.createElement('option')

o.value=c.id
o.textContent=c.company_name

companySelect.appendChild(o)

})

companyId=companySelect.value

loadSubs()

companySelect.onchange=()=>{

companyId=companySelect.value

loadSubs()

}

})

.catch(err=>{

console.error('LOAD COMPANIES ERROR:',err)

alert('Failed to load companies')

})

}


/* =========================
LOAD MODULES
========================= */

function loadModules(){

fetch(MOD_API,{credentials:'include'})

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

.then(res=>{

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

throw new Error(res.message||'Failed to load modules')

}

const modules=

Array.isArray(res.data?.modules)

?res.data.modules

:Array.isArray(res.data)

?res.data

:[]

moduleSelect.innerHTML=''

if(!modules.length){

const o=document.createElement('option')

o.disabled=true

o.textContent='No modules available'

moduleSelect.appendChild(o)

return

}

modules.forEach(m=>{

const o=document.createElement('option')

o.value=m.module_key??m.id

o.textContent=m.name??m.module_key

moduleSelect.appendChild(o)

})

})

.catch(err=>{

console.error('LOAD MODULES ERROR:',err)

alert('Failed to load modules')

})

}


/* =========================
LOAD SUBSCRIPTIONS
========================= */

function loadSubs(){

if(!companyId) return

fetch(`${SUB_API}?company_id=${companyId}`,{credentials:'include'})

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

.then(res=>{

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

throw new Error(res.message||'Failed to load subscriptions')

}

const subs=res.data?.subscriptions??[]

subsBody.innerHTML=''

if(!subs.length){

subsBody.innerHTML=`<tr><td colspan="5">No subscriptions found</td></tr>`

return

}

subs.forEach(s=>{

const tr=document.createElement('tr')

tr.innerHTML=`

<td>${s.module_name}</td>
<td>${s.status}</td>
<td>${s.start_date??'-'}</td>
<td>${s.end_date??'-'}</td>
<td>
${s.status==='active'
?`<button onclick="cancelSub(${s.id})">Cancel</button>`
:'-'}
</td>

`

subsBody.appendChild(tr)

})

})

.catch(err=>{

console.error('LOAD SUBSCRIPTIONS ERROR:',err)

alert('Failed to load subscriptions')

})

}


/* =========================
ASSIGN MODULE
========================= */

function assign(){

csrfFetch(SUB_API,{

method:'POST',

credentials:'include',

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

body:JSON.stringify({

company_id:companyId,
module_id:moduleSelect.value

})

})

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

.then(res=>{

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

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

}

closeModal()

loadSubs()

})

.catch(err=>{

console.error('ASSIGN MODULE ERROR:',err)

alert('Failed to assign module')

})

}


/* =========================
CANCEL SUBSCRIPTION
========================= */

function cancelSub(id){

if(!confirm('Cancel this subscription?')) return

fetch(SUB_API,{

method:'DELETE',

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||'Cancel failed')

}

loadSubs()

})

.catch(err=>{

console.error('CANCEL SUB ERROR:',err)

alert('Failed to cancel subscription')

})

}


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

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

loadCompanies()

loadModules()

})

</script>


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