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

$db = Database::getInstance();

/* ================= FETCH PRODUCTS ================= */
$stmt = $db->prepare("
    SELECT id, product_name
    FROM retail_products
    WHERE status != 'InActive'
    ORDER BY product_name ASC
");
$stmt->execute();
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Create Variant']); ?>
<?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'     => 'Create Variant'
]); ?>

<div class="card">
<div class="card-body">

<form id="variantForm">

<!-- ================= PRODUCT ================= -->
<div class="mb-3">
    <label class="form-label">Select Mattress <span class="text-danger">*</span></label>
    <select name="product_id" id="product_id" class="form-select" required>
        <option value="">-- Select Mattress --</option>
        <?php foreach ($products as $p): ?>
            <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['product_name']) ?></option>
        <?php endforeach; ?>
    </select>
</div>

<!-- ================= VARIANT INFO ================= -->
<div class="row g-3">

<div class="col-md-6">
    <label class="form-label">Variant Name *</label>
    <input type="text" name="variant_name" class="form-control" required>
</div>

<div class="col-md-6">
    <label class="form-label">SKU</label>
    <input type="text" name="sku" class="form-control">
</div>

<div class="col-md-4">
    <label class="form-label">Size *</label>
    <select name="size" class="form-select" required>
        <option value="">Select</option>
        <option>Single</option>
        <option>Double</option>
        <option>Queen</option>
        <option>King</option>
        <option>Custom</option>
    </select>
</div>

<div class="col-md-4">
    <label class="form-label">Firmness *</label>
    <select name="firmness" class="form-select" required>
        <option value="">Select</option>
        <option>Soft</option>
        <option>Medium</option>
        <option>Firm</option>
        <option>Custom</option>
    </select>
</div>

<div class="col-md-4">
    <label class="form-label">Thickness *</label>
    <input type="text" name="thickness" class="form-control" required>
</div>

<div class="col-md-6">
    <label class="form-label">MRP (₹) *</label>
    <input type="number" step="0.01" name="mrp" class="form-control" required>
</div>

<div class="col-md-6">
    <label class="form-label">Selling Price (₹) *</label>
    <input type="number" step="0.01" name="selling_price" class="form-control" required>
</div>

</div>

<!-- ================= SPECIFICATIONS ================= -->
<div class="mt-4">
    <label class="form-label">Specifications (Optional)</label>
    <textarea name="specifications" class="form-control" rows="4"
              placeholder='JSON format e.g. {"material":"Foam","warranty":"10 Years"}'></textarea>
</div>

<!-- ================= ACTIONS ================= -->
<div class="mt-4 d-flex justify-content-end gap-2">
    <a href="<?= ADMIN_BASE_URL ?>retail-products/variants.php"
       class="btn btn-light">Cancel</a>
    <button type="submit" class="btn btn-success">Create Variant</button>
</div>

</form>

</div>
</div>

</div>
</main>

<?php include '../partials/footer.php'; ?>
</div>

<?php include '../partials/vendor-scripts.php'; ?>

<script>
const API_CREATE = "<?= ADMIN_BASE_URL ?>api/retail-products/variants/create.php";

document.getElementById('variantForm').addEventListener('submit', function (e) {
    e.preventDefault();

    const form = new FormData(this);

    let specs = null;
    if (form.get('specifications')) {
        try {
            specs = JSON.parse(form.get('specifications'));
        } catch {
            alert('Specifications must be valid JSON');
            return;
        }
    }

    fetch(API_CREATE, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            product_id: form.get('product_id'),
            variant_name: form.get('variant_name'),
            sku: form.get('sku'),
            size: form.get('size'),
            firmness: form.get('firmness'),
            thickness: form.get('thickness'),
            mrp: form.get('mrp'),
            selling_price: form.get('selling_price'),
            specifications: specs
        })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            alert(res.message);
            window.location.href =
                "<?= ADMIN_BASE_URL ?>retail-products/variants.php?product_id=" +
                form.get('product_id');
        } else {
            alert(res.message);
        }
    });
});
</script>

</body>
</html>
