<?php
declare(strict_types=1);

require_once __DIR__ . '/../security/auth_guard.php';
require_once __DIR__ . '/../partials/main.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Blog 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'     => 'Blog Categories'
]); ?>

<!-- Header -->
<div class="card mb-4">
    <div class="card-body d-flex justify-content-between align-items-center">
        <span class="text-muted">Manage blog categories</span>
        <button class="btn btn-success" onclick="openCreateModal()">
            <i class="bi bi-plus-lg me-1"></i> Add Category
        </button>
    </div>
</div>

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

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

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

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

</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">
    <h5 class="modal-title text-danger">Delete Category</h5>
</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>

<!-- NOTIFICATION MODAL -->
<div class="modal fade" id="notifyModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered modal-sm">
<div class="modal-content">
<div class="modal-header py-2">
    <h5 class="modal-title" id="notifyTitle"></h5>
    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body text-center">
    <p id="notifyMessage" class="mb-0"></p>
</div>
<div class="modal-footer py-2 justify-content-center">
    <button class="btn btn-primary btn-sm" data-bs-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>

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

/* ================= STATE ================= */
let categoryModal, deleteModal, notifyModal;
let allCategories = [];
let currentPage = 1;
const perPage = 10;

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

function showNotification(message, type = 'success') {
    const titles = {
        success: 'Success',
        danger: 'Error',
        warning: 'Warning',
        info: 'Info'
    };
    document.getElementById('notifyTitle').innerText = titles[type];
    document.getElementById('notifyMessage').innerText = message;

    const header = document.querySelector('#notifyModal .modal-header');
    header.className = `modal-header py-2 bg-${type} text-white`;

    notifyModal.show();
}

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

/* ================= FETCH ================= */
function fetchCategories() {
    fetch(LIST_API)
        .then(r => r.json())
        .then(res => {
            if (res.status !== 'success') {
                showNotification(res.message, 'danger');
                return;
            }
            allCategories = Array.isArray(res.data) ? res.data : [];
            renderPage(1);
        });
}

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

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

    const start = (page - 1) * perPage;
    const slice = allCategories.slice(start, start + perPage);

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

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

        const statusBtn = c.status === 'Active'
            ? `<button class="btn btn-sm btn-outline-warning" onclick="deactivate(${c.id})">Deactivate</button>`
            : `<button class="btn btn-sm btn-outline-success" onclick="activate(${c.id})">Activate</button>`;

        tbody.innerHTML += `
            <tr>
                <td>${start + i + 1}</td>
                <td><strong>${escapeHtml(c.name)}</strong></td>
                <td class="text-muted">${escapeHtml(c.slug)}</td>
                <td>${statusBadge}</td>
                <td>
                    <span class="badge bg-info"
                          style="cursor:pointer"
                          title="View blogs in this category"
                          onclick="openBlogsByCategory(${c.id})">
                        ${c.blog_count ?? 0}
                    </span>
                </td>
                <td>${escapeHtml(c.created_at)}</td>
                <td class="d-flex gap-1">
                    <button class="btn btn-sm btn-outline-primary"
                        onclick="openEditModal(${c.id}, '${escapeHtml(c.name)}')">
                        Edit
                    </button>
                    ${statusBtn}
                    <button class="btn btn-sm btn-outline-danger"
                        onclick="openDeleteModal(${c.id})">
                        Delete
                    </button>
                </td>
            </tr>`;
    });

    renderPagination(Math.ceil(allCategories.length / perPage));
}

/* ================= PAGINATION ================= */
function renderPagination(totalPages) {
    const pag = document.getElementById('pagination');
    const info = document.getElementById('paginationInfo');

    pag.innerHTML = '';
    info.innerText = '';

    if (totalPages <= 1) return;

    for (let p = 1; p <= totalPages; p++) {
        pag.innerHTML += `
            <li class="page-item ${p === currentPage ? 'active' : ''}">
                <a class="page-link" href="javascript:void(0)" onclick="renderPage(${p})">${p}</a>
            </li>`;
    }

    info.innerText = `Showing page ${currentPage} of ${totalPages}`;
}

/* ================= BLOG FILTER REDIRECT ================= */
function openBlogsByCategory(categoryId) {
    window.location.href =
        "<?= ADMIN_BASE_URL ?>blogs/index.php?category_id=" + categoryId;
}

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

function saveCategory() {
    const id = document.getElementById('category_id').value;
    const name = document.getElementById('category_name').value.trim();
    if (!name) return showNotification('Category name is required', 'warning');

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

    fetch(api, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(payload)
    })
    .then(r => r.json())
    .then(res => {
        if (res.status !== 'success') {
            showNotification(res.message, 'danger');
            return;
        }
        categoryModal.hide();
        showNotification(res.message, 'success');
        fetchCategories();
    });
}

function deactivate(id) {
    fetch(DEACTIVATE_API, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ category_id: id })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status !== 'success') {
            showNotification(res.message, 'danger');
            return;
        }
        showNotification('Category deactivated successfully', 'success');
        fetchCategories();
    });
}

function activate(id) {
    fetch(ACTIVATE_API, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ category_id: id })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status !== 'success') {
            showNotification(res.message, 'danger');
            return;
        }
        showNotification('Category activated successfully', 'success');
        fetchCategories();
    });
}

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

function confirmDelete() {
    fetch(DELETE_API, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            category_id: document.getElementById('delete_category_id').value
        })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status !== 'success') {
            showNotification(res.message, 'danger');
            return;
        }
        deleteModal.hide();
        showNotification('Category deleted successfully', 'success');
        fetchCategories();
    });
}
</script>

</body>
</html>
