<?php
$products = json_decode(file_get_contents('../js/products.json'), true);
$product = current(array_filter($products, fn($p) => $p['id'] == $_GET['id']));
$verients = $product['verients'] ?? [];

// Parse existing color and storage variants
$existingColors = [];
$existingStorage = [];
$storageLabel = 'Storage';
foreach ($verients as $v) {
    if ($v['type'] === 'color') {
        $existingColors = $v['options'];
    } elseif (in_array($v['type'], ['storage', 'ram_storage', 'model'])) {
        $existingStorage = $v['options'];
        $storageLabel = $v['label'] ?? 'Storage';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Edit Product</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
  <style>
    body { font-family: 'Inter', sans-serif; background: linear-gradient(to right, #0f172a, #1e293b); }
    .glass { background: rgba(255,255,255,0.05); backdrop-filter: blur(20px); border: 1px solid rgba(255,255,255,0.1); }
    input:focus, textarea:focus, select:focus { box-shadow: 0 0 0 3px rgba(34,211,238,0.6); outline: none; }
    .variant-row { display: flex; gap: 8px; align-items: center; margin-bottom: 8px; }
    .remove-btn { background: #ef4444; color: white; border: none; border-radius: 6px; padding: 6px 12px; cursor: pointer; font-size: 12px; white-space: nowrap; }
    .add-btn { background: #10b981; color: white; border: none; border-radius: 6px; padding: 8px 16px; cursor: pointer; font-size: 13px; font-weight: 600; }
    .section-card { background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; padding: 16px; margin-bottom: 4px; }
  </style>
</head>
<body class="text-white min-h-screen p-6">
  <div class="w-full max-w-3xl mx-auto glass rounded-2xl shadow-2xl p-8">
    <div class="flex items-center mb-8 gap-4">
      <a href="main.php" class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg text-sm font-semibold">← Back</a>
      <h1 class="text-3xl font-extrabold text-cyan-300">Edit Product</h1>
    </div>
    <form action="process_product.php" method="POST" class="space-y-6">
      <input type="hidden" name="id" value="<?= $product['id'] ?>">

      <div>
        <label class="block text-sm font-medium mb-2 text-cyan-100">Product Name *</label>
        <input type="text" name="name" value="<?= htmlspecialchars($product['name']) ?>" required
               class="w-full px-4 py-3 rounded-lg bg-gray-900 text-white border border-gray-600">
      </div>

      <div class="grid grid-cols-2 gap-4">
        <div>
          <label class="block text-sm font-medium mb-2 text-cyan-100">Selling Price (₹) *</label>
          <input type="number" name="selling_price" value="<?= $product['selling_price'] ?>" required
                 class="w-full px-4 py-3 rounded-lg bg-gray-900 text-white border border-gray-600">
        </div>
        <div>
          <label class="block text-sm font-medium mb-2 text-cyan-100">MRP (₹) *</label>
          <input type="number" name="mrp" value="<?= $product['mrp'] ?>" required
                 class="w-full px-4 py-3 rounded-lg bg-gray-900 text-white border border-gray-600">
        </div>
      </div>

      <div>
        <label class="block text-sm font-medium mb-2 text-cyan-100">Product Images (Amazon/any URL)</label>
        <div class="space-y-3">
          <?php for ($i = 1; $i <= 5; $i++): ?>
            <input type="url" name="img<?= $i ?>" value="<?= $product["img$i"] ?? '' ?>"
                   placeholder="Image <?= $i ?> URL"
                   class="w-full px-4 py-3 rounded-lg bg-gray-900 text-white border border-gray-600">
          <?php endfor; ?>
        </div>
      </div>

      <div>
        <label class="block text-sm font-medium mb-2 text-cyan-100">Product Features / Description</label>
        <textarea name="features" rows="4"
                  class="w-full px-4 py-3 rounded-lg bg-gray-900 text-white border border-gray-600 resize-none"><?= htmlspecialchars($product['fetaures'] ?? '') ?></textarea>
      </div>

      <!-- COLOUR VARIANTS -->
      <div class="section-card">
        <div class="flex items-center justify-between mb-4">
          <div>
            <h3 class="text-lg font-bold text-cyan-200">🎨 Colour Variants</h3>
            <p class="text-xs text-gray-400 mt-1">Chhod do agar colour option nahi chahiye</p>
          </div>
          <button type="button" onclick="addColorRow()" class="add-btn">+ Add Colour</button>
        </div>
        <div id="colorVariants" class="space-y-2"></div>
        <p class="text-xs text-gray-500 mt-2">Tip: Colour image ke liye us colour ka Amazon product image URL daalo</p>
      </div>

      <!-- STORAGE VARIANTS -->
      <div class="section-card">
        <div class="flex items-center justify-between mb-4">
          <div>
            <h3 class="text-lg font-bold text-cyan-200">💾 Storage / RAM Variants</h3>
            <p class="text-xs text-gray-400 mt-1">Chhod do agar storage option nahi chahiye</p>
          </div>
          <button type="button" onclick="addStorageRow()" class="add-btn">+ Add Option</button>
        </div>
        <div class="mb-3">
          <select name="storage_label" class="px-3 py-2 rounded-lg bg-gray-900 text-white border border-gray-600 text-sm">
            <option value="Storage" <?= $storageLabel==='Storage'?'selected':'' ?>>Storage (GB/TB)</option>
            <option value="RAM + Storage" <?= $storageLabel==='RAM + Storage'?'selected':'' ?>>RAM + Storage</option>
            <option value="Model" <?= $storageLabel==='Model'?'selected':'' ?>>Model</option>
          </select>
        </div>
        <div id="storageVariants" class="space-y-2"></div>
      </div>

      <div class="flex justify-between items-center pt-4">
        <a href="main.php" class="px-6 py-3 bg-gray-700 hover:bg-gray-600 rounded-lg text-sm font-semibold transition shadow">Cancel</a>
        <button type="submit" name="action" value="update"
                class="px-8 py-3 bg-cyan-500 hover:bg-cyan-600 text-black font-bold rounded-lg shadow-lg transition text-base">
          💾 Save Changes
        </button>
      </div>
    </form>
  </div>

  <script>
    let colorCount = 0;
    let storageCount = 0;

    function addColorRow(name='', img='', isDefault=false) {
      colorCount++;
      const id = 'color_' + colorCount;
      const div = document.createElement('div');
      div.className = 'variant-row';
      div.id = id;
      div.innerHTML = `
        <div style="flex:1">
          <input type="text" name="color_name[]" value="${name}" placeholder="Colour name (e.g. Midnight)"
                 class="w-full px-3 py-2 rounded-lg bg-gray-900 text-white border border-gray-600 text-sm">
        </div>
        <div style="flex:1.5">
          <input type="url" name="color_img[]" value="${img}" placeholder="Image URL (optional)"
                 class="w-full px-3 py-2 rounded-lg bg-gray-900 text-white border border-gray-600 text-sm">
        </div>
        <label style="display:flex;align-items:center;gap:4px;font-size:12px;white-space:nowrap">
          <input type="checkbox" name="color_selected[]" value="${colorCount}" ${isDefault?'checked':''} style="accent-color:#2874f0"> Default
        </label>
        <button type="button" onclick="document.getElementById('${id}').remove()" class="remove-btn">✕</button>
      `;
      document.getElementById('colorVariants').appendChild(div);
    }

    function addStorageRow(name='', isDefault=false) {
      storageCount++;
      const id = 'storage_' + storageCount;
      const div = document.createElement('div');
      div.className = 'variant-row';
      div.id = id;
      div.innerHTML = `
        <div style="flex:1">
          <input type="text" name="storage_option[]" value="${name}" placeholder="e.g. 128 GB or 8 GB + 128 GB"
                 class="w-full px-3 py-2 rounded-lg bg-gray-900 text-white border border-gray-600 text-sm">
        </div>
        <label style="display:flex;align-items:center;gap:4px;font-size:12px;white-space:nowrap">
          <input type="checkbox" name="storage_selected[]" value="${storageCount}" ${isDefault?'checked':''} style="accent-color:#2874f0"> Default
        </label>
        <button type="button" onclick="document.getElementById('${id}').remove()" class="remove-btn">✕</button>
      `;
      document.getElementById('storageVariants').appendChild(div);
    }

    // Pre-fill existing variants
    const existingColors = <?= json_encode($existingColors) ?>;
    const existingStorage = <?= json_encode($existingStorage) ?>;

    existingColors.forEach(function(c, i) {
      addColorRow(c.name || '', c.img || '', c.selected || i===0);
    });
    existingStorage.forEach(function(s, i) {
      addStorageRow(s.name || '', s.selected || i===0);
    });
  </script>
</body>
</html>
