<?php
/**
 * Migration Helper - Convert old "sizes" to new "size_variants"
 * This script helps migrate products from old size format to new size_variants format
 */

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 = '';
$action = isset($_GET['action']) ? $_GET['action'] : '';

if ($action === 'convert') {
    // Convert a single product
    $productId = isset($_GET['product_id']) ? (int)$_GET['product_id'] : 0;
    $basePrice = isset($_GET['base_price']) ? (float)$_GET['base_price'] : 0;
    
    foreach ($products as $idx => $product) {
        if ($product['id'] === $productId && isset($product['sizes']) && !isset($product['size_variants'])) {
            $sizes = $product['sizes'];
            $sizeVariants = [];
            
            // Create price variations (base price, +$20, +$40, etc.)
            $priceIncrements = [0, 20, 40, 60, 80];
            
            foreach ($sizes as $sizeIdx => $size) {
                $priceIncrement = isset($priceIncrements[$sizeIdx]) ? $priceIncrements[$sizeIdx] : ($sizeIdx * 20);
                $sizeVariants[] = [
                    'name' => $size,
                    'price' => $basePrice + $priceIncrement,
                    'image' => $product['image'] ?? '' // Use main image as placeholder
                ];
            }
            
            // Update product
            $products[$idx]['size_variants'] = $sizeVariants;
            unset($products[$idx]['sizes']);
            
            // Save
            file_put_contents($dataFile, json_encode($products, JSON_PRETTY_PRINT));
            $message = 'Product ID ' . $productId . ' converted successfully!';
            break;
        }
    }
    
    if (empty($message)) {
        $message = 'Product not found or already converted.';
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Product Migration Helper - Admin</title>
    <link rel="stylesheet" href="styles.css">
    <style>
        body { background: #f5f5f5; }
        .container { max-width: 900px; margin: 40px auto; padding: 20px; }
        .header { background: #fff; padding: 24px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .header h1 { margin: 0; color: #333; }
        .products-table { background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        table { width: 100%; border-collapse: collapse; }
        th { background: #f9f9f9; padding: 16px; text-align: left; font-weight: 600; color: #333; border-bottom: 1px solid #eee; }
        td { padding: 16px; border-bottom: 1px solid #eee; }
        tr:last-child td { border-bottom: none; }
        .status { padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: 600; }
        .status-old { background: #fff3cd; color: #856404; }
        .status-new { background: #d4edda; color: #155724; }
        .btn { padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; text-decoration: none; display: inline-block; }
        .btn-convert { background: #F07E2D; color: #fff; }
        .btn-convert:hover { background: #d16a95; }
        .message { padding: 16px; border-radius: 8px; margin-bottom: 20px; }
        .message-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; }
        .modal.show { display: flex; align-items: center; justify-content: center; }
        .modal-content { background: #fff; padding: 30px; border-radius: 8px; max-width: 400px; box-shadow: 0 4px 8px rgba(0,0,0,0.2); }
        .modal-content h2 { margin-top: 0; color: #333; }
        .form-group { margin-bottom: 16px; }
        .form-group label { display: block; margin-bottom: 6px; color: #333; font-weight: 600; font-size: 14px; }
        .form-group input { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; }
        .btn-primary { background: #F07E2D; color: #fff; width: 100%; padding: 10px; }
        .btn-primary:hover { background: #d16a95; }
        .btn-cancel { background: #ccc; color: #333; width: 100%; padding: 10px; margin-top: 8px; }
        .btn-cancel:hover { background: #aaa; }
    </style>
</head>
<body>
<?php include __DIR__ . '/admin_sidebar.php'; ?>
<main class="admin-main-content" style="padding: 24px;">
    <div class="container">
        <div class="header">
            <h1>📦 Product Migration Helper</h1>
            <p style="margin: 12px 0 0 0; color: #666; font-size: 14px;">Convert old "sizes" format to new "size_variants" format with individual prices</p>
        </div>
        
        <?php if (!empty($message)): ?>
        <div class="message message-success">
            ✓ <?php echo htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>
        
        <div class="products-table">
            <table>
                <thead>
                    <tr>
                        <th>Product ID</th>
                        <th>Title</th>
                        <th>Current Format</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $needsMigration = [];
                    $alreadyMigrated = [];
                    
                    foreach ($products as $product) {
                        if (isset($product['sizes']) && !isset($product['size_variants'])) {
                            $needsMigration[] = $product;
                        } elseif (isset($product['size_variants'])) {
                            $alreadyMigrated[] = $product;
                        }
                    }
                    
                    // Show products needing migration
                    foreach ($needsMigration as $product):
                    ?>
                    <tr>
                        <td><?php echo $product['id']; ?></td>
                        <td><?php echo htmlspecialchars($product['title']); ?></td>
                        <td><span class="status status-old">Old Format (sizes)</span></td>
                        <td>
                            <button class="btn btn-convert" onclick="openConvertModal(<?php echo $product['id']; ?>, '<?php echo htmlspecialchars($product['title']); ?>', <?php echo $product['price']; ?>)">
                                Convert
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    
                    <?php if (empty($needsMigration)): ?>
                    <tr>
                        <td colspan="4" style="text-align: center; color: #999; padding: 40px;">
                            ✓ All products have been migrated!
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <?php if (!empty($alreadyMigrated)): ?>
        <div style="margin-top: 40px;">
            <h3 style="color: #333; margin-bottom: 16px;">✓ Already Migrated (<?php echo count($alreadyMigrated); ?> products)</h3>
            <div style="background: #fff; border-radius: 8px; padding: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <table>
                    <thead>
                        <tr>
                            <th>Product ID</th>
                            <th>Title</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($alreadyMigrated as $product): ?>
                        <tr>
                            <td><?php echo $product['id']; ?></td>
                            <td><?php echo htmlspecialchars($product['title']); ?></td>
                            <td><span class="status status-new">New Format (size_variants)</span></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<!-- Convert Modal -->
<div id="convertModal" class="modal">
    <div class="modal-content">
        <h2>Convert Product</h2>
        <form onsubmit="submitConversion(event)">
            <div class="form-group">
                <label>Product:</label>
                <p id="productName" style="margin: 0; color: #666; padding: 8px; background: #f9f9f9; border-radius: 4px;"></p>
            </div>
            
            <div class="form-group">
                <label>Base Price (for XS size):</label>
                <input type="number" id="basePrice" step="0.01" required>
                <p style="margin: 6px 0 0 0; font-size: 12px; color: #666;">
                    Other sizes will increase by $20 each (S: +$20, M: +$40, L: +$60, XL: +$80)
                </p>
            </div>
            
            <button type="submit" class="btn btn-primary">Convert Product</button>
            <button type="button" class="btn btn-cancel" onclick="closeConvertModal()">Cancel</button>
        </form>
    </div>
</div>

<script>
let modalProductId = 0;

function openConvertModal(productId, productName, basePrice) {
    modalProductId = productId;
    document.getElementById('productName').textContent = productName;
    document.getElementById('basePrice').value = basePrice;
    document.getElementById('convertModal').classList.add('show');
}

function closeConvertModal() {
    document.getElementById('convertModal').classList.remove('show');
}

function submitConversion(event) {
    event.preventDefault();
    const basePrice = parseFloat(document.getElementById('basePrice').value);
    window.location.href = '?action=convert&product_id=' + modalProductId + '&base_price=' + basePrice;
}
</script>
<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>
