<?php
require_once __DIR__ . '/../functions.php';
requireAdmin();
ini_set('max_file_uploads', '50');
$page_title = 'Add / Edit Product';
$db = db();

$id = (int)($_GET['id'] ?? 0);
$product = null;
if ($id) {
    $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$id]);
    $product = $stmt->fetch();
    if (!$product) { header('Location: products.php'); exit; }
    $page_title = 'Edit Product: ' . $product['name'];
}

$categories = $db->query("SELECT * FROM categories WHERE parent_id IS NULL AND is_active = 1 ORDER BY sort_order")->fetchAll();
$subcategories = [];
$productImages = [];
if ($product) {
    $stmt = $db->prepare("SELECT * FROM categories WHERE parent_id = ? AND is_active = 1 ORDER BY sort_order");
    $stmt->execute([$product['category_id']]);
    $subcategories = $stmt->fetchAll();
    $stmt = $db->prepare("SELECT * FROM product_images WHERE product_id = ? ORDER BY is_primary DESC, sort_order");
    $stmt->execute([$product['id']]);
    $productImages = $stmt->fetchAll();
}

// Handle image delete
if (isset($_GET['delete_img'])) {
    $imgId = (int)$_GET['delete_img'];
    $stmt = $db->prepare("SELECT image_path FROM product_images WHERE id = ?");
    $stmt->execute([$imgId]);
    $img = $stmt->fetch();
    if ($img) {
        $file = __DIR__ . '/../' . $img['image_path'];
        if (file_exists($file)) unlink($file);
        $db->prepare("DELETE FROM product_images WHERE id = ?")->execute([$imgId]);
        flash('success', 'Image deleted.');
    }
    if (isset($_GET['delete_img'])) { header('Location: product-form.php?id=' . $id); exit; }
}

// Handle variant image delete
if (isset($_GET['delete_vimg'])) {
    $vimgId = (int)$_GET['delete_vimg'];
    $stmt = $db->prepare("SELECT image_path, variant_id FROM variant_images WHERE id = ?");
    $stmt->execute([$vimgId]);
    $vimg = $stmt->fetch();
    if ($vimg) {
        $file = __DIR__ . '/../' . $vimg['image_path'];
        if (file_exists($file)) unlink($file);
        $db->prepare("DELETE FROM variant_images WHERE id = ?")->execute([$vimgId]);
        flash('success', 'Variant image deleted.');
        header('Location: product-form.php?id=' . $id);
        exit;
    }
}

// Handle set primary
if (isset($_GET['set_primary'])) {
    $imgId = (int)$_GET['set_primary'];
    $db->prepare("UPDATE product_images SET is_primary = 0 WHERE product_id = ?")->execute([$id]);
    $db->prepare("UPDATE product_images SET is_primary = 1 WHERE id = ?")->execute([$imgId]);
    flash('success', 'Primary image updated.');
    header('Location: product-form.php?id=' . $id);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = [
        'name' => $_POST['name'],
        'slug' => $_POST['slug'] ?: slugify($_POST['name']),
        'description' => $_POST['description'],
        'short_description' => $_POST['short_description'],
        'price' => $_POST['price'],
        'compare_price' => $_POST['compare_price'] ?: null,
        'cost_price' => $_POST['cost_price'] ?: null,
        'sku' => $_POST['sku'],
        'stock_quantity' => (int)$_POST['stock_quantity'],
        'low_stock_threshold' => (int)($_POST['low_stock_threshold'] ?: 5),
        'weight' => $_POST['weight'] ?? null,
        'category_id' => $_POST['category_id'] ?: null,
        'deal_start' => $_POST['deal_start'] ?: null,
        'deal_end' => $_POST['deal_end'] ?: null,
        'is_featured' => isset($_POST['is_featured']) ? 1 : 0,
        'is_active' => isset($_POST['is_active']) ? 1 : 0,
        'meta_title' => $_POST['meta_title'],
        'meta_description' => $_POST['meta_description'],
    ];
    
    try {
        if ($id) {
            $sets = implode(', ', array_map(fn($k) => "$k = ?", array_keys($data)));
            $data['id'] = $id;
            $db->prepare("UPDATE products SET $sets WHERE id = ?")->execute(array_values($data));
            $productId = $id;
        } else {
            $cols = implode(', ', array_keys($data));
            $vals = implode(', ', array_fill(0, count($data), '?'));
            $db->prepare("INSERT INTO products ($cols) VALUES ($vals)")->execute(array_values($data));
            $productId = $db->lastInsertId();
        }
    } catch (PDOException $e) {
        if ($e->getCode() == 23000 && str_contains($e->getMessage(), 'sku')) {
            flash('error', 'SKU "' . h($data['sku']) . '" already exists. Use a different SKU.');
        } else {
            flash('error', 'Failed to save product: ' . $e->getMessage());
        }
        header('Location: product-form.php' . ($id ? '?id=' . $id : ''));
        exit;
    }
    
    // Handle image sort order
    if (!empty($_POST['image_sort'])) {
        foreach ($_POST['image_sort'] as $sort => $imgId) {
            $db->prepare("UPDATE product_images SET sort_order = ?, is_primary = ? WHERE id = ? AND product_id = ?")
                ->execute([$sort, $sort === 0 ? 1 : 0, $imgId, $productId]);
        }
    }
    // Handle new image uploads
    if (!empty($_FILES['images']['name'][0])) {
        $stmt = $db->prepare("SELECT MAX(sort_order) FROM product_images WHERE product_id = ?");
        $stmt->execute([$productId]);
        $maxSort = (int)$stmt->fetchColumn() + 1;
        $newIdx = 0;
        foreach ($_FILES['images']['tmp_name'] as $i => $tmp) {
            if ($_FILES['images']['error'][$i] === 0 && $tmp) {
                $ext = pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION);
                $filename = 'product_' . $productId . '_' . uniqid() . '.' . $ext;
                $dest = __DIR__ . '/../assets/uploads/products/' . $filename;
                move_uploaded_file($tmp, $dest);
                $path = 'assets/uploads/products/' . $filename;
                $db->prepare("INSERT INTO product_images (product_id, image_path, is_primary, sort_order) VALUES (?, ?, ?, ?)")
                    ->execute([$productId, $path, 0, $maxSort + $newIdx]);
                $newIdx++;
            }
        }
        // Re-sort: set first image as primary
        $db->prepare("UPDATE product_images SET is_primary = 0 WHERE product_id = ?")->execute([$productId]);
        $db->prepare("UPDATE product_images SET is_primary = 1 WHERE product_id = ? ORDER BY sort_order ASC LIMIT 1")->execute([$productId]);
    }
    
    // Handle variants
    $oldVariantIds = [];
    $existingStmt = $db->prepare("SELECT id FROM product_variants WHERE product_id = ?");
    $existingStmt->execute([$productId]);
    while ($r = $existingStmt->fetch()) { $oldVariantIds[] = $r['id']; }
    $submittedIds = [];
    if (!empty($_POST['variant_type']) && !empty($_POST['variant_value'])) {
        foreach ($_POST['variant_type'] as $i => $type) {
            if (!empty($type) && !empty($_POST['variant_value'][$i])) {
                $imagePath = $_POST['variant_image_current'][$i] ?? null;
                $vid = $_POST['variant_id'][$i] ?? null;
                if ($vid && in_array($vid, $oldVariantIds)) {
                    $db->prepare("UPDATE product_variants SET type=?, value=?, image_path=?, price_modifier=?, stock=? WHERE id=? AND product_id=?")
                        ->execute([$type, $_POST['variant_value'][$i], $imagePath, $_POST['variant_price'][$i] ?? 0, $_POST['variant_stock'][$i] ?? 0, $vid, $productId]);
                    $submittedIds[] = $vid;
                    $newVid = $vid;
                } else {
                    $db->prepare("INSERT INTO product_variants (product_id, type, value, image_path, price_modifier, stock, sku) VALUES (?, ?, ?, ?, ?, ?, ?)")
                        ->execute([$productId, $type, $_POST['variant_value'][$i], $imagePath, $_POST['variant_price'][$i] ?? 0, $_POST['variant_stock'][$i] ?? 0, $_POST['variant_sku'][$i] ?? '']);
                    $newVid = $db->lastInsertId();
                    $submittedIds[] = $newVid;
                }
                // Handle multiple images for this variant
                $fileKey = 'variant_image_' . $i;
                if (!empty($_FILES[$fileKey]['name'][0])) {
                    $firstImg = true;
                    foreach ($_FILES[$fileKey]['tmp_name'] as $j => $tmp) {
                        if ($_FILES[$fileKey]['error'][$j] === 0 && $tmp) {
                            $ext = pathinfo($_FILES[$fileKey]['name'][$j], PATHINFO_EXTENSION);
                            $filename = 'varimg_' . $newVid . '_' . uniqid() . '.' . $ext;
                            $dest = __DIR__ . '/../assets/uploads/variants/' . $filename;
                            move_uploaded_file($tmp, $dest);
                            $path = 'assets/uploads/variants/' . $filename;
                            $db->prepare("INSERT INTO variant_images (variant_id, image_path, is_primary, sort_order) VALUES (?, ?, ?, ?)")
                                ->execute([$newVid, $path, $firstImg ? 1 : 0, $j]);
                            if ($firstImg && !$imagePath) {
                                $db->prepare("UPDATE product_variants SET image_path = ? WHERE id = ?")->execute([$path, $newVid]);
                            }
                            $firstImg = false;
                        }
                    }
                }
            }
        }
    }
    // Delete variants that were removed
    $toDelete = array_diff($oldVariantIds, $submittedIds);
    if ($toDelete) {
        $placeholders = implode(',', array_fill(0, count($toDelete), '?'));
        // Delete their images first
        $delStmt = $db->prepare("SELECT image_path FROM product_variants WHERE id IN ($placeholders)");
        $delStmt->execute(array_values($toDelete));
        while ($r = $delStmt->fetch()) {
            if ($r['image_path'] && file_exists(__DIR__ . '/../' . $r['image_path'])) {
                unlink(__DIR__ . '/../' . $r['image_path']);
            }
        }
        // Delete variant_images for these variants
        $db->prepare("DELETE FROM variant_images WHERE variant_id IN ($placeholders)")->execute(array_values($toDelete));
        $db->prepare("DELETE FROM product_variants WHERE id IN ($placeholders)")->execute(array_values($toDelete));
    }
    
    flash('success', 'Product saved successfully!');
    header('Location: products.php');
    exit;
}

require_once __DIR__ . '/../includes/admin-header.php';
?>
<!-- Sticky top bar -->
<div class="sticky top-0 z-20 bg-white border-b border-gray-200 -m-6 p-4 mb-6 flex items-center justify-between shadow-sm">
    <div>
        <h1 class="text-lg font-bold text-gray-800"><?= $id ? 'Edit Product' : 'Add Product' ?></h1>
        <p class="text-xs text-gray-400"><?= $id ? 'Update product details' : 'Create a new product listing' ?></p>
    </div>
    <div class="flex items-center gap-3">
        <a href="products.php" class="text-sm text-gray-500 hover:text-gray-700 px-3 py-1.5">Cancel</a>
        <button type="submit" class="bg-primary-600 text-white px-6 py-2 rounded-lg text-sm font-semibold hover:bg-primary-700 flex items-center gap-2"><i class="fas fa-save"></i> Save Product</button>
    </div>
</div>

<form method="POST" enctype="multipart/form-data" class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <div class="lg:col-span-2 space-y-5">
        <!-- Vital Info -->
        <div class="bg-white rounded-lg border border-gray-200 overflow-hidden">
            <div class="px-5 py-3 bg-gray-50 border-b border-gray-200 flex items-center gap-2">
                <i class="fas fa-info-circle text-primary-500 text-sm"></i>
                <h3 class="font-semibold text-gray-700 text-sm">Vital Info</h3>
            </div>
            <div class="p-5 space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Product Name <span class="text-red-500">*</span></label>
                    <input type="text" name="name" value="<?= h($product['name'] ?? '') ?>" required placeholder="Enter product name" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition">
                    <p class="text-xs text-gray-400 mt-1">Include relevant keywords that customers might search for.</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Slug</label>
                    <input type="text" name="slug" value="<?= h($product['slug'] ?? '') ?>" placeholder="Leave empty to auto-generate" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Short Description</label>
                    <textarea name="short_description" rows="2" placeholder="Brief description for listing pages" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition"><?= h($product['short_description'] ?? '') ?></textarea>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Full Description</label>
                    <textarea name="description" rows="5" placeholder="Detailed product description..." class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition"><?= h($product['description'] ?? '') ?></textarea>
                </div>
            </div>
        </div>

        <!-- Images -->
        <div class="bg-white rounded-lg border border-gray-200 overflow-hidden">
            <div class="px-5 py-3 bg-gray-50 border-b border-gray-200 flex items-center gap-2">
                <i class="fas fa-images text-primary-500 text-sm"></i>
                <h3 class="font-semibold text-gray-700 text-sm">Images</h3>
                <span class="text-xs text-gray-400 ml-auto">Drag to reorder &middot; First = Main image</span>
            </div>
            <div class="p-5">
                <div class="flex flex-wrap gap-3" id="image-sortable">
                    <?php if ($productImages): ?>
                    <?php foreach ($productImages as $img): ?>
                    <div class="image-card relative w-[120px] h-[120px] bg-gray-50 rounded-lg overflow-hidden border-2 cursor-grab active:cursor-grabbing <?= $img['is_primary'] ? 'border-primary-500 ring-2 ring-primary-200' : 'border-gray-200 hover:border-gray-400' ?>" data-img-id="<?= $img['id'] ?>">
                        <img src="<?= BASE_PATH . '/' . h($img['image_path']) ?>" alt="" class="w-full h-full object-cover pointer-events-none">
                        <?php if ($img['is_primary']): ?>
                        <span class="absolute top-1 left-1 bg-primary-500 text-white text-[10px] px-1.5 py-0.5 rounded font-medium"><i class="fas fa-star mr-0.5"></i>Primary</span>
                        <?php endif; ?>
                        <div class="absolute inset-0 bg-black/0 hover:bg-black/30 transition flex items-center justify-center gap-2 opacity-0 hover:opacity-100">
                            <?php if (!$img['is_primary']): ?>
                            <a href="product-form.php?id=<?= $id ?>&set_primary=<?= $img['id'] ?>" class="w-8 h-8 bg-white/90 rounded-full flex items-center justify-center text-yellow-600 hover:bg-white shadow" title="Set as primary"><i class="fas fa-star text-sm"></i></a>
                            <?php endif; ?>
                            <a href="product-form.php?id=<?= $id ?>&delete_img=<?= $img['id'] ?>" class="w-8 h-8 bg-white/90 rounded-full flex items-center justify-center text-red-600 hover:bg-white shadow" title="Delete" onclick="return confirm('Delete this image?')"><i class="fas fa-trash text-sm"></i></a>
                        </div>
                        <div class="absolute top-1 right-1 text-gray-400 text-xs draggable-handle"><i class="fas fa-grip-vertical"></i></div>
                        <input type="hidden" name="image_sort[]" value="<?= $img['id'] ?>">
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                    <div class="image-add-card relative w-[120px] h-[120px] bg-gray-50 rounded-lg border-2 border-dashed border-gray-300 hover:border-primary-400 hover:bg-primary-50/30 transition cursor-pointer flex flex-col items-center justify-center gap-1.5" onclick="document.getElementById('file-input').click()">
                        <i class="fas fa-plus text-2xl text-gray-300"></i>
                        <span class="text-xs text-gray-400 font-medium">Add images</span>
                    </div>
                </div>
                <div id="drop-zone" class="mt-3 border-2 border-dashed border-gray-200 rounded-lg py-4 text-center hover:border-primary-300 hover:bg-primary-50/20 transition cursor-pointer" onclick="document.getElementById('file-input').click()" ondrop="handleFileDrop(event)" ondragover="event.preventDefault()">
                    <p class="text-xs text-gray-400"><i class="fas fa-cloud-upload-alt mr-1"></i> Drop images here or <span class="text-primary-600 font-medium">browse files</span></p>
                    <p class="text-[10px] text-gray-300 mt-0.5">JPG, PNG, WebP &middot; Max 10MB each</p>
                </div>
                <input type="file" id="file-input" name="images[]" multiple accept="image/*" class="hidden" onchange="previewFiles(this)">
                <div id="preview-container" class="flex flex-wrap gap-3 mt-3"></div>
                <div id="file-count" class="text-sm text-primary-600 font-medium mt-2 hidden"></div>
            </div>
        </div>

        <!-- Variants -->
        <div class="bg-white rounded-lg border border-gray-200 overflow-hidden">
            <div class="px-5 py-3 bg-gray-50 border-b border-gray-200 flex items-center gap-2">
                <i class="fas fa-layer-group text-primary-500 text-sm"></i>
                <h3 class="font-semibold text-gray-700 text-sm">Variants</h3>
                <span class="text-xs text-gray-400 ml-auto">Color, Size, etc.</span>
            </div>
            <div class="p-5">
                <div id="variants-container">
                    <?php if ($product): ?>
                    <?php $vstmt = $db->prepare("SELECT * FROM product_variants WHERE product_id = ?"); $vstmt->execute([$product['id']]); $existingVariants = $vstmt->fetchAll(); ?>
                    <?php if ($existingVariants): ?>
                    <div class="grid grid-cols-6 gap-2 mb-2 px-1">
                        <div class="text-[10px] text-gray-400 uppercase tracking-wider font-medium">Type</div>
                        <div class="text-[10px] text-gray-400 uppercase tracking-wider font-medium">Value</div>
                        <div class="text-[10px] text-gray-400 uppercase tracking-wider font-medium">Images</div>
                        <div class="text-[10px] text-gray-400 uppercase tracking-wider font-medium">Price</div>
                        <div class="text-[10px] text-gray-400 uppercase tracking-wider font-medium">Stock</div>
                        <div></div>
                    </div>
                    <?php endif; ?>
                    <?php foreach ($existingVariants as $vIdx => $v):
                        $vImgs = $db->prepare("SELECT * FROM variant_images WHERE variant_id = ? ORDER BY sort_order, is_primary DESC");
                        $vImgs->execute([$v['id']]);
                        $vImgs = $vImgs->fetchAll();
                    ?>
                    <div class="variant-row grid grid-cols-6 gap-2 mb-2 p-2.5 border border-gray-200 rounded-lg bg-gray-50/50 items-start hover:border-gray-300 transition">
                        <input type="hidden" name="variant_id[]" value="<?= $v['id'] ?>">
                        <div><input type="text" name="variant_type[]" value="<?= h($v['type']) ?>" placeholder="e.g. Color, Size" class="w-full border border-gray-300 rounded px-2 py-1.5 text-sm variant-type focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none" oninput="toggleColorPicker(this)"></div>
                        <div class="relative"><input type="text" name="variant_value[]" value="<?= h($v['value']) ?>" placeholder="Value" class="w-full border border-gray-300 rounded px-2 py-1.5 text-sm variant-value focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none"><input type="color" class="color-picker absolute right-1 bottom-1.5 w-6 h-6 p-0 border-0 cursor-pointer hidden" name="variant_color[]" value="<?= h($v['value']) ?>" title="Pick color" onchange="this.previousElementSibling.value=this.value"></div>
                        <div>
                            <div class="flex flex-wrap gap-1 mb-1 variant-gallery" data-variant-id="<?= $v['id'] ?>">
                                <?php if ($v['image_path']): ?>
                                <div class="relative w-8 h-8 rounded overflow-hidden border border-gray-200 group">
                                    <img src="<?= BASE_PATH . '/' . h($v['image_path']) ?>" class="w-full h-full object-cover">
                                    <a href="product-form.php?id=<?= $id ?>&delete_vimg=<?= $v['id'] ?>" class="absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition text-white text-xs" onclick="return confirm('Delete this image?')"><i class="fas fa-times"></i></a>
                                </div>
                                <?php endif; ?>
                                <?php foreach ($vImgs as $vi): ?>
                                <div class="relative w-8 h-8 rounded overflow-hidden border border-gray-200 group">
                                    <img src="<?= BASE_PATH . '/' . h($vi['image_path']) ?>" class="w-full h-full object-cover">
                                    <a href="product-form.php?id=<?= $id ?>&delete_vimg=<?= $vi['id'] ?>" class="absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition text-white text-xs" onclick="return confirm('Delete this image?')"><i class="fas fa-times"></i></a>
                                </div>
                                <?php endforeach; ?>
                                <label class="w-8 h-8 rounded border border-dashed border-gray-300 flex items-center justify-center cursor-pointer hover:border-primary-400 hover:text-primary-600 text-gray-400 text-xs" title="Add images">
                                    <i class="fas fa-plus"></i>
                                    <input type="file" name="variant_image_<?= $vIdx ?>[]" multiple accept="image/*" class="hidden" onchange="previewVariantImgs(this, <?= $vIdx ?>)">
                                </label>
                            </div>
                            <div class="variant-preview-<?= $vIdx ?> flex flex-wrap gap-1"></div>
                            <input type="hidden" name="variant_image_current[<?= $vIdx ?>]" value="<?= h($v['image_path'] ?? '') ?>">
                        </div>
                        <div><label class="text-[10px] text-gray-400 block mb-0.5">Price (₹)</label><input type="number" step="0.01" name="variant_price[]" value="<?= $v['price_modifier'] ?>" placeholder="e.g. 1299" class="w-full border border-gray-300 rounded px-2 py-1.5 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none"></div>
                        <div><label class="text-[10px] text-gray-400 block mb-0.5">Stock</label><input type="number" name="variant_stock[]" value="<?= $v['stock'] ?>" placeholder="0" class="w-full border border-gray-300 rounded px-2 py-1.5 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none"></div>
                        <div><button type="button" onclick="this.closest('.variant-row').remove()" class="text-red-400 hover:text-red-600 text-sm px-2 py-1.5"><i class="fas fa-trash-alt"></i></button></div>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <button type="button" onclick="addVariantRow()" class="mt-2 text-sm text-primary-600 hover:text-primary-700 flex items-center gap-1 font-medium"><i class="fas fa-plus-circle"></i> Add Color / Variant</button>
            </div>
        </div>

        <!-- SEO -->
        <div class="bg-white rounded-lg border border-gray-200 overflow-hidden">
            <div class="px-5 py-3 bg-gray-50 border-b border-gray-200 flex items-center gap-2">
                <i class="fas fa-search text-primary-500 text-sm"></i>
                <h3 class="font-semibold text-gray-700 text-sm">SEO</h3>
            </div>
            <div class="p-5 space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Meta Title</label>
                    <input type="text" name="meta_title" value="<?= h($product['meta_title'] ?? '') ?>" placeholder="<?= h($product['name'] ?? 'Product Title') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Meta Description</label>
                    <textarea name="meta_description" rows="2" placeholder="Brief description for search engines..." class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition"><?= h($product['meta_description'] ?? '') ?></textarea>
                </div>
            </div>
        </div>
    </div>

    <!-- Right Sidebar -->
    <div class="space-y-5">
        <!-- Organization -->
        <div class="bg-white rounded-lg border border-gray-200 overflow-hidden">
            <div class="px-5 py-3 bg-gray-50 border-b border-gray-200 flex items-center gap-2">
                <i class="fas fa-folder text-primary-500 text-sm"></i>
                <h3 class="font-semibold text-gray-700 text-sm">Organization</h3>
            </div>
            <div class="p-5 space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Category</label>
                    <select name="category_id" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none" onchange="loadSubcategories(this.value)">
                        <option value="">Select a category</option>
                        <?php foreach ($categories as $c): ?>
                        <option value="<?= $c['id'] ?>" <?= ($product['category_id'] ?? '') == $c['id'] ? 'selected' : '' ?>><?= h($c['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="flex flex-col gap-3 pt-1">
                    <label class="flex items-center gap-2.5 cursor-pointer">
                        <input type="checkbox" name="is_featured" <?= isset($product['is_featured']) && $product['is_featured'] ? 'checked' : '' ?> class="rounded border-gray-300 text-primary-600 focus:ring-primary-500">
                        <span class="text-sm text-gray-700">Featured Product</span>
                    </label>
                    <label class="flex items-center gap-2.5 cursor-pointer">
                        <input type="checkbox" name="is_active" <?= !isset($product['is_active']) || $product['is_active'] ? 'checked' : '' ?> class="rounded border-gray-300 text-primary-600 focus:ring-primary-500">
                        <span class="text-sm text-gray-700">Active (Visible on store)</span>
                    </label>
                </div>
            </div>
        </div>

        <!-- Limited Time Deal -->
        <div class="bg-white rounded-xl border border-gray-200 p-6">
            <h2 class="font-semibold text-gray-800 mb-4 flex items-center gap-2"><i class="fas fa-clock text-red-500"></i> Limited Time Deal</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Deal Start</label>
                    <input type="datetime-local" name="deal_start" value="<?= ($product['deal_start'] ?? null) ? date('Y-m-d\TH:i', strtotime($product['deal_start'])) : '' ?>" placeholder="dd-mm-yyyy --:--" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Deal End</label>
                    <input type="datetime-local" name="deal_end" value="<?= ($product['deal_end'] ?? null) ? date('Y-m-d\TH:i', strtotime($product['deal_end'])) : '' ?>" placeholder="dd-mm-yyyy --:--" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition">
                </div>
            </div>
            <p class="text-xs text-gray-400 mt-2">Set start and end time for a limited-time deal. Leave empty for no deal.</p>
        </div>

        <!-- Pricing -->
        <div class="bg-white rounded-lg border border-gray-200 overflow-hidden">
            <div class="px-5 py-3 bg-gray-50 border-b border-gray-200 flex items-center gap-2">
                <i class="fas fa-rupee-sign text-primary-500 text-sm"></i>
                <h3 class="font-semibold text-gray-700 text-sm">Pricing</h3>
            </div>
            <div class="p-5 space-y-3">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Price <span class="text-red-500">*</span></label>
                    <div class="relative">
                        <span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm">₹</span>
                        <input type="number" step="0.01" name="price" value="<?= h($product['price'] ?? '') ?>" required placeholder="0.00" class="w-full border border-gray-300 rounded-lg pl-7 pr-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition">
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Compare Price (MRP)</label>
                    <div class="relative">
                        <span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm">₹</span>
                        <input type="number" step="0.01" name="compare_price" value="<?= h($product['compare_price'] ?? '') ?>" placeholder="0.00" class="w-full border border-gray-300 rounded-lg pl-7 pr-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition">
                    </div>
                    <p class="text-xs text-gray-400 mt-1">Higher price shown as strikethrough to show discount</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Cost Price</label>
                    <div class="relative">
                        <span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm">₹</span>
                        <input type="number" step="0.01" name="cost_price" value="<?= h($product['cost_price'] ?? '') ?>" placeholder="0.00" class="w-full border border-gray-300 rounded-lg pl-7 pr-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition">
                    </div>
                    <p class="text-xs text-gray-400 mt-1">Your cost (for profit calculation)</p>
                </div>
            </div>
        </div>

        <!-- Inventory -->
        <div class="bg-white rounded-lg border border-gray-200 overflow-hidden">
            <div class="px-5 py-3 bg-gray-50 border-b border-gray-200 flex items-center gap-2">
                <i class="fas fa-boxes text-primary-500 text-sm"></i>
                <h3 class="font-semibold text-gray-700 text-sm">Inventory</h3>
            </div>
            <div class="p-5 space-y-3">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">SKU</label>
                    <input type="text" name="sku" value="<?= h($product['sku'] ?? '') ?>" placeholder="e.g. PROD-001" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition">
                    <p class="text-xs text-gray-400 mt-1">Unique product code for tracking</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Stock Quantity</label>
                    <input type="number" name="stock_quantity" value="<?= h($product['stock_quantity'] ?? '0') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Low Stock Alert</label>
                    <input type="number" name="low_stock_threshold" value="<?= h($product['low_stock_threshold'] ?? '5') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition">
                    <p class="text-xs text-gray-400 mt-1">Notify when stock falls below this</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Weight (kg)</label>
                    <input type="number" step="0.01" name="weight" value="<?= h($product['weight'] ?? '') ?>" placeholder="0.5" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none transition">
                </div>
            </div>
        </div>

        <!-- Bottom Save -->
        <button type="submit" class="w-full bg-primary-600 text-white px-6 py-3 rounded-lg text-sm font-semibold hover:bg-primary-700 flex items-center justify-center gap-2 transition"><i class="fas fa-save"></i> Save Product</button>
        <a href="products.php" class="block text-center text-sm text-gray-500 hover:text-gray-700 py-2">Cancel</a>
    </div>
</form>
<script>
// --- Sortable image reorder ---
const sortableEl = document.getElementById('image-sortable');
if (sortableEl) {
    new Sortable(sortableEl, {
        animation: 200,
        handle: '.image-card',
        ghostClass: 'opacity-50',
        dragClass: 'shadow-lg',
        onEnd: function() {
            // First image gets primary border style
            sortableEl.querySelectorAll('.image-card').forEach((card, i) => {
                const border = i === 0 ? 'border-primary-500 ring-2 ring-primary-200' : 'border-gray-200 hover:border-gray-400';
                card.className = card.className.replace(/border-\w+(-\d+)?(\sring-2\sring-\w+-\d+)?/g, '').trim() + ' ' + border;
            });
        }
    });
}

// --- Variant functions ---
let varRowIdx = <?= $existingVariants ? count($existingVariants) : 0 ?>;

function addVariantRow() {
    const idx = varRowIdx++;
    const c = document.getElementById('variants-container');
    const row = document.createElement('div');
    row.className = 'variant-row grid grid-cols-6 gap-2 mb-2 p-2.5 border border-gray-200 rounded-lg bg-gray-50/50 items-start hover:border-gray-300 transition';
    row.innerHTML = '<input type="hidden" name="variant_id[]" value="">'
        + '<div><input type="text" name="variant_type[]" placeholder="e.g. Color, Size" class="w-full border border-gray-300 rounded px-2 py-1.5 text-sm variant-type focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none" oninput="toggleColorPicker(this)"></div>'
        + '<div class="relative"><input type="text" name="variant_value[]" placeholder="Value" class="w-full border border-gray-300 rounded px-2 py-1.5 text-sm variant-value focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none">'
        + '<input type="color" class="color-picker absolute right-1 bottom-1.5 w-6 h-6 p-0 border-0 cursor-pointer hidden" name="variant_color[]" value="#ff0000" title="Pick color" onchange="this.previousElementSibling.value=this.value"></div>'
        + '<div>'
        + '<div class="flex flex-wrap gap-1 mb-1"><label class="w-8 h-8 rounded border border-dashed border-gray-300 flex items-center justify-center cursor-pointer hover:border-primary-400 hover:text-primary-600 text-gray-400 text-xs" title="Add images"><i class="fas fa-plus"></i><input type="file" name="variant_image_' + idx + '[]" multiple accept="image/*" class="hidden" onchange="previewVariantImgs(this, ' + idx + ')"></label></div>'
        + '<div class="variant-preview-' + idx + ' flex flex-wrap gap-1"></div>'
        + '<input type="hidden" name="variant_image_current[' + idx + ']" value=""></div>'
        + '<div><label class="text-[10px] text-gray-400 block mb-0.5">Price (₹)</label><input type="number" step="0.01" name="variant_price[]" placeholder="e.g. 1299" class="w-full border border-gray-300 rounded px-2 py-1.5 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none"></div>'
        + '<div><label class="text-[10px] text-gray-400 block mb-0.5">Stock</label><input type="number" name="variant_stock[]" placeholder="0" class="w-full border border-gray-300 rounded px-2 py-1.5 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 outline-none"></div>'
        + '<div><button type="button" onclick="this.closest(\'.variant-row\').remove()" class="text-red-400 hover:text-red-600 text-sm px-2 py-1.5"><i class="fas fa-trash-alt"></i></button></div>';
    c.appendChild(row);
    toggleColorPicker(row.querySelector('.variant-type'));
}

function toggleColorPicker(typeInput) {
    const row = typeInput.closest('.variant-row');
    const picker = row.querySelector('.color-picker');
    if (typeInput.value.toLowerCase() === 'color') {
        picker.classList.remove('hidden');
    } else {
        picker.classList.add('hidden');
    }
}

function previewVariantImgs(input, idx) {
    var container = document.querySelector('.variant-preview-' + idx);
    if (!container) return;
    container.innerHTML = '';
    var files = [...input.files].filter(function(f) { return f.type.startsWith('image/'); });
    files.forEach(function(f) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var div = document.createElement('div');
            div.className = 'relative w-8 h-8 rounded overflow-hidden border border-primary-300';
            div.innerHTML = '<img src="' + e.target.result + '" class="w-full h-full object-cover">';
            container.appendChild(div);
        };
        reader.readAsDataURL(f);
    });
    var row = input.closest('.variant-row');
    var countEl = row.querySelector('.var-file-count');
    if (!countEl) {
        countEl = document.createElement('div');
        countEl.className = 'var-file-count text-[10px] text-primary-600 font-medium mt-1';
        container.after(countEl);
    }
    countEl.textContent = files.length + ' file(s) selected';
}

// --- Image upload ---
const fileInput = document.getElementById('file-input');

function handleFileDrop(e) {
    e.preventDefault();
    document.getElementById('drop-zone').classList.remove('border-primary-500', 'bg-primary-50');
    const dt = new DataTransfer();
    [...e.dataTransfer.files].forEach(f => { if (f.type.startsWith('image/')) dt.items.add(f); });
    // Append to existing files instead of replacing
    const existing = fileInput.files;
    if (existing) {
        for (let i = 0; i < existing.length; i++) {
            dt.items.add(existing[i]);
        }
    }
    fileInput.files = dt.files;
    previewFiles(fileInput);
}

document.getElementById('drop-zone').addEventListener('dragover', e => { e.preventDefault(); e.stopPropagation(); e.currentTarget.classList.add('border-primary-500', 'bg-primary-50'); });
document.getElementById('drop-zone').addEventListener('dragleave', e => { e.preventDefault(); e.stopPropagation(); e.currentTarget.classList.remove('border-primary-500', 'bg-primary-50'); });
document.getElementById('drop-zone').addEventListener('drop', handleFileDrop);

function previewFiles(input) {
    const container = document.getElementById('preview-container');
    const counter = document.getElementById('file-count');
    container.innerHTML = '';
    const files = [...input.files].filter(f => f.type.startsWith('image/'));
    if (files.length > 0) {
        counter.classList.remove('hidden');
        counter.innerHTML = '<i class="fas fa-images mr-1"></i>' + files.length + ' new image(s) selected &middot; Click Save to upload';
    } else {
        counter.classList.add('hidden');
    }
    files.forEach(f => {
        const reader = new FileReader();
        reader.onload = e => {
            const div = document.createElement('div');
            div.className = 'relative w-[120px] h-[120px] rounded-lg overflow-hidden border-2 border-primary-300 shadow-sm';
            div.innerHTML = '<img src="' + e.target.result + '" class="w-full h-full object-cover"><span class="absolute bottom-0 inset-x-0 bg-black/60 text-white text-[10px] text-center py-1">' + (f.size/1024).toFixed(0) + 'KB</span><span class="absolute top-1 left-1 bg-primary-500 text-white text-[10px] px-1.5 py-0.5 rounded font-medium"><i class="fas fa-plus-circle mr-0.5"></i>New</span>';
            container.appendChild(div);
        };
        reader.readAsDataURL(f);
    });
}
</script>
<?php require_once __DIR__ . '/../includes/admin-footer.php'; ?>
