<?php
/**
 * Automatic Product Migration Script
 * Converts ALL products with "sizes" to "size_variants" format
 * Also ensures all products have proper structure
 */

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

$dataFile = __DIR__ . '/data/products.json';
$products = [];
if (file_exists($dataFile)) {
    $products = json_decode(file_get_contents($dataFile), true) ?: [];
}

$message = '';
$convertedCount = 0;
$skippedCount = 0;
$results = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Perform migration
    foreach ($products as &$product) {
        $productId = $product['id'] ?? 0;
        
        // If product already has size_variants, skip
        if (isset($product['size_variants']) && !empty($product['size_variants'])) {
            $skippedCount++;
            $results[] = "✓ Product ID {$productId}: Already has size_variants (skipped)";
            continue;
        }
        
        // If product has old "sizes" format, convert it
        if (isset($product['sizes']) && is_array($product['sizes']) && !empty($product['sizes'])) {
            $basePrice = (float)($product['price'] ?? 0);
            $mainImage = $product['image'] ?? '';
            $gallery = $product['gallery'] ?? [];
            
            $sizeVariants = [];
            $priceIncrement = 0;
            
            foreach ($product['sizes'] as $idx => $size) {
                // Determine price for this size
                $sizePriceIncrements = ['XS' => 0, 'S' => 15, 'M' => 0, 'L' => 20, 'XL' => 40, 'XXL' => 60];
                $increment = isset($sizePriceIncrements[$size]) ? $sizePriceIncrements[$size] : ($idx * 15);
                
                // Use gallery images for sizes if available, otherwise use main image
                $sizeImage = isset($gallery[$idx]) ? $gallery[$idx] : $mainImage;
                
                $sizeVariants[] = [
                    'name' => $size,
                    'price' => $basePrice + $increment,
                    'image' => $sizeImage
                ];
            }
            
            // Update product
            $product['size_variants'] = $sizeVariants;
            unset($product['sizes']); // Remove old format
            
            $convertedCount++;
            $results[] = "✓ Product ID {$productId} ({$product['title']}): Converted " . count($sizeVariants) . " sizes";
            
        } elseif (isset($product['size']) && !empty($product['size'])) {
            // Convert single "size" to size_variants
            $basePrice = (float)($product['price'] ?? 0);
            $mainImage = $product['image'] ?? '';
            
            $product['size_variants'] = [[
                'name' => $product['size'],
                'price' => $basePrice,
                'image' => $mainImage
            ]];
            unset($product['size']);
            
            $convertedCount++;
            $results[] = "✓ Product ID {$productId}: Converted single size to variant";
        } else {
            // No sizes at all
            $skippedCount++;
            $results[] = "○ Product ID {$productId}: No sizes (skipped)";
        }
    }
    unset($product); // Break reference
    
    // Save migrated data
    $saveResult = file_put_contents($dataFile, json_encode($products, JSON_PRETTY_PRINT));
    
    if ($saveResult !== false) {
        $message = "Migration complete! Converted: {$convertedCount} | Skipped: {$skippedCount}";
    } else {
        $message = "Error saving data!";
    }
}

// Count stats
$totalProducts = count($products);
$withVariants = 0;
$withOldSizes = 0;
$withoutSizes = 0;

foreach ($products as $product) {
    if (isset($product['size_variants'])) {
        $withVariants++;
    } elseif (isset($product['sizes']) || isset($product['size'])) {
        $withOldSizes++;
    } else {
        $withoutSizes++;
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Automatic Product Migration - Admin</title>
    <link rel="stylesheet" href="styles.css">
    <style>
        body { background: #f5f5f5; }
        .container { max-width: 1000px; margin: 40px auto; padding: 20px; }
        .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 30px; border-radius: 8px; color: #fff; margin-bottom: 20px; }
        .header h1 { margin: 0; font-size: 28px; }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 20px; }
        .stat-card { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .stat-card .number { font-size: 32px; font-weight: 700; color: #667eea; margin: 0; }
        .stat-card .label { color: #666; font-size: 14px; margin: 8px 0 0 0; }
        .message { padding: 16px; border-radius: 8px; margin-bottom: 20px; }
        .message-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .btn { padding: 12px 24px; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; font-weight: 600; }
        .btn-primary { background: #667eea; color: #fff; }
        .btn-primary:hover { background: #5568d3; }
        .btn-danger { background: #e74c3c; color: #fff; }
        .results-section { background: #fff; border-radius: 8px; padding: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .results-section h3 { margin: 0 0 16px 0; color: #333; }
        .result-item { padding: 12px; border-left: 4px solid #667eea; margin-bottom: 8px; background: #f9f9f9; border-radius: 4px; font-family: monospace; font-size: 13px; color: #333; }
        .result-item.success { border-left-color: #27ae60; }
        .result-item.skip { border-left-color: #f39c12; }
        .alert { background: #fff3cd; border: 1px solid #ffc107; padding: 16px; border-radius: 8px; margin-bottom: 20px; }
        .alert strong { color: #856404; }
    </style>
</head>
<body>
<?php include __DIR__ . '/admin_sidebar.php'; ?>
<main class="admin-main-content" style="padding: 24px;">
    <div class="container">
        <div class="header">
            <h1>🔄 Automatic Product Migration</h1>
            <p style="margin: 12px 0 0 0; opacity: 0.9;">Convert all products from old format to size_variants format</p>
        </div>
        
        <?php if (!empty($message)): ?>
        <div class="message message-success">
            ✓ <strong><?php echo htmlspecialchars($message); ?></strong>
        </div>
        <?php endif; ?>
        
        <div class="stats-grid">
            <div class="stat-card">
                <p class="number"><?php echo $totalProducts; ?></p>
                <p class="label">Total Products</p>
            </div>
            <div class="stat-card">
                <p class="number" style="color: #27ae60;"><?php echo $withVariants; ?></p>
                <p class="label">With Size Variants ✓</p>
            </div>
            <div class="stat-card">
                <p class="number" style="color: #e74c3c;"><?php echo $withOldSizes; ?></p>
                <p class="label">With Old Format (Need Migration)</p>
            </div>
            <div class="stat-card">
                <p class="number" style="color: #95a5a6;"><?php echo $withoutSizes; ?></p>
                <p class="label">Without Size Info</p>
            </div>
        </div>
        
        <?php if ($withOldSizes > 0): ?>
        <div class="alert">
            <strong>⚠️ Notice:</strong> You have <?php echo $withOldSizes; ?> product(s) using the old size format. Click "Start Migration" to convert them all automatically.
        </div>
        
        <form method="POST" style="margin-bottom: 20px;">
            <button type="submit" class="btn btn-primary" name="migrate">🚀 Start Migration Now</button>
        </form>
        <?php else: ?>
        <div style="background: #d4edda; border: 1px solid #c3e6cb; padding: 16px; border-radius: 8px; margin-bottom: 20px;">
            <strong style="color: #155724;">✓ All products are up to date!</strong> No migration needed.
        </div>
        <?php endif; ?>
        
        <?php if (!empty($results)): ?>
        <div class="results-section">
            <h3>Migration Results:</h3>
            <?php foreach ($results as $result): 
                $isSuccess = strpos($result, '✓') !== false;
                $isSkip = strpos($result, '○') !== false;
            ?>
                <div class="result-item <?php echo $isSuccess ? 'success' : ($isSkip ? 'skip' : ''); ?>">
                    <?php echo htmlspecialchars($result); ?>
                </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
        
        <div style="margin-top: 30px; padding: 20px; background: #f0f4f8; border-radius: 8px;">
            <h3 style="margin: 0 0 12px 0; color: #333;">📋 What This Migration Does:</h3>
            <ul style="margin: 0; padding-left: 20px; color: #666; line-height: 1.8;">
                <li>Converts all products with "sizes" array to new "size_variants" format</li>
                <li>Automatically calculates prices for each size (small discounts for smaller sizes)</li>
                <li>Uses gallery images for size-specific photos when available</li>
                <li>Removes old "sizes" field from products</li>
                <li>Preserves all other product data</li>
                <li>Creates proper data structure for dropdown and image switching</li>
            </ul>
        </div>
        
        <div style="margin-top: 20px; padding: 20px; background: #fff; border-radius: 8px; border: 1px solid #eee;">
            <h3 style="margin: 0 0 12px 0; color: #333;">✨ After Migration:</h3>
            <ul style="margin: 0; padding-left: 20px; color: #666; line-height: 1.8;">
                <li>Size selection will appear as dropdown (not radio buttons)</li>
                <li>Clicking on sizes will change the main product image</li>
                <li>Color swatches will change the main product image</li>
                <li>Each size variant will have its own price</li>
                <li>Everything works for ALL products automatically</li>
            </ul>
        </div>
        
        <div style="margin-top: 20px;">
            <a href="admin_products.php" style="color: #667eea; text-decoration: none;">← Back to Products</a>
        </div>
    </div>
</main>

<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');
}

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>
