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

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

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

<table class="table align-middle text-nowrap">
<thead>
<tr>
    <th>#</th>
    <th>Title</th>
    <th>Type</th>
    <th>Usage</th>
    <th>Priority</th>
    <th>Status</th>
    <th>Approval</th>
    <th>Created</th>
    <th>Actions</th>
</tr>
</thead>

<tbody id="productRows">
<tr>
    <td colspan="9" class="text-center text-muted">
        Loading products…
    </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 Product</h6>
</div>
<div class="modal-body text-center">
    <p>This will permanently delete this product.</p>
    <input type="hidden" id="delete_product_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-products/list.php";
const API_DELETE =
    "<?= ADMIN_BASE_URL ?>api/hospitality-products/delete.php";

let deleteModal;

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

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

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

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

        res.data.items.forEach((p, i) => {

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

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

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

            tbody.innerHTML += `
<tr>
<td>${i + 1}</td>
<td><strong>${p.title}</strong></td>
<td>${p.product_type}</td>
<td>${p.usage_category ?? '-'}</td>
<td>${p.priority}</td>
<td>${statusBadge}</td>
<td>${approvalBadge}</td>
<td>${p.created_at}</td>
<td class="d-flex gap-1">
    <a href="<?= ADMIN_BASE_URL ?>hospitality-products/view.php?id=${p.id}"
       class="btn btn-sm btn-light-info">
        <i class="bi bi-eye"></i>
    </a>
    <a href="<?= ADMIN_BASE_URL ?>hospitality-products/edit.php?id=${p.id}"
       class="btn btn-sm btn-light-warning">
        <i class="bi bi-pencil-square"></i>
    </a>
    ${deleteBtn}
</td>
</tr>`;
        });
    });
}

/* ================= DELETE ================= */
function openDeleteModal(id) {
    document.getElementById('delete_product_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_product_id').value
        })
    }).then(() => {
        deleteModal.hide();
        loadProducts();
    });
}
</script>

</body>
</html>
