<?php
declare(strict_types=1);

/* ================= AUTH ================= */
require_once __DIR__ . '/../security/auth_guard_web.php';
require_once __DIR__ . '/../partials/main.php';
require_once __DIR__ . '/../config/database.php';

/* ================= ROLE ================= */
$db = Database::getInstance();
$stmt = $db->prepare("
    SELECT r.name
    FROM roles r
    JOIN employees e ON e.role_id = r.id
    WHERE e.id = :id
");
$stmt->execute(['id' => $_SESSION['employee_id']]);
$userRole = $stmt->fetchColumn();

$canDelete = in_array($userRole, ['Super Admin','Admin','SEO Manager'], true);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Blogs']); ?>
<?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'     => 'Blogs'
]); ?>

<!-- ================= FILTERS ================= -->
<div class="card mb-4">
<div class="card-body">
<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="Title or excerpt">
</div>

<div class="col-md-2">
    <label class="form-label">Status</label>
    <select id="status" class="form-select">
        <option value="">All</option>
        <option value="Active">Active</option>
        <option value="Draft">Draft</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>
    </select>
</div>

<div class="col-md-2">
    <button class="btn btn-primary w-100" onclick="loadBlogs(1)">
        Apply
    </button>
</div>

<div class="col-md-3 text-end">
    <a href="<?= ADMIN_BASE_URL ?>blogs/create.php"
       class="btn btn-success">
        <i class="bi bi-plus-lg me-1"></i> Add Blog
    </a>
</div>

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

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

<table class="table align-middle text-nowrap">
<thead>
<tr>
    <th>#</th>
    <th>Image</th>
    <th>Title</th>
    <th>Author</th>
    <th>Status</th>
    <th>Approval</th>
    <th>Published</th>
    <th>Created</th>
    <th>Actions</th>
</tr>
</thead>

<tbody id="blogRows">
<tr>
    <td colspan="9" class="text-center text-muted">Loading blogs…</td>
</tr>
</tbody>
</table>

<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'; ?>

<!-- ================= MAIN MODAL ================= -->
<div class="modal fade" id="blogModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">

<div class="modal-header">
    <h5 class="modal-title" id="blogModalTitle"></h5>
    <button class="btn-close" data-bs-dismiss="modal"></button>
</div>

<div class="modal-body">
    <input type="hidden" id="modal_blog_id">

    <div id="modalWarning" class="mb-3 d-none"></div>

    <!-- STATUS -->
    <div id="statusBlock" class="mb-3 d-none">
        <label class="form-label">Status</label>
        <select id="modal_status" class="form-select">
            <option value="Active">Active</option>
            <option value="Draft">Draft</option>
            <option value="InActive">Inactive</option>
        </select>
    </div>

    <!-- REJECTION -->
    <div id="rejectionBlock" class="mb-3 d-none">
        <label class="form-label">Rejection Reason</label>
        <textarea id="rejection_reason"
                  class="form-control"
                  rows="3"></textarea>
    </div>
</div>

<div class="modal-footer">
    <button class="btn btn-success d-none" id="approveBtn" onclick="approveBlog()">Approve</button>
    <button class="btn btn-danger d-none" id="rejectBtn" onclick="rejectBlog()">Reject</button>
    <button class="btn btn-primary d-none" id="saveStatusBtn" onclick="saveStatus()">Save</button>
    <button class="btn btn-secondary" data-bs-dismiss="modal">Close</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 Blog</h6>
</div>
<div class="modal-body text-center">
    <p>This action is irreversible.</p>
    <input type="hidden" id="delete_blog_id">
    <button class="btn btn-danger w-100" onclick="confirmDeleteBlog()">
        Delete
    </button>
</div>
</div>
</div>
</div>

<script>
const API_LIST   = "<?= ADMIN_BASE_URL ?>api/blogs/list.php";
const API_APPROVE= "<?= ADMIN_BASE_URL ?>api/blogs/approve.php";
const API_REJECT = "<?= ADMIN_BASE_URL ?>api/blogs/reject.php";
const API_STATUS = "<?= ADMIN_BASE_URL ?>api/blogs/update-status.php";
const API_DELETE = "<?= ADMIN_BASE_URL ?>api/blogs/delete.php";

let blogModal, deleteModal;
let currentPage = 1;

document.addEventListener('DOMContentLoaded', () => {
    blogModal   = new bootstrap.Modal(document.getElementById('blogModal'));
    deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    loadBlogs(1);
});

/* ================= LOAD ================= */
function loadBlogs(page = 1) {
    currentPage = page;

    const params = new URLSearchParams({
        context: 'backend',
        page,
        search: document.getElementById('search').value,
        status: document.getElementById('status').value,
        approval_status: document.getElementById('approval_status').value
    });

    fetch(API_LIST + '?' + params.toString(), { credentials: 'include' })
    .then(r => r.json())
    .then(res => {

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

        const blogs = res.data.blogs;
        const p = res.data.pagination;
        const tbody = document.getElementById('blogRows');
        tbody.innerHTML = '';

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

        blogs.forEach((b, i) => {

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

            const statusBadge = `
                <span class="badge bg-${b.status === 'Active' ? 'success' : b.status === 'Draft' ? 'warning' : 'secondary'}
                      cursor-pointer"
                      onclick="openStatusModal(${b.id}, '${b.status}')">
                    ${b.status}
                </span>`;

            const approvalBadge =
                `<span class="badge bg-${b.approval_status === 'Approved' ? 'success' : 'warning'}
                      cursor-pointer"
                      onclick="openApprovalModal(${b.id}, ${b.is_approval_ready}, '${b.approval_status}')">
                    ${b.approval_status}
                </span>`;

            const deleteBtn = <?= $canDelete ? 'true' : 'false' ?> ? `
                <button class="btn btn-sm btn-light-danger"
                        onclick="openDeleteModal(${b.id})">
                    <i class="bi bi-trash"></i>
                </button>` : '';

            tbody.innerHTML += `
<tr>
<td>${(p.page - 1) * p.limit + i + 1}</td>
<td>${img}</td>
<td><strong>${b.title}</strong></td>
<td>${b.author_name}</td>
<td>${statusBadge}</td>
<td>${approvalBadge}</td>
<td>${b.published_at ?? '-'}</td>
<td>${b.created_at}</td>
<td class="d-flex gap-1">
    <a href="<?= ADMIN_BASE_URL ?>blogs/view.php?id=${b.id}"
       class="btn btn-sm btn-light-info"><i class="bi bi-eye"></i></a>
    <a href="<?= ADMIN_BASE_URL ?>blogs/edit.php?id=${b.id}"
       class="btn btn-sm btn-light-warning"><i class="bi bi-pencil-square"></i></a>
    ${deleteBtn}
</td>
</tr>`;
        });

        const pag = document.getElementById('pagination');
        pag.innerHTML = '';
        for (let i = 1; i <= p.pages; i++) {
            pag.innerHTML += `
                <li class="page-item ${i === p.page ? 'active' : ''}">
                    <a class="page-link" href="javascript:void(0)"
                       onclick="loadBlogs(${i})">${i}</a>
                </li>`;
        }

        document.getElementById('paginationInfo').innerText =
            `Showing page ${p.page} of ${p.pages}`;
    });
}

/* ================= APPROVAL ================= */
function openApprovalModal(id, isReady, approvalStatus) {

    document.getElementById('modal_blog_id').value = id;
    document.getElementById('blogModalTitle').innerText = 'Blog Approval';

    document.getElementById('statusBlock').classList.add('d-none');
    document.getElementById('rejectionBlock').classList.add('d-none');
    document.getElementById('rejection_reason').value = '';

    document.getElementById('approveBtn').classList.add('d-none');
    document.getElementById('rejectBtn').classList.remove('d-none');
    document.getElementById('saveStatusBtn').classList.add('d-none');

    let msg = '';

    if (!isReady) {
        msg = `<div class="alert alert-danger">
            <strong>Approval blocked</strong>
            <ul class="mb-0 mt-2">
                <li>Featured image missing</li>
                <li>SEO title & description missing</li>
                <li>Excerpt too short</li>
                <li>Content too short</li>
            </ul>
        </div>`;
    }

    if (approvalStatus === 'Approved') {
        msg += `<div class="alert alert-warning mt-2">
            Already approved. You may reject to move back to Pending.
        </div>`;
    }

    if (isReady && approvalStatus !== 'Approved') {
        document.getElementById('approveBtn').classList.remove('d-none');
    }

    document.getElementById('modalWarning').innerHTML = msg;
    document.getElementById('modalWarning').classList.remove('d-none');

    blogModal.show();
}

function approveBlog() {
    fetch(API_APPROVE, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({ blog_id: document.getElementById('modal_blog_id').value })
    }).then(() => { blogModal.hide(); loadBlogs(currentPage); });
}

function rejectBlog() {
    document.getElementById('rejectionBlock').classList.remove('d-none');

    const reason = document.getElementById('rejection_reason').value.trim();
    if (!reason) return;

    fetch(API_REJECT, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            blog_id: document.getElementById('modal_blog_id').value,
            rejection_reason: reason
        })
    }).then(() => { blogModal.hide(); loadBlogs(currentPage); });
}

/* ================= STATUS ================= */
function openStatusModal(id, status) {
    document.getElementById('modal_blog_id').value = id;
    document.getElementById('blogModalTitle').innerText = 'Update Status';

    document.getElementById('modal_status').value = status;
    document.getElementById('statusBlock').classList.remove('d-none');
    document.getElementById('modalWarning').classList.add('d-none');

    document.getElementById('approveBtn').classList.add('d-none');
    document.getElementById('rejectBtn').classList.add('d-none');
    document.getElementById('saveStatusBtn').classList.remove('d-none');

    blogModal.show();
}

function saveStatus() {
    fetch(API_STATUS, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            blog_id: document.getElementById('modal_blog_id').value,
            status: document.getElementById('modal_status').value
        })
    }).then(() => { blogModal.hide(); loadBlogs(currentPage); });
}

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

function confirmDeleteBlog() {
    fetch(API_DELETE, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            blog_id: document.getElementById('delete_blog_id').value
        })
    }).then(() => {
        deleteModal.hide();
        loadBlogs(currentPage);
    });
}
</script>

</body>
</html>
