<?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 CHECK ================= */
$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'], true);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', [
    'title' => 'Hospitality Sections'
]); ?>
<?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' => 'Hospitality',
    'title'     => 'Hospitality Product Sections'
]); ?>

<!-- ================= ACTION BAR ================= -->
<div class="card mb-4">
<div class="card-body d-flex justify-content-end">
    <a href="<?= ADMIN_BASE_URL ?>hospitality-products/sections-create.php"
       class="btn btn-success">
        <i class="bi bi-plus-lg me-1"></i> Add Section
    </a>
</div>
</div>

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

<table class="table align-middle text-nowrap">
<thead>
<tr>
    <th>#</th>
    <th>Preview</th>
    <th>Product</th>
    <th>Section Key</th>
    <th>Title</th>
    <th>Type</th>
    <th>Priority</th>
    <th>Status</th>
    <th>Approval</th>
    <th>Actions</th>
</tr>
</thead>

<tbody id="sectionRows">
<tr>
    <td colspan="10" class="text-center text-muted">
        Loading sections…
    </td>
</tr>
</tbody>
</table>

</div>
</div>

</div>
</main>

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

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

<!-- ================= 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 Section</h6>
</div>
<div class="modal-body text-center">
    <p>This will deactivate the section.</p>
    <input type="hidden" id="delete_section_id">
    <button class="btn btn-danger w-100" onclick="confirmDelete()">
        Delete
    </button>
</div>
</div>
</div>
</div>

<script>
const API_LIST =
    "<?= ADMIN_BASE_URL ?>api/hospitality-product-sections/list-all.php";
const API_DELETE =
    "<?= ADMIN_BASE_URL ?>api/hospitality-product-sections/delete.php";

let deleteModal;

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

/* ================= LOAD SECTIONS ================= */
function loadSections() {
    fetch(API_LIST, { credentials: 'include' })
    .then(r => r.json())
    .then(res => {

        const tbody = document.getElementById('sectionRows');
        tbody.innerHTML = '';

        if (res.status !== 'success' || !res.data.sections.length) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="10"
                        class="text-center text-muted">
                        No sections found
                    </td>
                </tr>`;
            return;
        }

        res.data.sections.forEach((s, i) => {

            let preview = '-';
            if (s.file_type === 'Image' && s.file_path) {
                preview = `
                    <img src="${s.file_path}"
                         width="70"
                         class="rounded border">`;
            } else if (s.thumbnail_path) {
                preview = `
                    <img src="${s.thumbnail_path}"
                         width="70"
                         class="rounded border">`;
            }

            const statusBadge = `
                <span class="badge bg-${
                    s.status === 'Active'
                        ? 'success'
                        : s.status === 'Draft'
                        ? 'warning'
                        : 'secondary'
                }">
                    ${s.status}
                </span>`;

            const approvalBadge = `
                <span class="badge bg-${
                    s.approval_status === 'Approved'
                        ? 'success'
                        : s.approval_status === 'Rejected'
                        ? 'danger'
                        : 'warning'
                }">
                    ${s.approval_status}
                </span>`;

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

            tbody.innerHTML += `
<tr>
<td>${i + 1}</td>
<td>${preview}</td>
<td><strong>${s.product_title}</strong></td>
<td><code>${s.section_key ?? '-'}</code></td>
<td>${s.section_title ?? '-'}</td>
<td>${s.file_type}</td>
<td>${s.priority}</td>
<td>${statusBadge}</td>
<td>${approvalBadge}</td>
<td class="d-flex gap-1">
    <a href="<?= ADMIN_BASE_URL ?>hospitality-products/sections-view.php?id=${s.id}"
       class="btn btn-sm btn-light-info">
        <i class="bi bi-eye"></i>
    </a>
    <a href="<?= ADMIN_BASE_URL ?>hospitality-products/sections-edit.php?id=${s.id}"
       class="btn btn-sm btn-light-warning">
        <i class="bi bi-pencil-square"></i>
    </a>
    ${deleteBtn}
</td>
</tr>`;
        });
    })
    .catch(() => {
        document.getElementById('sectionRows').innerHTML = `
            <tr>
                <td colspan="10"
                    class="text-center text-danger">
                    Failed to load sections
                </td>
            </tr>`;
    });
}

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

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

</body>
</html>
