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

<!-- Header -->
<div class="card mb-4">
    <div class="card-body d-flex justify-content-between align-items-center">
        <span class="text-muted">Manage blog tags</span>
        <button class="btn btn-success" onclick="openCreateModal()">
            <i class="bi bi-plus-lg me-1"></i> Add Tag
        </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="tagRows">
<tr>
    <td colspan="7" class="text-center text-muted">Loading tags…</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="tagModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">

<div class="modal-header">
    <h5 class="modal-title" id="tagModalTitle">Add Tag</h5>
    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>

<div class="modal-body">
    <input type="hidden" id="tag_id">
    <label class="form-label">Tag Name</label>
    <input type="text" id="tag_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="saveTag()">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 Tag</h5>
</div>

<div class="modal-body text-center">
    <p>This action is irreversible.</p>
    <input type="hidden" id="delete_tag_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/tags/list.php";
const CREATE_API     = "<?= ADMIN_BASE_URL ?>api/blogs/tags/create.php";
const UPDATE_API     = "<?= ADMIN_BASE_URL ?>api/blogs/tags/update.php";
const DEACTIVATE_API = "<?= ADMIN_BASE_URL ?>api/blogs/tags/deactivate.php";
const ACTIVATE_API   = "<?= ADMIN_BASE_URL ?>api/blogs/tags/activate.php";
const DELETE_API     = "<?= ADMIN_BASE_URL ?>api/blogs/tags/delete.php";

/* ================= STATE ================= */
let tagModal, deleteModal, notifyModal;
let allTags = [];
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;
    document.querySelector('#notifyModal .modal-header')
        .className = `modal-header py-2 bg-${type} text-white`;
    notifyModal.show();
}

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

/* ================= FETCH ================= */
function fetchTags() {
    fetch(LIST_API)
        .then(r => r.json())
        .then(res => {
            if (res.status !== 'success') {
                showNotification(res.message, 'danger');
                return;
            }
            allTags = res.data || [];
            renderPage(1);
        });
}

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

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

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

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

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

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

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

    renderPagination(Math.ceil(allTags.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}`;
}

/* ================= REDIRECT ================= */
function openBlogsByTag(tagId) {
    window.location.href =
        "<?= ADMIN_BASE_URL ?>blogs/index.php?tag_id=" + tagId;
}

/* ================= CRUD ================= */
function openCreateModal() {
    document.getElementById('tagModalTitle').innerText = 'Add Tag';
    document.getElementById('tag_id').value = '';
    document.getElementById('tag_name').value = '';
    tagModal.show();
}

function openEditModal(id, name) {
    document.getElementById('tagModalTitle').innerText = 'Edit Tag';
    document.getElementById('tag_id').value = id;
    document.getElementById('tag_name').value = name;
    tagModal.show();
}

function saveTag() {
    const id = document.getElementById('tag_id').value;
    const name = document.getElementById('tag_name').value.trim();
    if (!name) return showNotification('Tag name is required', 'warning');

    const api = id ? UPDATE_API : CREATE_API;
    const payload = id ? { tag_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;
        }
        tagModal.hide();
        showNotification(res.message, 'success');
        fetchTags();
    });
}

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

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

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

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

</body>
</html>
