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

<!-- ================= FILTERS ================= -->
<div class="card mb-4">
<div class="card-body">
<div class="row g-3 align-items-end">

<div class="col-md-3">
    <label class="form-label">Search</label>
    <input type="text" id="search" class="form-control" placeholder="Product name">
</div>

<div class="col-md-2">
    <label class="form-label">Status</label>
    <select id="status" class="form-select">
        <option value="">All</option>
        <option value="Active">Active</option>
        <option value="Draft">Draft</option>
        <option value="InActive">Inactive</option>
    </select>
</div>

<div class="col-md-2">
    <label class="form-label">Approval</label>
    <select id="approval_status" class="form-select">
        <option value="">All</option>
        <option value="Pending">Pending</option>
        <option value="Approved">Approved</option>
        <option value="Rejected">Rejected</option>
    </select>
</div>

<div class="col-md-2">
    <button class="btn btn-primary w-100" onclick="loadProducts(1)">Apply</button>
</div>

<div class="col-md-3 text-end">
    <a href="<?= ADMIN_BASE_URL ?>retail-products/create.php" class="btn btn-success">
        <i class="bi bi-plus-lg me-1"></i> Add Product
    </a>
</div>

</div>
</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>Product</th>
    <th>Category</th>
    <th>P. SleepId</th>
    <th>S. SleepId</th>
    <th>Variants</th>
    <th>Price Range</th>
    <th>Status</th>
    <th>Approval</th>
    <th>Actions</th>
</tr>
</thead>

<tbody id="productRows">
<tr>
    <td colspan="12" class="text-center text-muted">Loading products…</td>
</tr>
</tbody>
</table>

<div class="d-flex justify-content-between align-items-center mt-3">
    <div id="paginationInfo" class="text-muted"></div>
    <nav>
        <ul class="pagination pagination-primary mb-0" id="pagination"></ul>
    </nav>
</div>

</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 action is irreversible.</p>
    <input type="hidden" id="delete_product_id">
    <button class="btn btn-danger w-100" onclick="confirmDeleteProduct()">Delete</button>
</div>
</div>
</div>
</div>

<!-- ================= STATUS MODAL ================= -->
<div class="modal fade" id="statusModal" tabindex="-1">
<div class="modal-dialog modal-sm modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
    <h6 class="modal-title">Update Status</h6>
</div>
<div class="modal-body">
    <input type="hidden" id="status_product_id">
    <select id="new_status" class="form-select">
        <option value="Active">Active</option>
        <option value="Draft">Draft</option>
        <option value="InActive">InActive</option>
    </select>
    <button class="btn btn-primary w-100 mt-3" onclick="updateStatus()">Update</button>
</div>
</div>
</div>
</div>

<!-- ================= APPROVAL MODAL ================= -->
<div class="modal fade" id="approvalModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
    <h6 class="modal-title">Approval Action</h6>
</div>
<div class="modal-body">
    <input type="hidden" id="approval_product_id">

    <div id="rejectBox" class="d-none">
        <label class="form-label">Rejection Reason</label>
        <textarea id="rejection_reason" class="form-control" rows="3"></textarea>
        <button class="btn btn-danger w-100 mt-2" onclick="rejectProduct()">Confirm Reject</button>
    </div>

    <div class="d-flex gap-2 mt-3">
        <button class="btn btn-success w-50" onclick="approveProduct()">Approve</button>
        <button class="btn btn-outline-danger w-50" onclick="showReject()">Reject</button>
    </div>
</div>
</div>
</div>
</div>

<script>
const API_LIST   = "<?= ADMIN_BASE_URL ?>api/retail-products/list.php";
const API_DELETE = "<?= ADMIN_BASE_URL ?>api/retail-products/delete.php";
const API_STATUS = "<?= ADMIN_BASE_URL ?>api/retail-products/update-status.php";
const API_APPROVE = "<?= ADMIN_BASE_URL ?>api/retail-products/approve.php";
const API_REJECT  = "<?= ADMIN_BASE_URL ?>api/retail-products/reject.php";

let currentPage = 1;
let deleteModal, statusModal, approvalModal;

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

/* ================= LOAD PRODUCTS ================= */
function loadProducts(page = 1) {
    currentPage = page;

    const params = new URLSearchParams({
        page,
        search: document.getElementById('search').value,
        status: document.getElementById('status').value,
        approval_status: document.getElementById('approval_status').value
    });

    fetch(API_LIST + '?' + params.toString(), { credentials: 'include' })
    .then(r => r.json())
    .then(res => {

        if (res.status !== 'success') {
            alert(res.message);
            return;
        }

        const { products, pagination: p } = res.data;
        const tbody = document.getElementById('productRows');
        tbody.innerHTML = '';

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

        products.forEach((prod, i) => {

            const featured = prod.images?.find(img => img.is_featured == 1);
            const img = featured
                ? `<img src="<?= APP_ROOT ?>${featured.image_path}" width="45" class="rounded">`
                : '—';

            const prices = prod.variants?.map(v => parseFloat(v.selling_price)) || [];
            const priceRange = prices.length
                ? `₹${Math.min(...prices)} – ₹${Math.max(...prices)}`
                : '—';

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

            tbody.innerHTML += `
<tr>
<td>${(p.page - 1) * p.limit + i + 1}</td>
<td>${img}</td>
<td><strong>${prod.product_name}</strong></td>
<td>${prod.category_name}</td>
<td>${prod.primary_sleep_id ?? '-'}</td>
<td>${prod.secondary_sleep_id ?? '-'}</td>
<td>
${(prod.variants?.length ?? 0) > 0
    ? `<a href="<?= ADMIN_BASE_URL ?>retail-products/variants.php?product_id=${prod.id}"
         class="badge bg-info text-decoration-none"
         title="View Variants">
         ${prod.variants.length}
       </a>`
    : `<span class="badge bg-secondary">0</span>`
}
</td>

<td>${priceRange}</td>
<td>
<span class="badge bg-secondary cursor-pointer" onclick="openStatusModal(${prod.id}, '${prod.status}')">
${prod.status}
</span>
</td>
<td>
<span class="badge bg-${prod.approval_status === 'Approved' ? 'success' : 'warning'} cursor-pointer"
      onclick="openApprovalModal(${prod.id})">
${prod.approval_status}
</span>
</td>
<td class="d-flex gap-1">

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

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

<a href="<?= ADMIN_BASE_URL ?>retail-products/variants.php?product_id=${prod.id}"
   class="btn btn-sm btn-light-dark" title="Manage Variants">
<i class="bi bi-layers"></i>
</a>

<a href="<?= ADMIN_BASE_URL ?>retail-products/images.php?product_id=${prod.id}"
   class="btn btn-sm btn-light-success" title="Manage Images">
<i class="bi bi-images"></i>
</a>

<a href="<?= ADMIN_BASE_URL ?>retail-products/sections.php?product_id=${prod.id}"
   class="btn btn-sm btn-light-primary" title="Manage Sections">
<i class="bi bi-grid"></i>
</a>

${deleteBtn}

</td>

</tr>`;
        });

        const pages = Math.ceil(p.total / p.limit);
        const pag = document.getElementById('pagination');
        pag.innerHTML = '';

        for (let i = 1; i <= pages; i++) {
            pag.innerHTML += `
<li class="page-item ${i === p.page ? 'active' : ''}">
<a class="page-link" href="javascript:void(0)" onclick="loadProducts(${i})">${i}</a>
</li>`;
        }

        document.getElementById('paginationInfo').innerText =
            `Showing page ${p.page} of ${pages}`;
    });
}

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

function confirmDeleteProduct() {
    fetch(API_DELETE, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({ product_id: document.getElementById('delete_product_id').value })
    }).then(() => {
        deleteModal.hide();
        loadProducts(currentPage);
    });
}

function openStatusModal(id, status) {
    document.getElementById('status_product_id').value = id;
    document.getElementById('new_status').value = status;
    statusModal.show();
}

function updateStatus() {
    fetch(API_STATUS, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            product_id: document.getElementById('status_product_id').value,
            status: document.getElementById('new_status').value
        })
    }).then(r => r.json()).then(() => {
        statusModal.hide();
        loadProducts(currentPage);
    });
}

function openApprovalModal(id) {
    document.getElementById('approval_product_id').value = id;
    document.getElementById('rejectBox').classList.add('d-none');
    document.getElementById('rejection_reason').value = '';
    approvalModal.show();
}

function approveProduct() {
    fetch(API_APPROVE, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({ product_id: document.getElementById('approval_product_id').value })
    }).then(() => {
        approvalModal.hide();
        loadProducts(currentPage);
    });
}

function showReject() {
    document.getElementById('rejectBox').classList.remove('d-none');
}

function rejectProduct() {
    fetch(API_REJECT, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            product_id: document.getElementById('approval_product_id').value,
            rejection_reason: document.getElementById('rejection_reason').value
        })
    }).then(() => {
        approvalModal.hide();
        loadProducts(currentPage);
    });
}
</script>

</body>
</html>
