<?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;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

input, select {
    padding: 6px;
    font-size: 14px;
}

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;
    vertical-align: top;
}

th {
    background: #f9fafb;
}

.details {
    background: #f9fafb;
    font-family: monospace;
    white-space: pre-wrap;
    font-size: 13px;
}

.pagination {
    margin-top: 12px;
    display: flex;
    align-items: center;
    gap: 10px;
}

</style>


<main class="main">

<h1>Audit Logs</h1>

<div id="auditError" style="display:none;background:#fee2e2;color:#991b1b;padding:12px;margin-bottom:12px;">
<strong id="auditErrorTitle"></strong>
<div id="auditErrorMessage"></div>
</div>


<div class="toolbar">

<input id="actor" placeholder="Actor email contains">

<select id="action">
<option value="">All actions</option>
<option value="create">Create</option>
<option value="update">Update</option>
<option value="delete">Delete</option>
<option value="login">Login</option>
<option value="logout">Logout</option>
</select>

<select id="targetType">
<option value="">All targets</option>
<option value="user">User</option>
<option value="company">Company</option>
<option value="subscription">Subscription</option>
<option value="billing">Billing</option>
<option value="auth">Auth</option>
</select>

<input type="date" id="dateFrom">
<input type="date" id="dateTo">

<button onclick="applyFilters()">Apply</button>

</div>


<table>

<thead>

<tr>
<th>Date</th>
<th>Action</th>
<th>Actor</th>
<th>Target</th>
<th>Company</th>
<th>RSP</th>
<th>IP</th>
<th></th>
</tr>

</thead>

<tbody id="auditBody"></tbody>

</table>


<div class="pagination">

<button class="secondary" onclick="prevPage()">Prev</button>

<span id="pageInfo"></span>

<button class="secondary" onclick="nextPage()">Next</button>

</div>

</main>


<script>

const API_BASE='/audit'
let page=1
const limit=25
let total=0


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

function loadAudit(){

hideError()

const params=new URLSearchParams({

page,
limit,
actor:document.getElementById('actor').value,
action:document.getElementById('action').value,
target_type:document.getElementById('targetType').value,
from:document.getElementById('dateFrom').value,
to:document.getElementById('dateTo').value

})

fetch(`${API_BASE}/list.php?${params}`,{credentials:'include'})

.then(async r=>{

if(r.status===403){
throw{type:'forbidden'}
}

if(!r.ok){
throw{type:'server'}
}

return r.json()

})

.then(res=>{

if(res.status!=='success'){
throw{type:'server'}
}

total=res.data.total||0

renderRows(res.data.logs||[])

updatePageInfo()

})

.catch(err=>{
handleAuditError(err)
})

}


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

function renderRows(logs){

const tbody=document.getElementById('auditBody')

tbody.innerHTML=''

if(!logs.length){

tbody.innerHTML=`<tr><td colspan="8" style="text-align:center">No records found</td></tr>`

return

}

logs.forEach(log=>{

const tr=document.createElement('tr')

tr.innerHTML=`

<td>${fmt(log.created_at)}</td>
<td>${esc(log.action)}</td>
<td>${esc(log.actor_email)}<br><small>${esc(log.actor_role)}</small></td>
<td>${esc(log.target_type)} ${log.target_id??''}</td>
<td>${esc(log.company_name??'-')}</td>
<td>${esc(log.rsp_name??'-')}</td>
<td>${esc(log.ip_address)}</td>
<td><button class="secondary" onclick='toggleDetails(this, ${JSON.stringify(log.metadata)})'>Details</button></td>

`

tbody.appendChild(tr)

})

}


/* ===============================
DETAILS
=============================== */

function toggleDetails(btn,meta){

const tr=btn.closest('tr')

if(tr.nextSibling && tr.nextSibling.classList.contains('details-row')){
tr.nextSibling.remove()
return
}

const details=document.createElement('tr')

details.className='details-row'

details.innerHTML=`
<td colspan="8" class="details">
${meta?esc(JSON.stringify(meta,null,2)):'No metadata'}
</td>
`

tr.after(details)

}


/* ===============================
PAGINATION
=============================== */

function nextPage(){

if(page*limit<total){

page++

loadAudit()

}

}

function prevPage(){

if(page>1){

page--

loadAudit()

}

}

function updatePageInfo(){

document.getElementById('pageInfo').innerText=
`Page ${page} of ${Math.max(1,Math.ceil(total/limit))}`

}


/* ===============================
FILTERS
=============================== */

function applyFilters(){

page=1

loadAudit()

}


/* ===============================
HELPERS
=============================== */

function esc(v){

if(v==null) return ''

return String(v)
.replace(/&/g,'&amp;')
.replace(/</g,'&lt;')
.replace(/>/g,'&gt;')
.replace(/"/g,'&quot;')
.replace(/'/g,'&#039;')

}

function fmt(ts){

return ts?new Date(ts).toLocaleString():'-'

}


function handleAuditError(err){

const tbody=document.getElementById('auditBody')

tbody.innerHTML=''

if(err.type==='forbidden'){

showError(
'Access denied',
'You do not have permission to view audit logs for this scope.'
)

disablePagination()

return

}

showError(
'Audit service unavailable',
'An internal error occurred while loading audit logs. Please try again later.'
)

disablePagination()

}


function showError(title,message){

document.getElementById('auditErrorTitle').innerText=title
document.getElementById('auditErrorMessage').innerText=message
document.getElementById('auditError').style.display='block'

}

function hideError(){

document.getElementById('auditError').style.display='none'

}

function disablePagination(){

document.querySelectorAll('.pagination button')
.forEach(b=>b.disabled=true)

}


document.addEventListener('DOMContentLoaded',loadAudit)

</script>


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