<?php
declare(strict_types=1);

require_once __DIR__ . '/../security/auth_guard_web.php';
require_once __DIR__ . '/../partials/main.php';

$role = $_SESSION['role'] ?? '';
$isAdmin = in_array($role, ['Admin', 'Super Admin'], true);
$isSuperAdmin = ($role === 'Super Admin');
?>
<!DOCTYPE html>
<html lang="en">
<head>

<?php includeFileWithVariables(
    __DIR__ . '/../partials/title-meta.php',
    ['title' => 'Pages']
); ?>

<?php include __DIR__ . '/../partials/head-css.php'; ?>
</head>
<body>

<div id="layout-wrapper">
<?php include __DIR__ . '/../partials/header.php'; ?>
<?php include __DIR__ . '/../partials/sidebar.php'; ?>
<?php include __DIR__ . '/../partials/horizontal.php'; ?>

<main class="app-wrapper">
<div class="container-fluid">

<?php includeFileWithVariables(
    __DIR__ . '/../partials/page-title.php',
    ['title_sub' => 'CMS', 'title' => 'Pages']
); ?>

<div class="card">

<!-- HEADER -->
<div class="card-header d-flex justify-content-between align-items-center">
<h6 class="mb-0">Pages</h6>

<?php if ($isAdmin): ?>
<a href="<?= ADMIN_BASE_URL ?>pages/create.php" class="btn btn-primary">
<i class="bi bi-plus-lg me-1"></i> Add Page
</a>
<?php endif; ?>
</div>

<!-- FILTERS -->
<div class="card-body border-bottom">
<div class="row g-3 align-items-end">

<div class="col-md-3">
<label class="form-label">Search</label>
<input type="text" id="search" class="form-control" placeholder="Page title">
</div>

<div class="col-md-2">
<label class="form-label">Status</label>
<select id="status" class="form-select">
<option value="">All</option>
<option value="Draft">Draft</option>
<option value="Active">Active</option>
<option value="InActive">Inactive</option>
</select>
</div>

<div class="col-md-2">
<label class="form-label">Approval</label>
<select id="approval_status" class="form-select">
<option value="">All</option>
<option value="Pending">Pending</option>
<option value="Approved">Approved</option>
<option value="Rejected">Rejected</option>
</select>
</div>

<div class="col-md-2">
<label class="form-label">Show in Menu</label>
<select id="show_in_menu" class="form-select">
<option value="">All</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</div>

<div class="col-md-3 text-end">
<button class="btn btn-primary w-100" onclick="loadPages(1)">
Apply Filters
</button>
</div>

</div>
</div>

<!-- TABLE -->
<div class="card-body">
<div class="table-responsive">

<table class="table table-bordered align-middle text-nowrap">
<thead class="table-light">
<tr>
<th>#</th>
<th>Image</th>
<th>Title</th>
<th>Slug</th>
<th>Type</th>
<th>Menu</th>
<th>Status</th>
<th>Approval</th>
<th>Created</th>
<th>Actions</th>
</tr>
</thead>

<tbody id="pageTableBody">
<tr>
<td colspan="10" class="text-center text-muted">Loading pages…</td>
</tr>
</tbody>
</table>

</div>

<!-- PAGINATION -->
<div class="d-flex justify-content-between align-items-center mt-3">
<div id="paginationInfo" class="text-muted"></div>
<ul class="pagination pagination-primary mb-0" id="pagination"></ul>
</div>

</div>
</div>

</div>
</main>

<?php include __DIR__ . '/../partials/footer.php'; ?>
</div>

<?php include __DIR__ . '/../partials/vendor-scripts.php'; ?>

<!-- REJECT MODAL -->
<div class="modal fade" id="rejectModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title">Reject Page</h6>
<button class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<textarea id="rejectReason" class="form-control"
placeholder="Enter rejection reason"></textarea>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button class="btn btn-danger" onclick="confirmReject()">Reject</button>
</div>
</div>
</div>
</div>

<script>
const ADMIN = "<?= ADMIN_BASE_URL ?>";
const IS_ADMIN = <?= $isAdmin ? 'true' : 'false' ?>;
const IS_SUPER_ADMIN = <?= $isSuperAdmin ? 'true' : 'false' ?>;

let CSRF_TOKEN = null;
let selectedPageId = null;

/* CSRF */
fetch(`${ADMIN}security/csrf.php`, { credentials:'include' })
.then(r => r.json())
.then(j => CSRF_TOKEN = j.data.csrf_token);

/* LOAD PAGES */
async function loadPages(page = 1){

const params = new URLSearchParams({
context:'backend',
page
});

if (search.value) params.append('search', search.value);
if (status.value) params.append('status', status.value);
if (approval_status.value) params.append('approval_status', approval_status.value);
if (show_in_menu.value !== '') params.append('show_in_menu', show_in_menu.value);

const res = await fetch(`${ADMIN}api/pages/list.php?${params}`,{
credentials:'include'
});
const json = await res.json();

if(json.status !== 'success'){
alert(json.message);
return;
}

const rows = json.data.list;
const p = json.data.pagination;

pageTableBody.innerHTML = rows.length ? rows.map((r,i)=>`
<tr>
<td>${(p.page-1)*p.limit+i+1}</td>

<td>${r.featured_image
? `<img src="<?= APP_ROOT ?>${r.featured_image}" width="45" class="rounded">`
: `<span class="text-muted">—</span>`}
</td>

<td><strong>${r.title}</strong></td>
<td>${r.slug}</td>
<td>${r.page_type}</td>
<td>${r.show_in_menu ? 'Yes' : 'No'}</td>

<td>
<span class="badge bg-${r.status==='Active'?'success':'secondary'}">
${r.status}
</span>
</td>

<td>
${
r.approval_status === 'Pending' && IS_ADMIN
? `
<select class="form-select form-select-sm"
onchange="approvalAction(${r.id}, this.value)">
<option value="">Pending</option>
<option value="approve">Approve</option>
<option value="reject">Reject</option>
</select>`
: `
<span class="badge bg-${r.approval_status==='Approved'?'success':'danger'}">
${r.approval_status}
</span>`
}
</td>

<td>${r.created_at}</td>

<td>
<a href="<?= ADMIN_BASE_URL ?>pages/view.php?id=${r.id}"
class="btn btn-light-info icon-btn-sm me-1">
<i class="bi bi-eye"></i>
</a>

<?php if ($isAdmin): ?>
<a href="<?= ADMIN_BASE_URL ?>pages/edit.php?id=${r.id}"
class="btn btn-light-primary icon-btn-sm me-1">
<i class="bi bi-pencil-square"></i>
</a>
<?php endif; ?>

${IS_SUPER_ADMIN && r.status!=='Active' ? `
<button class="btn btn-light-danger icon-btn-sm"
onclick="deletePage(${r.id})">
<i class="bi bi-trash"></i>
</button>` : ''}
</td>
</tr>
`).join('')
:
`<tr><td colspan="10" class="text-center text-muted">No pages found</td></tr>`;

pagination.innerHTML='';
for(let i=1;i<=p.pages;i++){
pagination.innerHTML+=`
<li class="page-item ${i===p.page?'active':''}">
<a class="page-link" onclick="loadPages(${i})">${i}</a>
</li>`;
}

paginationInfo.innerText =
`Showing page ${p.page} of ${p.pages} (${p.total} records)`;
}

/* APPROVAL */
function approvalAction(id, action){
if(!action) return;

if(action === 'approve'){
fetch(`${ADMIN}api/pages/approve.php`,{
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRF-TOKEN':CSRF_TOKEN
},
credentials:'include',
body:JSON.stringify({page_id:id})
})
.then(r=>r.json())
.then(r=>{
alert(r.message);
if(r.status==='success') loadPages();
});
}

if(action === 'reject'){
selectedPageId = id;
rejectReason.value = '';
new bootstrap.Modal(rejectModal).show();
}
}

/* CONFIRM REJECT */
function confirmReject(){
if(!rejectReason.value.trim()){
alert('Rejection reason required');
return;
}

fetch(`${ADMIN}api/pages/reject.php`,{
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRF-TOKEN':CSRF_TOKEN
},
credentials:'include',
body:JSON.stringify({
page_id:selectedPageId,
reason:rejectReason.value
})
})
.then(r=>r.json())
.then(r=>{
alert(r.message);
bootstrap.Modal.getInstance(rejectModal).hide();
if(r.status==='success') loadPages();
});
}

/* DELETE */
function deletePage(id){
if(!confirm('This will permanently delete the page. Continue?')) return;

fetch(`${ADMIN}api/pages/delete.php`,{
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRF-TOKEN':CSRF_TOKEN
},
credentials:'include',
body:JSON.stringify({page_id:id})
})
.then(r=>r.json())
.then(r=>{
alert(r.message);
if(r.status==='success') loadPages();
});
}

/* INIT */
loadPages();
</script>

</body>
</html>
