<?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';

/* ================= INPUT ================= */
if (empty($_GET['product_id'])) {
    die('Invalid product');
}
$productId = (int)$_GET['product_id'];

/* ================= ROLE ================= */
$db = Database::getInstance();
$stmt = $db->prepare("
    SELECT r.name
    FROM employees e
    JOIN roles r ON r.id = e.role_id
    WHERE e.id = :id
");
$stmt->execute(['id' => $_SESSION['employee_id']]);
$userRole = $stmt->fetchColumn();

$canManage = in_array($userRole, ['Super Admin','Admin','SEO Manager'], true);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Product Variants']); ?>
<?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'     => 'Product Variants'
]); ?>

<!-- ================= ACTION BAR ================= -->
<div class="card mb-4">
<div class="card-body d-flex justify-content-between align-items-center">

<div>
    <select id="statusFilter" class="form-select d-inline-block w-auto">
        <option value="">All</option>
        <option value="Active">Active</option>
        <option value="InActive">Inactive</option>
    </select>
    <button class="btn btn-primary ms-2" onclick="loadVariants()">Apply</button>
</div>

<a href="<?= ADMIN_BASE_URL ?>retail-products/variant-create.php?product_id=<?= $productId ?>"
   class="btn btn-success">
    <i class="bi bi-plus-lg me-1"></i> Add Variant
</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>Variant</th>
    <th>SKU</th>
    <th>Size</th>
    <th>Firmness</th>
    <th>Thickness</th>
    <th>MRP</th>
    <th>Selling</th>
    <th>Status</th>
    <th>Order</th>
    <th>Actions</th>
</tr>
</thead>

<tbody id="variantRows">
<tr>
    <td colspan="11" class="text-center text-muted">Loading variants…</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 Variant</h6>
</div>
<div class="modal-body text-center">
    <p>This action is irreversible.</p>
    <input type="hidden" id="delete_variant_id">
    <button class="btn btn-danger w-100" onclick="confirmDelete()">Delete</button>
</div>
</div>
</div>
</div>

<script>
const PRODUCT_ID = <?= $productId ?>;

const API_LIST   = "<?= ADMIN_BASE_URL ?>api/retail-products/variants/list.php";
const API_TOGGLE = "<?= ADMIN_BASE_URL ?>api/retail-products/variants/deactivate.php";
const API_DELETE = "<?= ADMIN_BASE_URL ?>api/retail-products/variants/delete.php";
const API_REORDER = "<?= ADMIN_BASE_URL ?>api/retail-products/variants/reorder.php";

let deleteModal;

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

/* ================= LOAD VARIANTS ================= */
function loadVariants() {

    const status = document.getElementById('statusFilter').value;
    const params = new URLSearchParams({
        product_id: PRODUCT_ID,
        status
    });

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

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

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

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

        res.data.variants.forEach((v, i) => {

            const statusBadge = `
<span class="badge cursor-pointer bg-${v.status === 'Active' ? 'success' : 'secondary'}"
      title="Click to ${v.status === 'Active' ? 'Deactivate' : 'Activate'}"
      onclick="toggleStatus(${v.id}, '${v.status}')">
    ${v.status}
</span>`;

            tbody.innerHTML += `
<tr>
<td>${i + 1}</td>
<td><strong>${v.variant_name}</strong></td>
<td>${v.sku ?? '-'}</td>
<td>${v.size}</td>
<td>${v.firmness}</td>
<td>${v.thickness}</td>
<td>₹${v.mrp}</td>
<td>₹${v.selling_price}</td>
<td>${statusBadge}</td>
<td class="text-center">
    <div class="btn-group btn-group-sm">
        <button class="btn btn-light"
                title="Move Up"
                onclick="reorderVariant(${v.id}, 'up')">
            <i class="bi bi-chevron-up"></i>
        </button>
        <button class="btn btn-light"
                title="Move Down"
                onclick="reorderVariant(${v.id}, 'down')">
            <i class="bi bi-chevron-down"></i>
        </button>
    </div>
</td>
<td class="d-flex gap-1">

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

<button class="btn btn-sm btn-light-danger"
        title="Delete Variant"
        onclick="openDelete(${v.id})">
<i class="bi bi-trash"></i>
</button>

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

/* ================= ACTIONS ================= */
function toggleStatus(variantId, currentStatus) {
    fetch(API_TOGGLE, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            variant_id: variantId,
            status: currentStatus === 'Active' ? 'InActive' : 'Active'
        })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status !== 'success') {
            alert(res.message);
            return;
        }
        loadVariants();
    });
}

function reorderVariant(id, direction) {
    fetch(API_REORDER, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            variant_id: id,
            direction: direction
        })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status !== 'success') {
            alert(res.message);
            return;
        }
        loadVariants();
    });
}

function openDelete(id) {
    document.getElementById('delete_variant_id').value = id;
    deleteModal.show();
}

function confirmDelete() {
    fetch(API_DELETE, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            variant_id: document.getElementById('delete_variant_id').value
        })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status !== 'success') {
            alert(res.message);
            return;
        }
        deleteModal.hide();
        loadVariants();
    });
}
</script>

</body>
</html>
