<?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' => 'Retail Categories']); ?>
<?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' => 'Catalog',
    'title'     => 'Retail Categories'
]); ?>

<!-- ================= ACTION BAR ================= -->
<div class="card mb-3">
<div class="card-body text-end">
<a href="<?= ADMIN_BASE_URL ?>retail-products/create-category.php"
   class="btn btn-success">
<i class="bi bi-plus-lg me-1"></i> Add Category
</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>Image</th>
    <th>Name</th>
    <th>Short Description</th>
    <th>Status</th>
    <th>Updated</th>
    <th>Actions</th>
</tr>
</thead>

<tbody id="categoryRows">
<tr>
    <td colspan="7" class="text-center text-muted">
        Loading categories…
    </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 Category</h6>
</div>

<div class="modal-body text-center">
    <div id="deleteError"
         class="alert alert-danger d-none mb-2"></div>

    <p>
        Category is connected to one or more retail products.
        <br>Please reassign or delete products first.
    </p>

    <input type="hidden" id="delete_category_id">

    <button class="btn btn-danger w-100"
            onclick="confirmDeleteCategory()">
        Delete
    </button>
</div>

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

<script>
/* ================= CONFIG ================= */
const ADMIN = "<?= ADMIN_BASE_URL ?>";
const API_LIST   = `${ADMIN}api/retail-categories/list.php`;
const API_DELETE = `${ADMIN}api/retail-categories/delete.php`;
const CAN_DELETE = <?= $canDelete ? 'true' : 'false' ?>;

let deleteModal;

/* ================= INIT ================= */
document.addEventListener('DOMContentLoaded', () => {
    deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    loadCategories();
});

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

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

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

        res.data.forEach((c, i) => {

            const img = c.image_path
                ? `<img src="<?= APP_ROOT ?>${c.image_path}"
                        alt="${escapeHtml(c.image_alt ?? c.category_name)}"
                        style="width:48px;height:48px;
                               object-fit:cover;border-radius:6px;">`
                : `<span class="text-muted">—</span>`;

            let deleteBtn = '';
            if (CAN_DELETE) {
                deleteBtn = `
                <button class="btn btn-sm btn-light-danger"
                        title="Delete"
                        onclick="openDeleteModal(${c.id})">
                    <i class="bi bi-trash"></i>
                </button>`;
            }

            tbody.innerHTML += `
<tr>
<td>${i + 1}</td>

<td>${img}</td>

<td><strong>${escapeHtml(c.category_name)}</strong></td>

<td style="
    max-width:320px;
    display:-webkit-box;
    -webkit-line-clamp:4;
    -webkit-box-orient:vertical;
    overflow:hidden;">
${escapeHtml(c.short_description ?? '-')}
</td>

<td>
<span class="badge bg-${c.status === 'Active' ? 'success' : 'secondary'}">
${c.status}
</span>
</td>

<td>${c.updated_at}</td>

<td class="d-flex gap-1">

<a href="${ADMIN}retail-products/view-category.php?id=${c.id}"
   class="btn btn-sm btn-light-info"
   title="View">
<i class="bi bi-eye"></i>
</a>

<a href="${ADMIN}retail-products/edit-category.php?id=${c.id}"
   class="btn btn-sm btn-light-warning"
   title="Edit">
<i class="bi bi-pencil-square"></i>
</a>

${deleteBtn}

</td>
</tr>`;
        });
    });
}

/* ================= DELETE ================= */
function openDeleteModal(id) {
    document.getElementById('delete_category_id').value = id;
    document.getElementById('deleteError').classList.add('d-none');
    deleteModal.show();
}

function confirmDeleteCategory() {
    const errorBox = document.getElementById('deleteError');

    fetch(API_DELETE, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            category_id: document.getElementById('delete_category_id').value
        })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status !== 'success') {
            errorBox.innerText = res.message;
            errorBox.classList.remove('d-none');
            return;
        }
        deleteModal.hide();
        loadCategories();
    });
}

/* ================= UTIL ================= */
function escapeHtml(str) {
    return String(str)
        .replace(/&/g,"&amp;")
        .replace(/</g,"&lt;")
        .replace(/>/g,"&gt;")
        .replace(/"/g,"&quot;")
        .replace(/'/g,"&#039;");
}
</script>

</body>
</html>
