<?php
session_start();
if (empty($_SESSION['is_admin']) && (empty($_SESSION['user_type']) || $_SESSION['user_type'] !== 'admin')) {
    header('Location: index.php');
    exit;
}

require_once __DIR__ . '/helpers/database_helper.php';

$products = DatabaseHelper::loadJson('products.json', []);

// Load categories for dropdown
$categories = DatabaseHelper::loadJson('categories.json', []);

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$itemKey = null;
$p = [];
foreach ($products as $k => $prod) {
    if ($prod['id'] === $id) {
        $itemKey = $k;
        $p = $prod;
        break;
    }
}
if ($itemKey === null || empty($p)) {
    header('Location: admin_products.php');
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $price = (float)($_POST['price'] ?? 0);
    $cat = trim($_POST['cat'] ?? '');
    $desc = trim($_POST['desc'] ?? '');
    $tags = trim($_POST['tags'] ?? '');
    $brand = trim($_POST['brand'] ?? '');
    $rating = isset($_POST['rating']) && $_POST['rating'] !== '' ? (float)$_POST['rating'] : null;
    $salePrice = isset($_POST['sale_price']) && $_POST['sale_price'] !== '' ? (float)$_POST['sale_price'] : null;
    $onSale = isset($_POST['on_sale']) ? true : false;
    $featured = isset($_POST['featured']) ? true : false;
    
    // Handle size variants with individual prices and images
    $sizeVariants = [];
    if (!empty($_POST['size_variants']) && is_array($_POST['size_variants'])) {
        foreach ($_POST['size_variants'] as $idx => $variant) {
            $sizeName = trim($variant['name'] ?? '');
            $sizePrice = (float)($variant['price'] ?? 0);
            
            if (!empty($sizeName) && $sizePrice > 0) {
                $sizeVariants[] = [
                    'name' => $sizeName,
                    'price' => $sizePrice,
                    'image' => $variant['image'] ?? '' // Image path will be updated below
                ];
            }
        }
    }
    
    // Handle main image update
    if (!empty($_FILES['image']['tmp_name']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $dest = __DIR__ . '/pics_ecom/' . basename($_FILES['image']['name']);
        if (move_uploaded_file($_FILES['image']['tmp_name'], $dest)) {
            $products[$itemKey]['image'] = 'pics_ecom/' . basename($_FILES['image']['name']);
        }
    }
    
    // Handle gallery images - fix for multiple files
    if (isset($_FILES['gallery'])) {
        $gallery = $products[$itemKey]['gallery'] ?? [];
        $galleryCount = count($_FILES['gallery']['tmp_name']);
        for ($i = 0; $i < $galleryCount; $i++) {
            if (!empty($_FILES['gallery']['tmp_name'][$i]) && $_FILES['gallery']['error'][$i] === UPLOAD_ERR_OK) {
                $origName = $_FILES['gallery']['name'][$i];
                $dest = __DIR__ . '/pics_ecom/' . basename($origName);
                if (move_uploaded_file($_FILES['gallery']['tmp_name'][$i], $dest)) {
                    $gallery[] = 'pics_ecom/' . basename($origName);
                }
            }
        }
        $products[$itemKey]['gallery'] = $gallery;
    }
    
    // Handle product video upload/update
    if (!empty($_FILES['video']['tmp_name']) && $_FILES['video']['error'] === UPLOAD_ERR_OK) {
        $videoName = basename($_FILES['video']['name']);
        $videoExt = strtolower(pathinfo($videoName, PATHINFO_EXTENSION));
        $allowedVideoExts = ['mp4', 'webm', 'mov', 'avi', 'mkv'];
        
        if (in_array($videoExt, $allowedVideoExts)) {
            $videoFileName = 'video_' . time() . '_' . rand(1000, 9999) . '.' . $videoExt;
            $videoDest = __DIR__ . '/pics_ecom/' . $videoFileName;
            if (move_uploaded_file($_FILES['video']['tmp_name'], $videoDest)) {
                $products[$itemKey]['video'] = 'pics_ecom/' . $videoFileName;
            }
        }
    }
    
    // Handle size variant images
    if (isset($_FILES['size_variant_images']) && !empty($sizeVariants)) {
        $variantCount = count($_FILES['size_variant_images']['tmp_name']);
        for ($i = 0; $i < $variantCount && $i < count($sizeVariants); $i++) {
            if (!empty($_FILES['size_variant_images']['tmp_name'][$i]) && $_FILES['size_variant_images']['error'][$i] === UPLOAD_ERR_OK) {
                $origName = $_FILES['size_variant_images']['name'][$i];
                $dest = __DIR__ . '/pics_ecom/' . basename($origName);
                if (move_uploaded_file($_FILES['size_variant_images']['tmp_name'][$i], $dest)) {
                    $sizeVariants[$i]['image'] = 'pics_ecom/' . basename($origName);
                }
            }
        }
    }
    
    // Handle color images - add new colors or update existing
    $colors = $products[$itemKey]['colors'] ?? [];
    
    // Handle new color uploads with color codes
    if (isset($_FILES['color_images'])) {
        $colorCount = count($_FILES['color_images']['tmp_name']);
        $colorNames = $_POST['color_names'] ?? [];
        $colorCodes = $_POST['color_codes'] ?? [];
        
        for ($i = 0; $i < $colorCount; $i++) {
            $colorName = trim($colorNames[$i] ?? '');
            $colorCode = trim($colorCodes[$i] ?? '#cccccc');
            
            if (!empty($colorName)) {
                $colorData = [
                    'name' => $colorName,
                    'code' => $colorCode
                ];
                
                // Only add image if one was uploaded
                if (!empty($_FILES['color_images']['tmp_name'][$i]) && $_FILES['color_images']['error'][$i] === UPLOAD_ERR_OK) {
                    $origName = $_FILES['color_images']['name'][$i];
                    $dest = __DIR__ . '/pics_ecom/' . basename($origName);
                    if (move_uploaded_file($_FILES['color_images']['tmp_name'][$i], $dest)) {
                        $colorData['image'] = 'pics_ecom/' . basename($origName);
                    }
                }
                
                $colors[] = $colorData;
            }
        }
    }
    
    // Handle color deletion (must be done BEFORE other updates)
    if (isset($_POST['delete_color']) && !isset($_POST['title'])) {
        // This is a delete-only request
        $deleteIdx = (int)$_POST['delete_color'];
        if (isset($colors[$deleteIdx])) {
            unset($colors[$deleteIdx]);
            $colors = array_values($colors); // Re-index array
            $products[$itemKey]['colors'] = $colors;
            // Save immediately and redirect
            if (DatabaseHelper::saveJson('products.json', $products)) {
                header('Location: admin_edit_product.php?id=' . $id);
                exit;
            }
        }
    }
    
    // Update product fields only if this is a full form submission (not just delete)
    if (isset($_POST['title'])) {
        $products[$itemKey]['title'] = $title;
        $products[$itemKey]['price'] = $price;
        $products[$itemKey]['cat'] = $cat;
        $products[$itemKey]['desc'] = $desc;
        $products[$itemKey]['tags'] = $tags;
        
        // Handle video removal
        if (isset($_POST['remove_video']) && $_POST['remove_video'] === 'on') {
            unset($products[$itemKey]['video']);
        }
        
        // Update brand
        if (!empty($brand)) {
            $products[$itemKey]['brand'] = $brand;
        } else {
            unset($products[$itemKey]['brand']);
        }
        
        // Update rating
        if ($rating !== null && $rating > 0) {
            $products[$itemKey]['rating'] = $rating;
        } else {
            unset($products[$itemKey]['rating']);
        }
        
        // Update sale price
        if ($salePrice !== null && $salePrice > 0) {
            $products[$itemKey]['sale_price'] = $salePrice;
            $products[$itemKey]['on_sale'] = true;
        } elseif ($onSale) {
            $products[$itemKey]['on_sale'] = true;
        } else {
            unset($products[$itemKey]['sale_price']);
            unset($products[$itemKey]['on_sale']);
        }
        
        // Update featured flag
        if ($featured) {
            $products[$itemKey]['featured'] = true;
        } else {
            unset($products[$itemKey]['featured']);
        }
        
        // Update size variants (new system)
        if (!empty($sizeVariants)) {
            $products[$itemKey]['size_variants'] = $sizeVariants;
        } elseif (isset($products[$itemKey]['size_variants'])) {
            unset($products[$itemKey]['size_variants']);
        }
        
        // Remove old sizes field if exists
        if (isset($products[$itemKey]['sizes'])) {
            unset($products[$itemKey]['sizes']);
        }
        if (isset($products[$itemKey]['size'])) {
            unset($products[$itemKey]['size']);
        }
        
        // Always save colors array (even if empty) - this ensures new colors are saved
        $products[$itemKey]['colors'] = $colors;
        
        if (DatabaseHelper::saveJson('products.json', $products)) {
            $_SESSION['success'] = 'Product updated successfully!';
            header('Location: admin_products.php');
            exit;
        } else {
            $error = 'Failed to save product. Please check file permissions and try again.';
        }
    }
}

$p = $products[$itemKey];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Edit Product - Admin</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body class="admin-with-sidebar">
<?php include __DIR__ . '/admin_sidebar.php'; ?>
<?php // Admin pages don't include the main site header ?>
<main class="admin-main-content" style="padding: 24px;">
    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:16px;">
        <h1 style="margin:0;">Edit Product</h1>
        <a href="admin_products.php" class="btn" style="background:#F07E2D; color:#fff; text-decoration:none; padding:8px 12px; border-radius:6px;">← Back to Products</a>
    </div>
    <?php if ($error): ?>
    <p class="muted"><?php echo htmlspecialchars($error); ?></p>
    <?php endif; ?>
    <form method="post" enctype="multipart/form-data" style="display:flex;flex-direction:column;gap:8px;max-width:600px;background:#fff;padding:16px;border-radius:8px;">
        <input type="text" name="title" value="<?php echo htmlspecialchars($p['title'] ?? ''); ?>" placeholder="Title" required>
        <input type="number" name="price" step="0.01" value="<?php echo htmlspecialchars($p['price'] ?? ''); ?>" placeholder="Price" required>
        
        <label style="font-weight:600;">Category:</label>
        <select name="cat" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px;">
            <option value="">-- Select Category --</option>
            <?php 
            $currentCat = $p['cat'] ?? '';
            // Group categories by parent
            foreach ($categories as $cat):
                if (empty($cat['parent_id'])): // Top-level categories
            ?>
                <option value="<?php echo htmlspecialchars($cat['name']); ?>" <?php echo $currentCat === $cat['name'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
                <?php 
                    // Show subcategories under parent
                    foreach ($categories as $subcat):
                        if ($subcat['parent_id'] === $cat['id']):
                ?>
                    <option value="<?php echo htmlspecialchars($subcat['name']); ?>" style="padding-left:20px;" <?php echo $currentCat === $subcat['name'] ? 'selected' : ''; ?>>→ <?php echo htmlspecialchars($subcat['name']); ?></option>
                <?php 
                        endif;
                    endforeach;
                endif;
            endforeach; 
            ?>
        </select>
        
        <label style="font-weight:600; margin-top:8px;">Product Size Variants (with different prices and images):</label>
        <div style="background:#f9f9f9; padding:12px; border-radius:6px;">
            <p style="font-size:12px; color:#666; margin:0 0 12px 0;">Add different sizes with their own prices and product images. Each size can have a unique photo showing the product in that size.</p>
            
            <div id="sizeVariantsContainer">
                <?php 
                $currentVariants = $p['size_variants'] ?? [];
                if (!empty($currentVariants)):
                    foreach ($currentVariants as $idx => $variant):
                ?>
                    <div style="background:#fff; padding:12px; border-radius:6px; margin-bottom:12px; border-left:4px solid #F07E2D;">
                        <div style="display:grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap:8px; align-items:flex-end; margin-bottom:8px;">
                            <div>
                                <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Size Name</label>
                                <input type="text" name="size_variants[<?php echo $idx; ?>][name]" value="<?php echo htmlspecialchars($variant['name'] ?? ''); ?>" placeholder="e.g., S, M, L" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;">
                            </div>
                            <div>
                                <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Price for this Size</label>
                                <input type="number" name="size_variants[<?php echo $idx; ?>][price]" step="0.01" value="<?php echo htmlspecialchars($variant['price'] ?? ''); ?>" placeholder="0.00" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;">
                            </div>
                            <div>
                                <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Current Image</label>
                                <?php if (!empty($variant['image'])): ?>
                                    <img src="<?php echo htmlspecialchars($variant['image']); ?>" style="height:35px; border-radius:4px; border:1px solid #ddd;">
                                <?php else: ?>
                                    <span style="color:#999; font-size:11px;">No image</span>
                                <?php endif; ?>
                            </div>
                            <div>
                                <button type="button" onclick="removeVariant(this)" style="background:#dc3545; color:#fff; border:none; padding:8px 12px; border-radius:4px; cursor:pointer; font-size:12px;">Remove</button>
                            </div>
                        </div>
                    </div>
                <?php 
                    endforeach;
                endif;
                ?>
            </div>
            
            <button type="button" onclick="addSizeVariant()" style="background:#28a745; color:#fff; border:none; padding:8px 16px; border-radius:4px; cursor:pointer; font-size:12px; font-weight:600;">+ Add Size Variant</button>
            
            <div style="margin-top:12px; padding-top:12px; border-top:1px solid #e6e6e6;">
                <label style="font-weight:600; display:block; margin-bottom:8px; font-size:13px;">Upload Images for Each Size:</label>
                <p style="font-size:11px; color:#999; margin:0 0 8px 0;">Select images in the same order as your size variants above</p>
                <input type="file" name="size_variant_images[]" accept="image/*" multiple style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;">
            </div>
        </div>
        
        <textarea name="desc" placeholder="Description" style="resize:vertical; min-height:80px;"><?php echo htmlspecialchars($p['desc'] ?? ''); ?></textarea>
        <input type="text" name="tags" value="<?php echo htmlspecialchars($p['tags'] ?? ''); ?>" placeholder="Tags (e.g., dress, summer, casual, cotton) - separated by comma">
        
        <label style="font-weight:600; margin-top:8px;">Brand:</label>
        <?php
        $brandsFile = __DIR__ . '/data/brands.json';
        $brandsList = [];
        if (file_exists($brandsFile)) {
            $brandsData = json_decode(file_get_contents($brandsFile), true);
            if (is_array($brandsData)) {
                $brandsList = $brandsData;
            }
        }
        ?>
        <input type="text" name="brand" list="brands-list" value="<?php echo htmlspecialchars($p['brand'] ?? ''); ?>" placeholder="Enter brand name (optional)" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px;">
        <datalist id="brands-list">
            <?php foreach ($brandsList as $brand): ?>
                <option value="<?php echo htmlspecialchars($brand['name']); ?>">
            <?php endforeach; ?>
        </datalist>
        
        <label style="font-weight:600; margin-top:8px;">Rating (0-5):</label>
        <input type="number" name="rating" step="0.1" min="0" max="5" value="<?php echo isset($p['rating']) ? $p['rating'] : ''; ?>" placeholder="e.g., 4.5" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px;">
        
        <label style="font-weight:600; margin-top:8px;">Sale Price (Optional - leave empty if not on sale):</label>
        <input type="number" name="sale_price" step="0.01" min="0" value="<?php echo isset($p['sale_price']) ? $p['sale_price'] : ''; ?>" placeholder="e.g., 29.99" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px;">
        <label style="font-weight:600; display:flex; align-items:center; gap:8px; margin-top:4px;">
            <input type="checkbox" name="on_sale" <?php echo (isset($p['on_sale']) && $p['on_sale']) || isset($p['sale_price']) ? 'checked' : ''; ?>> Mark as On Sale
        </label>
        <label style="font-weight:600; display:flex; align-items:center; gap:8px; margin-top:8px;">
            <input type="checkbox" name="featured" <?php echo !empty($p['featured']) ? 'checked' : ''; ?>> Mark as Featured Product
        </label>
        
        <div style="border:1px solid #eee; padding:12px; border-radius:6px; background:#f9f9f9;">
            <strong>Main Image:</strong>
            <?php if (!empty($p['image'])): ?>
                <img src="<?php echo htmlspecialchars($p['image']); ?>" style="height:80px;margin:8px 0; display:block; border-radius:4px;"/>
            <?php else: ?>
                <p style="color:#999; font-size:13px; margin:8px 0;">No main image set</p>
            <?php endif; ?>
            <label style="display:block; margin-top:8px;">Replace Main Image: <input type="file" name="image" accept="image/*"></label>
        </div>
        
        <div style="border:1px solid #eee; padding:12px; border-radius:6px; background:#f9f9f9;">
            <strong>Product Gallery:</strong>
            <?php if (!empty($p['gallery']) && is_array($p['gallery'])): ?>
                <div style="display:grid; grid-template-columns:repeat(auto-fill, minmax(70px, 1fr)); gap:8px; margin:8px 0;">
                    <?php foreach ($p['gallery'] as $idx => $img): ?>
                        <div style="position:relative;">
                            <img src="<?php echo htmlspecialchars($img); ?>" style="width:100%; height:70px; object-fit:cover; border-radius:4px; display:block;"/>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p style="color:#999; font-size:13px; margin:8px 0;">No gallery images uploaded</p>
            <?php endif; ?>
            <label style="display:block; margin-top:8px;">Add Gallery Images (select multiple files): <input type="file" name="gallery[]" accept="image/*" multiple></label>
            <p style="font-size:11px; color:#999; margin:4px 0 0 0;">Hold Ctrl/Cmd and click to select multiple images</p>
        </div>
        
        <div style="border:1px solid #eee; padding:12px; border-radius:6px; background:#f9f9f9;">
            <strong style="color:#F07E2D;">Product Video:</strong>
            <?php if (!empty($p['video'])): ?>
                <p style="font-size:12px; color:#666; margin:8px 0;">Current video: <code style="background:#eee; padding:2px 6px; border-radius:3px;"><?php echo htmlspecialchars(basename($p['video'])); ?></code></p>
                <video style="width:100%; height:auto; max-height:200px; border-radius:4px; margin:8px 0; background:#000;" controls>
                    <source src="<?php echo htmlspecialchars($p['video']); ?>" type="video/mp4">
                    Your browser does not support the video tag.
                </video>
                <br>
                <label style="display:flex; align-items:center; gap:8px; margin-top:8px; font-size:12px;"><input type="checkbox" name="remove_video"> Remove current video</label>
            <?php else: ?>
                <p style="color:#999; font-size:13px; margin:8px 0;">No video uploaded</p>
            <?php endif; ?>
            <label style="display:block; margin-top:8px;">Upload New Video (MP4, WebM, MOV, AVI, MKV): <input type="file" name="video" accept="video/*"></label>
        </div>
        
        <div style="border:1px solid #eee; padding:12px; border-radius:6px; background:#f9f9f9;">
            <strong style="color:#F07E2D;">Color Swatches:</strong>
            <?php if (!empty($p['colors']) && is_array($p['colors'])): ?>
                <div style="margin:12px 0;">
                    <strong style="display:block; margin-bottom:8px; font-size:12px;">Current Swatches:</strong>
                    <div style="display:flex; gap:8px; flex-wrap:wrap; margin-bottom:12px;">
                        <?php foreach ($p['colors'] as $idx => $color): ?>
                            <div style="position:relative; text-align:center;">
                                <div style="width:50px; height:50px; background-color: <?php echo htmlspecialchars($color['code'] ?? '#cccccc'); ?>; border-radius:50%; border:3px solid #ddd; display:flex; align-items:center; justify-content:center; position:relative;">
                                    <span style="font-size:10px; color:#fff; text-shadow: 0 1px 2px rgba(0,0,0,0.5); font-weight:bold; position:absolute;">●</span>
                                </div>
                                <div style="font-size:11px; margin-top:4px; color:#333; font-weight:600;"><?php echo htmlspecialchars($color['name']); ?></div>
                                <div style="font-size:10px; margin:2px 0; color:#666;"><?php echo htmlspecialchars($color['code'] ?? '#cccccc'); ?></div>
                                <?php if (isset($color['image']) && !empty($color['image'])): ?>
                                    <img src="<?php echo htmlspecialchars($color['image']); ?>" style="width:40px; height:40px; object-fit:cover; border-radius:4px; margin:4px 0; display:block; border:1px solid #ddd;">
                                <?php else: ?>
                                    <p style="font-size:9px; color:#f00; margin:4px 0;">No image</p>
                                <?php endif; ?>
                                <button type="button" onclick="deleteColorSwatch(<?php echo $idx; ?>)" class="btn" style="background:#dc3545; padding:4px 8px; font-size:11px; margin-top:4px;">Delete</button>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php else: ?>
                <p style="color:#999; font-size:13px; margin:8px 0;">No color swatches added yet</p>
            <?php endif; ?>
            
            <div style="margin-top:12px; padding-top:12px; border-top:1px solid #e6e6e6;">
                <strong style="display:block; margin-bottom:8px; font-size:13px;">Add New Color Swatch:</strong>
                <div id="newColorContainer" style="display:flex; gap:8px; align-items:flex-end; padding:8px; background:#fff; border-radius:4px;">
                    <div style="flex:1;">
                        <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Color Name</label>
                        <input type="text" name="color_names[]" placeholder="e.g., Red, Blue, Black" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;">
                    </div>
                    <div style="flex:0.5;">
                        <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Color Code</label>
                        <input type="color" name="color_codes[]" value="#FF0000" style="width:100%; height:38px; border:1px solid #ddd; border-radius:4px; cursor:pointer;">
                    </div>
                    <div style="flex:1;">
                        <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Product Image</label>
                        <input type="file" name="color_images[]" accept="image/*" style="width:100%; padding:4px; border:1px solid #ddd; border-radius:4px;">
                    </div>
                    <button type="button" onclick="addAnotherColor()" class="btn" style="background:#28a745; padding:8px 12px; font-size:12px; align-self:center;">+ Add</button>
                </div>
                <div id="additionalColors"></div>
            </div>
        </div>
        
        <button class="btn" type="submit" style="background:#F07E2D; color:#fff; padding:12px 24px; font-size:16px; font-weight:600; border:none; border-radius:6px; cursor:pointer; margin-top:12px;">Save Changes</button>
    </form>
</main>
<?php include __DIR__ . '/footer.php'; ?>
<script>
function toggleAdminSidebar() {
    const sidebar = document.getElementById('adminSidebarContainer');
    const mainContent = document.querySelector('.admin-main-content');
    sidebar.classList.toggle('collapsed');
    mainContent.classList.toggle('with-collapsed-sidebar');
    localStorage.setItem('adminSidebarCollapsed', sidebar.classList.contains('collapsed') ? '1' : '0');
}

function addAnotherColor() {
    const container = document.getElementById('additionalColors');
    const newColor = document.createElement('div');
    newColor.style.cssText = 'display:flex; gap:8px; align-items:flex-end; margin-top:8px; padding:8px; background:#fff; border-radius:4px;';
    newColor.innerHTML = `
        <div style="flex:1;">
            <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Color Name</label>
            <input type="text" name="color_names[]" placeholder="e.g., Red, Blue, Black" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;">
        </div>
        <div style="flex:0.5;">
            <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Color Code</label>
            <input type="color" name="color_codes[]" value="#FF0000" style="width:100%; height:38px; border:1px solid #ddd; border-radius:4px; cursor:pointer;">
        </div>
        <div style="flex:1;">
            <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Product Image</label>
            <input type="file" name="color_images[]" accept="image/*" style="width:100%; padding:4px; border:1px solid #ddd; border-radius:4px;">
        </div>
        <button type="button" onclick="this.parentElement.remove()" class="btn" style="background:#dc3545; padding:8px 12px; font-size:12px; align-self:center;">Remove</button>
    `;
    container.appendChild(newColor);
}

function deleteColorSwatch(idx) {
    if (!confirm('Are you sure you want to delete this color swatch?')) {
        return;
    }
    
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = window.location.href;
    
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'delete_color';
    input.value = idx;
    
    form.appendChild(input);
    document.body.appendChild(form);
    form.submit();
}

function addSizeVariant() {
    const container = document.getElementById('sizeVariantsContainer');
    const newIdx = container.children.length;
    
    const newVariant = document.createElement('div');
    newVariant.style.cssText = 'background:#fff; padding:12px; border-radius:6px; margin-bottom:12px; border-left:4px solid #F07E2D;';
    newVariant.innerHTML = `
        <div style="display:grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap:8px; align-items:flex-end; margin-bottom:8px;">
            <div>
                <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Size Name</label>
                <input type="text" name="size_variants[${newIdx}][name]" placeholder="e.g., S, M, L" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;">
            </div>
            <div>
                <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Price for this Size</label>
                <input type="number" name="size_variants[${newIdx}][price]" step="0.01" placeholder="0.00" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;">
            </div>
            <div style="color:#999; font-size:11px;">Image uploaded separately</div>
            <div>
                <button type="button" onclick="removeVariant(this)" style="background:#dc3545; color:#fff; border:none; padding:8px 12px; border-radius:4px; cursor:pointer; font-size:12px;">Remove</button>
            </div>
        </div>
    `;
    
    container.appendChild(newVariant);
}

function removeVariant(btn) {
    btn.closest('div[style*="border-left:4px"]').remove();
}

document.addEventListener('DOMContentLoaded', function() {
    const isCollapsed = localStorage.getItem('adminSidebarCollapsed') === '1';
    if (isCollapsed) {
        document.getElementById('adminSidebarContainer').classList.add('collapsed');
        document.querySelector('.admin-main-content').classList.add('with-collapsed-sidebar');
    }
});
</script>
</body>
</html>
