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

<!-- ================= ACTION BAR ================= -->
<div class="card mb-4">
<div class="card-body d-flex justify-content-end">
    <a href="<?= ADMIN_BASE_URL ?>offers/create.php"
       class="btn btn-success">
        <i class="bi bi-plus-lg me-1"></i> Add Offer
    </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>Desktop</th>
    <th>Mobile</th>
    <th>Title</th>
    <th>Price</th>
    <th>Status</th>
    <th>Duration</th>
    <th>Actions</th>
</tr>
</thead>

<tbody id="offerRows">
<tr>
    <td colspan="8" class="text-center text-muted">Loading offers…</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 Offer</h6>
</div>
<div class="modal-body text-center">
    <p>This will permanently delete offer & images.</p>
    <input type="hidden" id="delete_offer_id">
    <button class="btn btn-danger w-100" onclick="confirmDelete()">Delete</button>
</div>
</div>
</div>
</div>

<script>
const API_LIST   = "<?= ADMIN_BASE_URL ?>api/offers/list.php";
const API_DELETE = "<?= ADMIN_BASE_URL ?>api/offers/delete.php";

let deleteModal;

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

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

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

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

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

            const desktopImg = `
                <img src="${o.desktop_image}"
                     width="70" class="rounded">`;

            const mobileImg = `
                <img src="${o.mobile_image}"
                     width="45" class="rounded">`;

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

            const duration = `
                <small>
                    ${o.start_date}<br>
                    <strong>to</strong><br>
                    ${o.end_date}
                </small>`;

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

            tbody.innerHTML += `
<tr>
<td>${i + 1}</td>
<td>${desktopImg}</td>
<td>${mobileImg}</td>
<td><strong>${o.title}</strong></td>
<td>₹${o.offer_price}</td>
<td>${statusBadge}</td>
<td>${duration}</td>
<td class="d-flex gap-1">
    <a href="<?= ADMIN_BASE_URL ?>offers/view.php?id=${o.id}"
       class="btn btn-sm btn-light-info"><i class="bi bi-eye"></i></a>
    <a href="<?= ADMIN_BASE_URL ?>offers/edit.php?id=${o.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_offer_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_offer_id').value
        })
    }).then(() => {
        deleteModal.hide();
        loadOffers();
    });
}
</script>

</body>
</html>
