<?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' => 'Home Sliders']); ?>
<?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'     => 'Home Page Sliders'
]); ?>

<!-- ================= ACTION BAR ================= -->
<div class="card mb-4">
<div class="card-body d-flex justify-content-end">
    <a href="<?= ADMIN_BASE_URL ?>home-sliders/create.php"
       class="btn btn-success">
        <i class="bi bi-plus-lg me-1"></i> Add Slider
    </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>Priority</th>
    <th>Status</th>
    <th>Created</th>
    <th>Actions</th>
</tr>
</thead>

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

<script>
const API_LIST   = "<?= ADMIN_BASE_URL ?>api/home-sliders/list.php";
const API_DELETE = "<?= ADMIN_BASE_URL ?>api/home-sliders/delete.php";
const API_TOGGLE = "<?= ADMIN_BASE_URL ?>api/home-sliders/toggle-status.php";

let deleteModal;

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

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

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

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

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

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

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

            const statusBadge = `
                <span class="badge bg-${s.is_active == 1 ? 'success' : 'secondary'}
                      cursor-pointer"
                      onclick="toggleStatus(${s.id}, ${s.is_active})">
                    ${s.is_active == 1 ? 'Active' : 'Inactive'}
                </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>${desktopImg}</td>
<td>${mobileImg}</td>
<td><strong>${s.title ?? '-'}</strong></td>
<td>${s.priority}</td>
<td>${statusBadge}</td>
<td>${s.created_at}</td>
<td class="d-flex gap-1">
    <a href="<?= ADMIN_BASE_URL ?>home-sliders/view.php?id=${s.id}"
       class="btn btn-sm btn-light-info"><i class="bi bi-eye"></i></a>
    <a href="<?= ADMIN_BASE_URL ?>home-sliders/edit.php?id=${s.id}"
       class="btn btn-sm btn-light-warning"><i class="bi bi-pencil-square"></i></a>
    ${deleteBtn}
</td>
</tr>`;
        });
    });
}

/* ================= TOGGLE STATUS ================= */
function toggleStatus(id, currentStatus) {
    fetch(API_TOGGLE, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            id: id,
            is_active: currentStatus === 1 ? 0 : 1
        })
    }).then(() => loadSliders());
}

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

</body>
</html>
