<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';
require_once __DIR__ . '/../app/helpers/activity.php';

require_admin();

$pageTitle = 'Products';
$success = '';
$error = '';
$editProduct = null;

if (isset($_GET['edit'])) {
    $editId = (int) $_GET['edit'];

    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ? LIMIT 1");
    $stmt->execute([$editId]);
    $editProduct = $stmt->fetch();

    if (!$editProduct) {
        $error = 'Product not found.';
    }
}

if (isset($_GET['delete'])) {
    $deleteId = (int) $_GET['delete'];

    $stmt = $pdo->prepare("SELECT product_name FROM products WHERE id = ? LIMIT 1");
    $stmt->execute([$deleteId]);
    $deletedProduct = $stmt->fetch();

    $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
    $stmt->execute([$deleteId]);

    log_admin_activity(
        'product_deleted',
        'Product deleted: ' . ($deletedProduct['product_name'] ?? 'Product ID ' . $deleteId)
    );

    redirect(ADMIN_URL . '/products.php?deleted=1');
}

if (isset($_GET['deleted'])) {
    $success = 'Product deleted successfully.';
}

if (isset($_GET['delete_variation'])) {
    $variationId = (int) $_GET['delete_variation'];
    $productId = (int) ($_GET['product_id'] ?? 0);

    $stmt = $pdo->prepare("SELECT * FROM product_variations WHERE id = ? LIMIT 1");
    $stmt->execute([$variationId]);
    $variation = $stmt->fetch();

    if ($variation) {
        if (!empty($variation['image_path'])) {
            $imageFile = __DIR__ . '/../' . $variation['image_path'];

            if (file_exists($imageFile)) {
                unlink($imageFile);
            }
        }

        $stmt = $pdo->prepare("DELETE FROM product_variations WHERE id = ?");
        $stmt->execute([$variationId]);

        log_admin_activity(
            'product_variation_deleted',
            'Variation deleted: ' . $variation['variation_name'] . ' - ' . $variation['variation_value'] . ' | Product ID: ' . $variation['product_id']
        );
    }

    redirect(ADMIN_URL . '/products.php?edit=' . $productId . '&variation_deleted=1');
}

if (isset($_GET['created'])) {
    $success = 'Product created successfully.';
}

if (isset($_GET['updated'])) {
    $success = 'Product updated successfully.';
}

if (isset($_GET['variation_created'])) {
    $success = 'Variation created successfully.';
}

if (isset($_GET['variation_updated'])) {
    $success = 'Variation updated successfully.';
}

if (isset($_GET['variation_deleted'])) {
    $success = 'Variation deleted successfully.';
}

if (is_post() && ($_POST['form_type'] ?? '') === 'variation') {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $variationId = (int) ($_POST['variation_id'] ?? 0);
        $productId = (int) ($_POST['product_id'] ?? 0);

        $variationName = trim($_POST['variation_name'] ?? 'Color');
        $variationValue = trim($_POST['variation_value'] ?? '');
        $colorCode = trim($_POST['color_code'] ?? '');
        $variationSku = trim($_POST['variation_sku'] ?? '');
        $priceAdjustment = (float) ($_POST['price_adjustment'] ?? 0);
        $variationStock = (int) ($_POST['variation_stock_quantity'] ?? 0);
        $variationStatus = $_POST['variation_status'] ?? 'active';

        if ($productId <= 0) {
            $error = 'Invalid product for variation.';
        } elseif ($variationValue === '') {
            $error = 'Variation value is required. Example: Rose Gold.';
        } else {
            try {
                $imagePath = null;

                if ($variationId > 0) {
                    $stmt = $pdo->prepare("SELECT image_path FROM product_variations WHERE id = ? AND product_id = ? LIMIT 1");
                    $stmt->execute([$variationId, $productId]);
                    $existingVariation = $stmt->fetch();

                    $imagePath = $existingVariation['image_path'] ?? null;
                }

                if (!empty($_FILES['variation_image']['name'])) {
                    $uploadDir = __DIR__ . '/../uploads/products/';

                    if (!is_dir($uploadDir)) {
                        mkdir($uploadDir, 0777, true);
                    }

                    $tmpName = $_FILES['variation_image']['tmp_name'];
                    $mimeType = mime_content_type($tmpName);
                    $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];

                    if (in_array($mimeType, $allowedTypes, true)) {
                        $extension = strtolower(pathinfo($_FILES['variation_image']['name'], PATHINFO_EXTENSION));
                        $fileName = 'variation-' . $productId . '-' . time() . '-' . bin2hex(random_bytes(4)) . '.' . $extension;
                        $targetPath = $uploadDir . $fileName;

                        if (move_uploaded_file($tmpName, $targetPath)) {
                            $imagePath = 'uploads/products/' . $fileName;
                        }
                    }
                }

                if ($variationId > 0) {
                    $stmt = $pdo->prepare("
                        UPDATE product_variations
                        SET variation_name = ?,
                            variation_value = ?,
                            color_code = ?,
                            image_path = ?,
                            sku = ?,
                            price_adjustment = ?,
                            stock_quantity = ?,
                            status = ?
                        WHERE id = ?
                          AND product_id = ?
                    ");

                    $stmt->execute([
                        $variationName,
                        $variationValue,
                        $colorCode !== '' ? $colorCode : null,
                        $imagePath,
                        $variationSku !== '' ? $variationSku : null,
                        $priceAdjustment,
                        $variationStock,
                        $variationStatus,
                        $variationId,
                        $productId
                    ]);

                    log_admin_activity(
                        'product_variation_updated',
                        'Variation updated: ' . $variationName . ' - ' . $variationValue . ' | Product ID: ' . $productId
                    );

                    redirect(ADMIN_URL . '/products.php?edit=' . $productId . '&variation_updated=1');
                } else {
                    $stmt = $pdo->prepare("
                        INSERT INTO product_variations (
                            product_id,
                            variation_name,
                            variation_value,
                            color_code,
                            image_path,
                            sku,
                            price_adjustment,
                            stock_quantity,
                            status
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");

                    $stmt->execute([
                        $productId,
                        $variationName,
                        $variationValue,
                        $colorCode !== '' ? $colorCode : null,
                        $imagePath,
                        $variationSku !== '' ? $variationSku : null,
                        $priceAdjustment,
                        $variationStock,
                        $variationStatus
                    ]);

                    log_admin_activity(
                        'product_variation_created',
                        'Variation created: ' . $variationName . ' - ' . $variationValue . ' | Product ID: ' . $productId
                    );

                    redirect(ADMIN_URL . '/products.php?edit=' . $productId . '&variation_created=1');
                }
            } catch (Exception $e) {
                $error = 'Variation could not be saved: ' . $e->getMessage();
            }
        }
    }
}

if (is_post() && ($_POST['form_type'] ?? 'product') === 'product') {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $productId = (int) ($_POST['product_id'] ?? 0);
        $categoryId = !empty($_POST['category_id']) ? (int) $_POST['category_id'] : null;

        $productName = trim($_POST['product_name'] ?? '');
        $slug = trim($_POST['slug'] ?? '');
        $shortDescription = trim($_POST['short_description'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $sku = trim($_POST['sku'] ?? '');
        $regularPrice = (float) ($_POST['regular_price'] ?? 0);
        $salePrice = $_POST['sale_price'] !== '' ? (float) $_POST['sale_price'] : null;
        $currencyCode = trim($_POST['currency_code'] ?? 'GBP');
        $stockQuantity = (int) ($_POST['stock_quantity'] ?? 0);
        $stockStatus = $_POST['stock_status'] ?? 'in_stock';
        $badge = trim($_POST['badge'] ?? '');
        $isFeatured = isset($_POST['is_featured']) ? 1 : 0;
        $isBestSeller = isset($_POST['is_best_seller']) ? 1 : 0;
        $isNewArrival = isset($_POST['is_new_arrival']) ? 1 : 0;
        $weight = $_POST['weight'] !== '' ? (float) $_POST['weight'] : null;
        $scentFamily = trim($_POST['scent_family'] ?? '');
        $ingredients = trim($_POST['ingredients'] ?? '');
        $howToUse = trim($_POST['how_to_use'] ?? '');
        $shippingReturnInfo = trim($_POST['shipping_return_info'] ?? '');
        $seoTitle = trim($_POST['seo_title'] ?? '');
        $seoDescription = trim($_POST['seo_description'] ?? '');
        $status = $_POST['status'] ?? 'active';

        if ($productName === '') {
            $error = 'Product name is required.';
        } elseif ($regularPrice <= 0) {
            $error = 'Regular price must be greater than zero.';
        } else {
            if ($slug === '') {
                $slug = generate_slug($productName);
            } else {
                $slug = generate_slug($slug);
            }

            if ($productId > 0) {
                $check = $pdo->prepare("SELECT id FROM products WHERE slug = ? AND id != ? LIMIT 1");
                $check->execute([$slug, $productId]);
            } else {
                $check = $pdo->prepare("SELECT id FROM products WHERE slug = ? LIMIT 1");
                $check->execute([$slug]);
            }

            if ($check->fetch()) {
                $error = 'This product slug already exists. Please use another slug.';
            } else {
                if ($productId > 0) {
                    $stmt = $pdo->prepare("
                        UPDATE products
                        SET category_id = ?, product_name = ?, slug = ?, short_description = ?, description = ?,
                            sku = ?, regular_price = ?, sale_price = ?, currency_code = ?, stock_quantity = ?,
                            stock_status = ?, badge = ?, is_featured = ?, is_best_seller = ?, is_new_arrival = ?,
                            weight = ?, scent_family = ?, ingredients = ?, how_to_use = ?, shipping_return_info = ?,
                            seo_title = ?, seo_description = ?, status = ?
                        WHERE id = ?
                    ");

                    $stmt->execute([
                        $categoryId,
                        $productName,
                        $slug,
                        $shortDescription,
                        $description,
                        $sku !== '' ? $sku : null,
                        $regularPrice,
                        $salePrice,
                        $currencyCode,
                        $stockQuantity,
                        $stockStatus,
                        $badge !== '' ? $badge : null,
                        $isFeatured,
                        $isBestSeller,
                        $isNewArrival,
                        $weight,
                        $scentFamily,
                        $ingredients,
                        $howToUse,
                        $shippingReturnInfo,
                        $seoTitle,
                        $seoDescription,
                        $status,
                        $productId
                    ]);

                    $savedProductId = $productId;
                } else {
                    $stmt = $pdo->prepare("
                        INSERT INTO products
                        (
                            category_id, product_name, slug, short_description, description,
                            sku, regular_price, sale_price, currency_code, stock_quantity,
                            stock_status, badge, is_featured, is_best_seller, is_new_arrival,
                            weight, scent_family, ingredients, how_to_use, shipping_return_info,
                            seo_title, seo_description, status
                        )
                        VALUES
                        (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");

                    $stmt->execute([
                        $categoryId,
                        $productName,
                        $slug,
                        $shortDescription,
                        $description,
                        $sku !== '' ? $sku : null,
                        $regularPrice,
                        $salePrice,
                        $currencyCode,
                        $stockQuantity,
                        $stockStatus,
                        $badge !== '' ? $badge : null,
                        $isFeatured,
                        $isBestSeller,
                        $isNewArrival,
                        $weight,
                        $scentFamily,
                        $ingredients,
                        $howToUse,
                        $shippingReturnInfo,
                        $seoTitle,
                        $seoDescription,
                        $status
                    ]);

                    $savedProductId = (int) $pdo->lastInsertId();
                }

                if (!empty($_FILES['product_images']['name'][0])) {
                    $uploadDir = __DIR__ . '/../uploads/products/';

                    if (!is_dir($uploadDir)) {
                        mkdir($uploadDir, 0777, true);
                    }

                    $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
                    $imageCount = count($_FILES['product_images']['name']);

                    for ($i = 0; $i < $imageCount; $i++) {
                        if ($_FILES['product_images']['error'][$i] !== UPLOAD_ERR_OK) {
                            continue;
                        }

                        $tmpName = $_FILES['product_images']['tmp_name'][$i];
                        $mimeType = mime_content_type($tmpName);

                        if (!in_array($mimeType, $allowedTypes, true)) {
                            continue;
                        }

                        $originalName = $_FILES['product_images']['name'][$i];
                        $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
                        $fileName = 'product-' . $savedProductId . '-' . time() . '-' . bin2hex(random_bytes(4)) . '.' . $extension;
                        $targetPath = $uploadDir . $fileName;

                        if (move_uploaded_file($tmpName, $targetPath)) {
                            $imagePath = 'uploads/products/' . $fileName;

                            $stmtImg = $pdo->prepare("
                                INSERT INTO product_images (product_id, image_path, alt_text, sort_order, is_primary)
                                VALUES (?, ?, ?, ?, ?)
                            ");

                            $isPrimary = 0;

                            $existingImg = $pdo->prepare("SELECT COUNT(*) FROM product_images WHERE product_id = ?");
                            $existingImg->execute([$savedProductId]);

                            if ((int) $existingImg->fetchColumn() === 0) {
                                $isPrimary = 1;
                            }

                            $stmtImg->execute([
                                $savedProductId,
                                $imagePath,
                                $productName,
                                $i,
                                $isPrimary
                            ]);
                        }
                    }
                }

                if ($productId > 0) {
                    log_admin_activity(
                        'product_updated',
                        'Product updated: ' . $productName . ' | Product ID: ' . $productId
                    );

                    redirect(ADMIN_URL . '/products.php?updated=1');
                }

                log_admin_activity(
                    'product_created',
                    'Product created: ' . $productName . ' | Product ID: ' . $savedProductId
                );

                redirect(ADMIN_URL . '/products.php?created=1');
            }
        }
    }
}

$categories = $pdo->query("
    SELECT id, name
    FROM categories
    WHERE status = 'active'
    ORDER BY name ASC
")->fetchAll();

$currencies = $pdo->query("
    SELECT currency_code, symbol
    FROM currencies
    WHERE status = 'active'
    ORDER BY is_default DESC, currency_code ASC
")->fetchAll();

$products = $pdo->query("
    SELECT p.*, c.name AS category_name,
        (
            SELECT image_path
            FROM product_images
            WHERE product_id = p.id
            ORDER BY is_primary DESC, sort_order ASC, id ASC
            LIMIT 1
        ) AS primary_image,
        (
            SELECT COUNT(*)
            FROM product_variations pv
            WHERE pv.product_id = p.id
        ) AS variation_count,
        (
            SELECT COALESCE(SUM(pv.stock_quantity), 0)
            FROM product_variations pv
            WHERE pv.product_id = p.id
              AND pv.status = 'active'
        ) AS variation_total_stock,
        (
            SELECT COUNT(*)
            FROM product_variations pv
            WHERE pv.product_id = p.id
              AND pv.status = 'active'
              AND pv.stock_quantity > 0
        ) AS active_variation_count
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    ORDER BY p.id DESC
")->fetchAll();

$productImages = [];
$productVariations = [];
$editVariation = null;

if ($editProduct) {
    $stmt = $pdo->prepare("SELECT * FROM product_images WHERE product_id = ? ORDER BY is_primary DESC, sort_order ASC");
    $stmt->execute([$editProduct['id']]);
    $productImages = $stmt->fetchAll();

    $stmt = $pdo->prepare("SELECT * FROM product_variations WHERE product_id = ? ORDER BY id ASC");
    $stmt->execute([$editProduct['id']]);
    $productVariations = $stmt->fetchAll();

    if (isset($_GET['edit_variation'])) {
        $editVariationId = (int) $_GET['edit_variation'];

        $stmt = $pdo->prepare("
            SELECT *
            FROM product_variations
            WHERE id = ?
              AND product_id = ?
            LIMIT 1
        ");
        $stmt->execute([$editVariationId, $editProduct['id']]);
        $editVariation = $stmt->fetch();
    }
}

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>Products</h1>
            <div class="admin-user">Create and manage LOVE-U Essentials products.</div>
        </div>

        <?php if ($editProduct): ?>
            <a href="<?= e(ADMIN_URL); ?>/products.php" class="admin-btn admin-btn-light">Cancel Edit</a>
        <?php endif; ?>
    </div>

    <?php if ($success): ?>
        <div class="admin-alert admin-alert-success"><?= e($success); ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="admin-alert admin-alert-error"><?= e($error); ?></div>
    <?php endif; ?>

    <section class="admin-panel admin-product-editor-panel">
        <div class="admin-panel-head">
            <div>
                <h2><?= $editProduct ? 'Edit Product' : 'Add New Product'; ?></h2>
                <p><?= $editProduct ? 'Update product details, pricing, stock, SEO, and product media.' : 'Create a new LOVE-U Essentials product with images, stock, and SEO details.'; ?></p>
            </div>

            <?php if ($editProduct): ?>
                <span class="admin-status-pill status-<?= e($editProduct['status']); ?>">
                    <?= e(ucfirst($editProduct['status'])); ?>
                </span>
            <?php endif; ?>
        </div>

        <form method="POST" enctype="multipart/form-data">
            <?= csrf_field(); ?>

            <input type="hidden" name="product_id" value="<?= e($editProduct['id'] ?? 0); ?>">
            <input type="hidden" name="form_type" value="product">

            <div class="admin-form-grid">
                <div class="admin-field">
                    <label>Product Name *</label>
                    <input type="text" name="product_name" value="<?= e($editProduct['product_name'] ?? ''); ?>" required>
                </div>

                <div class="admin-field">
                    <label>Slug</label>
                    <input type="text" name="slug" value="<?= e($editProduct['slug'] ?? ''); ?>" placeholder="auto-generated if empty">
                </div>

                <div class="admin-field">
                    <label>Category</label>
                    <select name="category_id">
                        <option value="">No Category</option>
                        <?php foreach ($categories as $category): ?>
                            <option value="<?= e($category['id']); ?>" <?= isset($editProduct['category_id']) && (int)$editProduct['category_id'] === (int)$category['id'] ? 'selected' : ''; ?>>
                                <?= e($category['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="admin-field">
                    <label>SKU</label>
                    <input type="text" name="sku" value="<?= e($editProduct['sku'] ?? ''); ?>">
                </div>

                <div class="admin-field">
                    <label>Regular Price *</label>
                    <input type="number" step="0.01" name="regular_price" value="<?= e($editProduct['regular_price'] ?? ''); ?>" required>
                </div>

                <div class="admin-field">
                    <label>Sale Price</label>
                    <input type="number" step="0.01" name="sale_price" value="<?= e($editProduct['sale_price'] ?? ''); ?>">
                </div>

                <div class="admin-field">
                    <label>Currency</label>
                    <select name="currency_code">
                        <?php foreach ($currencies as $currency): ?>
                            <option value="<?= e($currency['currency_code']); ?>" <?= ($editProduct['currency_code'] ?? 'GBP') === $currency['currency_code'] ? 'selected' : ''; ?>>
                                <?= e($currency['currency_code']); ?> <?= e($currency['symbol']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="admin-field">
                    <label>Stock Quantity</label>
                    <input type="number" name="stock_quantity" value="<?= e($editProduct['stock_quantity'] ?? 0); ?>">
                </div>

                <div class="admin-field">
                    <label>Stock Status</label>
                    <select name="stock_status">
                        <?php
                        $stockOptions = [
                            'in_stock' => 'In Stock',
                            'only_few_left' => 'Only Few Left',
                            'out_of_stock' => 'Out of Stock',
                            'back_in_stock' => 'Back In Stock'
                        ];
                        ?>
                        <?php foreach ($stockOptions as $value => $label): ?>
                            <option value="<?= e($value); ?>" <?= ($editProduct['stock_status'] ?? 'in_stock') === $value ? 'selected' : ''; ?>>
                                <?= e($label); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="admin-field">
                    <label>Badge</label>
                    <input type="text" name="badge" value="<?= e($editProduct['badge'] ?? ''); ?>" placeholder="Best Seller, New, Limited">
                </div>

                <div class="admin-field">
                    <label>Status</label>
                    <select name="status">
                        <option value="active" <?= ($editProduct['status'] ?? '') === 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?= ($editProduct['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        <option value="draft" <?= ($editProduct['status'] ?? '') === 'draft' ? 'selected' : ''; ?>>Draft</option>
                    </select>
                </div>

                <div class="admin-field">
                    <label>Weight</label>
                    <input type="number" step="0.01" name="weight" value="<?= e($editProduct['weight'] ?? ''); ?>">
                </div>

                <div class="admin-field">
                    <label>Scent Family</label>
                    <input type="text" name="scent_family" value="<?= e($editProduct['scent_family'] ?? ''); ?>">
                </div>
            </div>

            <div class="admin-field">
                <label>Product Flags</label>

                <div class="admin-product-flags">
                    <label>
                        <input type="checkbox" name="is_featured" <?= !empty($editProduct['is_featured']) ? 'checked' : ''; ?>>
                        <span>Featured</span>
                    </label>

                    <label>
                        <input type="checkbox" name="is_best_seller" <?= !empty($editProduct['is_best_seller']) ? 'checked' : ''; ?>>
                        <span>Best Seller</span>
                    </label>

                    <label>
                        <input type="checkbox" name="is_new_arrival" <?= !empty($editProduct['is_new_arrival']) ? 'checked' : ''; ?>>
                        <span>New Arrival</span>
                    </label>
                </div>
            </div>

            <div class="admin-field">
                <label>Short Description</label>
                <textarea name="short_description"><?= e($editProduct['short_description'] ?? ''); ?></textarea>
            </div>

            <div class="admin-field">
                <label>Description</label>
                <textarea name="description"><?= e($editProduct['description'] ?? ''); ?></textarea>
            </div>

            <div class="admin-form-grid">
                <div class="admin-field">
                    <label>Ingredients / Materials</label>
                    <textarea name="ingredients"><?= e($editProduct['ingredients'] ?? ''); ?></textarea>
                </div>

                <div class="admin-field">
                    <label>How To Use</label>
                    <textarea name="how_to_use"><?= e($editProduct['how_to_use'] ?? ''); ?></textarea>
                </div>
            </div>

            <div class="admin-field">
                <label>Shipping & Return Info</label>
                <textarea name="shipping_return_info"><?= e($editProduct['shipping_return_info'] ?? ''); ?></textarea>
            </div>

            <div class="admin-form-grid">
                <div class="admin-field">
                    <label>SEO Title</label>
                    <input type="text" name="seo_title" value="<?= e($editProduct['seo_title'] ?? ''); ?>">
                </div>

                <div class="admin-field">
                    <label>SEO Description</label>
                    <input type="text" name="seo_description" value="<?= e($editProduct['seo_description'] ?? ''); ?>">
                </div>
            </div>

            <div class="admin-field">
                <label>Product Images</label>
                <input type="file" name="product_images[]" accept="image/jpeg,image/png,image/webp" multiple>
                <small>Accepted: JPG, PNG, WEBP</small>
            </div>

            <?php if ($productImages): ?>
                <div class="admin-product-image-grid">
                    <?php foreach ($productImages as $image): ?>
                        <div class="admin-product-image-card">
                            <img src="<?= e(BASE_URL . '/' . $image['image_path']); ?>" alt="">
                            <?php if (!empty($image['is_primary'])): ?>
                                <span>Primary</span>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <button type="submit" class="admin-btn">
                <?= $editProduct ? 'Update Product' : 'Create Product'; ?>
            </button>
        </form>
    </section>
    <?php if ($editProduct): ?>
        <section class="admin-panel admin-variation-editor-panel">
            <div class="admin-panel-head">
                <div>
                    <h2><?= $editVariation ? 'Edit Variation' : 'Add Product Variation'; ?></h2>
                    <p>Create colour, size, scent, or other product options with separate stock and SKU.</p>
                </div>

                <?php if ($editVariation): ?>
                    <span class="admin-status-pill status-<?= e($editVariation['status']); ?>">
                        Editing Option
                    </span>
                <?php endif; ?>
            </div>

            <form method="POST" enctype="multipart/form-data">
                <?= csrf_field(); ?>

                <input type="hidden" name="form_type" value="variation">
                <input type="hidden" name="product_id" value="<?= e($editProduct['id']); ?>">
                <input type="hidden" name="variation_id" value="<?= e($editVariation['id'] ?? 0); ?>">

                <div class="admin-form-grid">
                    <div class="admin-field">
                        <label>Variation Name</label>
                        <input
                            type="text"
                            name="variation_name"
                            value="<?= e($editVariation['variation_name'] ?? 'Color'); ?>"
                            placeholder="Color"
                            required>
                        <small>Example: Color, Size, Scent</small>
                    </div>

                    <div class="admin-field">
                        <label>Variation Value *</label>
                        <input
                            type="text"
                            name="variation_value"
                            value="<?= e($editVariation['variation_value'] ?? ''); ?>"
                            placeholder="Rose Gold"
                            required>
                        <small>Example: Rose Gold, Black, 100ml</small>
                    </div>

                    <div class="admin-field">
                        <label>Color Code</label>
                        <input
                            type="text"
                            name="color_code"
                            value="<?= e($editVariation['color_code'] ?? ''); ?>"
                            placeholder="#C89B7B">
                        <small>Use only for color variations.</small>
                    </div>

                    <div class="admin-field">
                        <label>Variation SKU</label>
                        <input
                            type="text"
                            name="variation_sku"
                            value="<?= e($editVariation['sku'] ?? ''); ?>"
                            placeholder="LUE-ROSEGOLD-001">
                    </div>

                    <div class="admin-field">
                        <label>Price Adjustment</label>
                        <input
                            type="number"
                            step="0.01"
                            name="price_adjustment"
                            value="<?= e($editVariation['price_adjustment'] ?? '0.00'); ?>">
                        <small>Example: 0.00 or 2.00</small>
                    </div>

                    <div class="admin-field">
                        <label>Variation Stock</label>
                        <input
                            type="number"
                            name="variation_stock_quantity"
                            value="<?= e($editVariation['stock_quantity'] ?? 0); ?>">
                    </div>

                    <div class="admin-field">
                        <label>Status</label>
                        <select name="variation_status">
                            <option value="active" <?= ($editVariation['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="inactive" <?= ($editVariation['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>

                    <div class="admin-field">
                        <label>Variation Image</label>
                        <input type="file" name="variation_image" accept="image/jpeg,image/png,image/webp">

                        <?php if (!empty($editVariation['image_path'])): ?>
                            <div class="admin-variation-current-image">
                                <img src="<?= e(BASE_URL . '/' . $editVariation['image_path']); ?>" alt="">
                                <span>Current image</span>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <button type="submit" class="admin-btn">
                    <?= $editVariation ? 'Update Variation' : 'Add Variation'; ?>
                </button>

                <?php if ($editVariation): ?>
                    <a href="<?= e(ADMIN_URL); ?>/products.php?edit=<?= e($editProduct['id']); ?>" class="admin-btn admin-btn-light">
                        Cancel Variation Edit
                    </a>
                <?php endif; ?>
            </form>
        </section>

        <section class="admin-panel admin-variation-list-panel">
            <div class="admin-panel-head">
                <div>
                    <h2>Product Variations</h2>
                    <p>Manage colour options, variation SKUs, stock, and images.</p>
                </div>

                <span class="admin-status-pill">
                    <?= e(count($productVariations)); ?> option<?= count($productVariations) === 1 ? '' : 's'; ?>
                </span>
            </div>

            <table class="admin-table">
                <thead>
                    <tr>
                        <th>Swatch</th>
                        <th>Variation</th>
                        <th>SKU</th>
                        <th>Price Adjustment</th>
                        <th>Stock</th>
                        <th>Status</th>
                        <th>Image</th>
                        <th>Action</th>
                    </tr>
                </thead>

                <tbody>
                    <?php if (!$productVariations): ?>
                        <tr>
                            <td colspan="8">No variations added yet.</td>
                        </tr>
                    <?php endif; ?>

                    <?php foreach ($productVariations as $variation): ?>
                        <tr>
                            <td>
                                <?php if (!empty($variation['color_code'])): ?>
                                    <span class="admin-product-swatch" style="background:<?= e($variation['color_code']); ?>;"></span>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>

                            <td>
                                <strong><?= e($variation['variation_name']); ?></strong><br>
                                <small><?= e($variation['variation_value']); ?></small>
                            </td>

                            <td><?= e($variation['sku'] ?? '-'); ?></td>

                            <td><?= e(format_price($variation['price_adjustment'])); ?></td>

                            <td><?= e($variation['stock_quantity']); ?></td>

                            <td><?= e(ucfirst($variation['status'])); ?></td>

                            <td>
                                <?php if (!empty($variation['image_path'])): ?>
                                    <img src="<?= e(BASE_URL . '/' . $variation['image_path']); ?>" class="admin-mini-thumb" alt="">
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>

                            <td>
                                <a
                                    class="admin-btn admin-btn-light"
                                    href="<?= e(ADMIN_URL); ?>/products.php?edit=<?= e($editProduct['id']); ?>&edit_variation=<?= e($variation['id']); ?>">
                                    Edit
                                </a>

                                <a
                                    class="admin-btn"
                                    href="<?= e(ADMIN_URL); ?>/products.php?edit=<?= e($editProduct['id']); ?>&delete_variation=<?= e($variation['id']); ?>&product_id=<?= e($editProduct['id']); ?>"
                                    onclick="return confirm('Delete this variation?');">
                                    Delete
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </section>
    <?php endif; ?>

    <section class="admin-panel admin-products-list-panel">
        <div class="admin-panel-head">
            <div>
                <h2>All Products</h2>
                <p>Review product status, stock, images, pricing, and variation availability.</p>
            </div>

            <span class="admin-status-pill">
                <?= e(count($products)); ?> product<?= count($products) === 1 ? '' : 's'; ?>
            </span>
        </div>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Image</th>
                    <th>Product</th>
                    <th>Category</th>
                    <th>Price</th>
                    <th>Stock</th>
                    <th>Status</th>
                    <th>Flags</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$products): ?>
                    <tr>
                        <td colspan="8">No products created yet.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($products as $product): ?>
                    <tr>
                        <td>
                            <?php if (!empty($product['primary_image'])): ?>
                                <img src="<?= e(BASE_URL . '/' . $product['primary_image']); ?>" class="admin-mini-thumb" alt="">
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>

                        <td>
                            <strong><?= e($product['product_name']); ?></strong><br>
                            <small><?= e($product['sku'] ?? 'No SKU'); ?></small>

                            <?php if ((int) ($product['variation_count'] ?? 0) > 0): ?>
                                <br>
                                <small>
                                    <?= e($product['variation_count']); ?>
                                    variation<?= (int) $product['variation_count'] === 1 ? '' : 's'; ?>
                                </small>
                            <?php endif; ?>
                        </td>

                        <td><?= e($product['category_name'] ?? '-'); ?></td>

                        <td>
                            <?php if (!empty($product['sale_price'])): ?>
                                <span style="text-decoration:line-through; color:#888;">
                                    <?= e(format_price($product['regular_price'], $product['currency_code'])); ?>
                                </span><br>
                                <strong><?= e(format_price($product['sale_price'], $product['currency_code'])); ?></strong>
                            <?php else: ?>
                                <?= e(format_price($product['regular_price'], $product['currency_code'])); ?>
                            <?php endif; ?>
                        </td>

                        <td>
                            <?php if ((int) ($product['variation_count'] ?? 0) > 0): ?>
                                <strong><?= e($product['variation_total_stock'] ?? 0); ?></strong><br>
                                <small>
                                    Variation stock ·
                                    <?= e($product['active_variation_count'] ?? 0); ?>
                                    active option<?= (int) ($product['active_variation_count'] ?? 0) === 1 ? '' : 's'; ?>
                                </small>
                            <?php else: ?>
                                <strong><?= e($product['stock_quantity']); ?></strong><br>
                                <small><?= e(str_replace('_', ' ', ucfirst($product['stock_status']))); ?></small>
                            <?php endif; ?>
                        </td>

                        <td>
                            <span class="admin-status-pill status-<?= e($product['status']); ?>">
                                <?= e(ucfirst($product['status'])); ?>
                            </span>
                        </td>

                        <td>
                            <div class="admin-product-flag-list">
                                <?php if ($product['is_featured']): ?>
                                    <span>Featured</span>
                                <?php endif; ?>

                                <?php if ($product['is_best_seller']): ?>
                                    <span>Best Seller</span>
                                <?php endif; ?>

                                <?php if ($product['is_new_arrival']): ?>
                                    <span>New</span>
                                <?php endif; ?>

                                <?php if (!$product['is_featured'] && !$product['is_best_seller'] && !$product['is_new_arrival']): ?>
                                    <small>-</small>
                                <?php endif; ?>
                            </div>
                        </td>

                        <td>
                            <a class="admin-btn admin-btn-light" href="<?= e(ADMIN_URL); ?>/products.php?edit=<?= e($product['id']); ?>">
                                Edit
                            </a>

                            <a
                                class="admin-btn"
                                href="<?= e(ADMIN_URL); ?>/products.php?delete=<?= e($product['id']); ?>"
                                onclick="return confirm('Are you sure you want to delete this product?');">
                                Delete
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>

<?php require_once __DIR__ . '/includes/footer.php'; ?>