<?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' => 'FAQs']
); ?>

<?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' => 'FAQs']
); ?>

<div class="row">
<div class="col-12">
<div class="card">

<div class="card-header d-flex justify-content-between align-items-center">
    <h6 class="mb-0">FAQ List</h6>
    <a href="<?= ADMIN_BASE_URL ?>faq/create.php" class="btn btn-primary">
        <i class="bi bi-plus-lg me-1"></i> Add FAQ
    </a>
</div>

<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>Question</th>
    <th>Slug</th>
    <th>Status</th>
    <th>Approval</th>
    <th>Published</th>
    <th>Created</th>
    <th>Actions</th>
</tr>
</thead>
<tbody id="faqTableBody">
<tr>
    <td colspan="8" class="text-center text-muted">Loading FAQs…</td>
</tr>
</tbody>
</table>
</div>
</div>

</div>
</div>
</div>

</div>
</main>

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

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

<!-- ================= TOAST ================= -->
<div class="toast-container position-fixed top-0 end-0 p-3" style="z-index:1100">
    <div id="appToast" class="toast align-items-center border-0" role="alert">
        <div class="d-flex">
            <div class="toast-body" id="toastMessage"></div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto"
                    data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>

<!-- ================= STATUS MODAL ================= -->
<div class="modal fade" id="statusModal" tabindex="-1">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h6 class="modal-title">Update Status</h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <select id="faqStatusSelect" class="form-select">
          <option value="Active">Active</option>
          <option value="InActive">Inactive</option>
          <option value="Draft">Draft</option>
        </select>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button class="btn btn-primary" onclick="submitStatus()">Update</button>
      </div>
    </div>
  </div>
</div>

<!-- ================= APPROVAL MODAL ================= -->
<div class="modal fade" id="approvalModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h6 class="modal-title">Approval Action</h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <select id="approvalSelect" class="form-select mb-3"
                onchange="toggleRejectReason(this.value)">
          <option value="Approved">Approve</option>
          <option value="Rejected">Reject</option>
        </select>

        <textarea id="rejectReason"
                  class="form-control d-none"
                  placeholder="Enter rejection reason (min 5 chars)"></textarea>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button class="btn btn-primary" onclick="submitApproval()">Submit</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 CURRENT_FAQ_ID = null;

/* ================= TOAST ================= */
function showToast(type, message) {
    const toastEl = document.getElementById('appToast');
    const toastBody = document.getElementById('toastMessage');
    toastEl.className = `toast align-items-center text-bg-${type} border-0`;
    toastBody.innerText = message;
    new bootstrap.Toast(toastEl, { delay: 3000 }).show();
}

/* ================= LOAD FAQS ================= */
async function loadFaqs() {
    const tbody = document.getElementById('faqTableBody');

    try {
        const res = await fetch(`${ADMIN}api/faqs/list.php?context=backend&limit=100`, {
            credentials: 'include'
        });
        const json = await res.json();

        if (json.status !== 'success') {
            showToast('danger', json.message);
            return;
        }

        if (!json.data.list.length) {
            tbody.innerHTML = `<tr><td colspan="8" class="text-center text-muted">No FAQs found</td></tr>`;
            return;
        }

        tbody.innerHTML = json.data.list.map((f, i) => `
<tr>
<td>${i + 1}</td>
<td>${f.question}</td>
<td class="text-muted">${f.slug}</td>

<td>
<span class="badge bg-secondary ${IS_ADMIN ? 'cursor-pointer' : ''}"
onclick="openStatusModal(${f.id}, '${f.status}')">
${f.status}
</span>
</td>

<td>
<span class="badge bg-warning ${IS_ADMIN ? 'cursor-pointer' : ''}"
onclick="openApprovalModal(${f.id})">
${f.approval_status}
</span>
</td>

<td>${f.published_at ?? '-'}</td>
<td>${f.created_at}</td>

<td>
<button class="btn btn-light-info icon-btn-sm me-1"
onclick="viewFaq(${f.id})">
<i class="bi bi-eye"></i>
</button>

${IS_ADMIN ? `
<a href="edit.php?id=${f.id}"
class="btn btn-light-primary icon-btn-sm me-1">
<i class="bi bi-pencil-square"></i>
</a>` : ''}

${IS_SUPER_ADMIN ? `
<button class="btn btn-light-danger icon-btn-sm"
onclick="deleteFaq(${f.id})">
<i class="bi bi-trash"></i>
</button>` : ''}
</td>
</tr>
`).join('');

    } catch {
        showToast('danger', 'Failed to load FAQs');
    }
}

/* ================= STATUS ================= */
function openStatusModal(id, current) {
    if (!IS_ADMIN) return;
    CURRENT_FAQ_ID = id;
    document.getElementById('faqStatusSelect').value = current;
    new bootstrap.Modal('#statusModal').show();
}

async function submitStatus() {
    const status = document.getElementById('faqStatusSelect').value;

    const res = await fetch(`${ADMIN}api/faqs/status-update.php`, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ faq_id: CURRENT_FAQ_ID, status })
    });

    const json = await res.json();
    showToast(json.status === 'success' ? 'success' : 'danger', json.message);
    bootstrap.Modal.getInstance(document.getElementById('statusModal')).hide();
    loadFaqs();
}

/* ================= APPROVAL ================= */
function openApprovalModal(id) {
    if (!IS_ADMIN) return;
    CURRENT_FAQ_ID = id;
    document.getElementById('approvalSelect').value = 'Approved';
    document.getElementById('rejectReason').classList.add('d-none');
    new bootstrap.Modal('#approvalModal').show();
}

function toggleRejectReason(val) {
    document.getElementById('rejectReason')
        .classList.toggle('d-none', val !== 'Rejected');
}

async function submitApproval() {
    const action = document.getElementById('approvalSelect').value;
    let url = `${ADMIN}api/faqs/approve.php`;
    let payload = { faq_id: CURRENT_FAQ_ID };

    if (action === 'Rejected') {
        const reason = document.getElementById('rejectReason').value.trim();
        if (reason.length < 5) {
            showToast('danger', 'Rejection reason required');
            return;
        }
        url = `${ADMIN}api/faqs/reject.php`;
        payload.reason = reason;
    }

    const res = await fetch(url, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    });

    const json = await res.json();
    showToast(json.status === 'success' ? 'success' : 'danger', json.message);
    bootstrap.Modal.getInstance(document.getElementById('approvalModal')).hide();
    loadFaqs();
}

/* ================= ACTIONS ================= */
function viewFaq(id) {
    window.location.href = `view.php?id=${id}`;
}

function deleteFaq(id) {
    if (!IS_SUPER_ADMIN) return;
    if (!confirm('This will permanently delete the FAQ. Continue?')) return;

    fetch(`${ADMIN}api/faqs/delete.php`, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ faq_id: id })
    })
    .then(r => r.json())
    .then(r => {
        showToast(r.status === 'success' ? 'success' : 'danger', r.message);
        loadFaqs();
    });
}

/* ================= INIT ================= */
loadFaqs();
</script>

</body>
</html>
