<?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('../partials/title-meta.php', ['title' => 'FAQ Categories']); ?>
<?php include '../partials/head-css.php'; ?>
</head>

<body>
<div id="layout-wrapper">

<?php include '../partials/header.php'; ?>
<?php include '../partials/sidebar.php'; ?>
<?php include '../partials/horizontal.php'; ?>

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

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

<!-- HEADER -->
<div class="card mb-4">
    <div class="card-body d-flex justify-content-between align-items-center">
        <span class="text-muted">Manage FAQ categories</span>
        <?php if ($isAdmin): ?>
        <button class="btn btn-success" onclick="openCreateModal()">
            <i class="bi bi-plus-lg me-1"></i> Add Category
        </button>
        <?php endif; ?>
    </div>
</div>

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

<table class="table table-bordered align-middle text-nowrap">
<thead class="table-light">
<tr>
    <th>#</th>
    <th>Name</th>
    <th>Slug</th>
    <th>Status</th>
    <th>Created</th>
    <th>Actions</th>
</tr>
</thead>

<tbody id="categoryRows">
<tr>
    <td colspan="6" class="text-center text-muted">
        Loading categories…
    </td>
</tr>
</tbody>
</table>

</div>
</div>

</div>
</main>

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

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

<!-- CREATE / EDIT MODAL -->
<div class="modal fade" id="categoryModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
    <h5 class="modal-title" id="categoryModalTitle">Add Category</h5>
    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
    <input type="hidden" id="category_id">
    <label class="form-label">Category Name</label>
    <input type="text" id="category_name" class="form-control">
</div>
<div class="modal-footer">
    <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
    <button class="btn btn-primary" onclick="saveCategory()">Save</button>
</div>
</div>
</div>
</div>

<!-- DELETE MODAL -->
<div class="modal fade" id="deleteModal" tabindex="-1">
<div class="modal-dialog modal-sm modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-danger text-white">
    <h6 class="modal-title">Delete Category</h6>
</div>
<div class="modal-body text-center">
    <p>This action is irreversible.</p>
    <input type="hidden" id="delete_category_id">
    <button class="btn btn-danger w-100" onclick="confirmDelete()">Delete</button>
</div>
</div>
</div>
</div>

<!-- TOAST -->
<div class="toast-container position-fixed top-0 end-0 p-3" style="z-index:1100">
<div id="appToast" class="toast border-0">
<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>

<script>
/* ================= API PATHS ================= */
const API_BASE = "<?= ADMIN_BASE_URL ?>api/faqs/categories/";
const LIST_API       = API_BASE + "list.php";
const CREATE_API     = API_BASE + "create.php";
const UPDATE_API     = API_BASE + "update.php";
const DELETE_API     = API_BASE + "delete.php";
const DEACTIVATE_API = API_BASE + "deactivate.php";
const ACTIVATE_API   = API_BASE + "activate.php";

/* ================= STATE ================= */
let categoryModal, deleteModal;
let categories = [];

/* ================= INIT ================= */
document.addEventListener('DOMContentLoaded', () => {
    categoryModal = new bootstrap.Modal(document.getElementById('categoryModal'));
    deleteModal   = new bootstrap.Modal(document.getElementById('deleteModal'));
    loadCategories();
});

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

function escapeHtml(str) {
    return String(str ?? '')
        .replace(/&/g,"&amp;")
        .replace(/</g,"&lt;")
        .replace(/>/g,"&gt;")
        .replace(/"/g,"&quot;");
}

/* ================= LOAD ================= */
async function loadCategories() {
    try {
        const res = await fetch(LIST_API + '?context=backend', {
            credentials: 'include'
        });
        const json = await res.json();

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

        categories = json.data || [];
        renderTable();

    } catch (e) {
        console.error(e);
        showToast('danger', 'Failed to load categories');
    }
}

/* ================= RENDER ================= */
function renderTable() {
    const tbody = document.getElementById('categoryRows');
    tbody.innerHTML = '';

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

    categories.forEach((c, i) => {

        const statusBadge = c.status === 'Active'
            ? '<span class="badge bg-success">Active</span>'
            : '<span class="badge bg-secondary">Inactive</span>';

        tbody.innerHTML += `
<tr>
<td>${i + 1}</td>
<td><strong>${escapeHtml(c.name)}</strong></td>
<td class="text-muted">${escapeHtml(c.slug)}</td>
<td>${statusBadge}</td>
<td>${c.created_at}</td>
<td class="d-flex gap-1">

<?php if ($isAdmin): ?>

<button class="btn btn-light-primary icon-btn-sm"
        title="Edit Category"
        onclick="openEditModal(${c.id}, '${escapeHtml(c.name)}')">
    <i class="bi bi-pencil-square"></i>
</button>

${c.status === 'Active' ? `
<button class="btn btn-light-warning icon-btn-sm"
        title="Deactivate Category"
        onclick="deactivate(${c.id})">
    <i class="bi bi-slash-circle"></i>
</button>
` : `
<button class="btn btn-light-success icon-btn-sm"
        title="Activate Category"
        onclick="activate(${c.id})">
    <i class="bi bi-check-circle"></i>
</button>
`}

<?php endif; ?>

<?php if ($isSuperAdmin): ?>

<button class="btn btn-light-danger icon-btn-sm"
        title="Delete Category"
        onclick="openDeleteModal(${c.id})">
    <i class="bi bi-trash"></i>
</button>

<?php endif; ?>

</td>
</tr>`;
    });
}

/* ================= CRUD ================= */
function openCreateModal() {
    document.getElementById('categoryModalTitle').innerText = 'Add Category';
    document.getElementById('category_id').value = '';
    document.getElementById('category_name').value = '';
    categoryModal.show();
}

function openEditModal(id, name) {
    document.getElementById('categoryModalTitle').innerText = 'Edit Category';
    document.getElementById('category_id').value = id;
    document.getElementById('category_name').value = name;
    categoryModal.show();
}

async function saveCategory() {
    const id = document.getElementById('category_id').value;
    const name = document.getElementById('category_name').value.trim();

    if (!name) {
        showToast('warning', 'Category name is required');
        return;
    }

    const api = id ? UPDATE_API : CREATE_API;
    const payload = id ? { category_id: id, name } : { name };

    const res = await fetch(api, {
        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);

    if (json.status === 'success') {
        categoryModal.hide();
        loadCategories();
    }
}

/* ================= STATUS ================= */
async function deactivate(id) {
    const res = await fetch(DEACTIVATE_API, {
        method:'POST',
        credentials:'include',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ category_id:id })
    });
    const json = await res.json();
    showToast(json.status === 'success' ? 'success' : 'danger', json.message);
    loadCategories();
}

async function activate(id) {
    const res = await fetch(ACTIVATE_API, {
        method:'POST',
        credentials:'include',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ category_id:id })
    });
    const json = await res.json();
    showToast(json.status === 'success' ? 'success' : 'danger', json.message);
    loadCategories();
}

/* ================= DELETE ================= */
function openDeleteModal(id) {
    document.getElementById('delete_category_id').value = id;
    deleteModal.show();
}

async function confirmDelete() {
    const id = document.getElementById('delete_category_id').value;

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

    const json = await res.json();
    showToast(json.status === 'success' ? 'success' : 'danger', json.message);

    if (json.status === 'success') {
        deleteModal.hide();
        loadCategories();
    }
}
</script>

</body>
</html>
