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

if (empty($_GET['id'])) {
    die('Invalid variant');
}

$variantId = (int)$_GET['id'];
$db = Database::getInstance();

/* ================= FETCH VARIANT ================= */
$stmt = $db->prepare("
    SELECT
        v.*,
        p.product_name
    FROM retail_product_variants v
    JOIN retail_products p ON p.id = v.product_id
    WHERE v.id = :id
");
$stmt->execute(['id' => $variantId]);
$variant = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$variant) {
    die('Variant not found');
}

$specs = $variant['specifications']
    ? json_encode(json_decode($variant['specifications'], true), JSON_PRETTY_PRINT)
    : '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Edit 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'     => 'Edit Variant'
]); ?>

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

<form id="variantForm">

<input type="hidden" id="variant_id" value="<?= $variantId ?>">

<!-- ================= PRODUCT (READ ONLY) ================= -->
<div class="mb-3">
    <label class="form-label">Mattress</label>
    <input type="text" class="form-control" value="<?= htmlspecialchars($variant['product_name']) ?>" disabled>
</div>

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

<div class="col-md-6">
    <label class="form-label">Variant Name *</label>
    <input type="text" id="variant_name" class="form-control"
           value="<?= htmlspecialchars($variant['variant_name']) ?>" required>
</div>

<div class="col-md-6">
    <label class="form-label">SKU</label>
    <input type="text" id="sku" class="form-control"
           value="<?= htmlspecialchars($variant['sku'] ?? '') ?>">
</div>

<div class="col-md-4">
    <label class="form-label">Size *</label>
    <select id="size" class="form-select" required>
        <?php
        foreach (['Single','Double','Queen','King','Custom'] as $s) {
            $sel = $variant['size'] === $s ? 'selected' : '';
            echo "<option value=\"$s\" $sel>$s</option>";
        }
        ?>
    </select>
</div>

<div class="col-md-4">
    <label class="form-label">Firmness *</label>
    <select id="firmness" class="form-select" required>
        <?php
        foreach (['Soft','Medium','Firm','Custom'] as $f) {
            $sel = $variant['firmness'] === $f ? 'selected' : '';
            echo "<option value=\"$f\" $sel>$f</option>";
        }
        ?>
    </select>
</div>

<div class="col-md-4">
    <label class="form-label">Thickness *</label>
    <input type="text" id="thickness" class="form-control"
           value="<?= htmlspecialchars($variant['thickness']) ?>" required>
</div>

<div class="col-md-6">
    <label class="form-label">MRP (₹) *</label>
    <input type="number" step="0.01" id="mrp" class="form-control"
           value="<?= $variant['mrp'] ?>" required>
</div>

<div class="col-md-6">
    <label class="form-label">Selling Price (₹) *</label>
    <input type="number" step="0.01" id="selling_price" class="form-control"
           value="<?= $variant['selling_price'] ?>" required>
</div>

</div>

<!-- ================= SPECIFICATIONS ================= -->
<div class="mt-4">
    <label class="form-label">Specifications (JSON)</label>
    <textarea id="specifications" class="form-control" rows="4"
              placeholder='{"material":"Foam","warranty":"10 Years"}'><?= $specs ?></textarea>
</div>

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

</form>

</div>
</div>

</div>
</main>

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

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

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

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

    let specs = null;
    const specText = document.getElementById('specifications').value.trim();

    if (specText) {
        try {
            specs = JSON.parse(specText);
        } catch {
            alert('Specifications must be valid JSON');
            return;
        }
    }

    fetch(API_UPDATE, {
        method: 'POST',
        credentials: 'include',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({
            variant_id: document.getElementById('variant_id').value,
            variant_name: document.getElementById('variant_name').value,
            sku: document.getElementById('sku').value,
            size: document.getElementById('size').value,
            firmness: document.getElementById('firmness').value,
            thickness: document.getElementById('thickness').value,
            mrp: document.getElementById('mrp').value,
            selling_price: document.getElementById('selling_price').value,
            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=<?= $variant['product_id'] ?>";
        } else {
            alert(res.message);
        }
    });
});
</script>

</body>
</html>
