<?php
if (!isset($ADMIN_SECRET)) { die("Accès interdit"); }

// === Ajouter un produit ===
if (($_GET['action'] ?? '') === 'add' && $_SERVER['REQUEST_METHOD'] === 'POST') {
  $nom = $mysqli->real_escape_string($_POST['nom'] ?? '');
  $description = $mysqli->real_escape_string($_POST['description'] ?? '');
  $categorie_id = (int)($_POST['categorie_id'] ?? 0);

  $mysqli->query("INSERT INTO produits (nom, prix, description, categorie_id)
                  VALUES ('{$nom}', 0, '{$description}', ".($categorie_id?:'NULL').")");
  $pid = $mysqli->insert_id;

  // Upload des fichiers multiples
  uploadMedias($pid, $_FILES['media']);

  // Insertion des prix multiples
  savePrices($pid, $_POST['price_label'] ?? [], $_POST['price_value'] ?? []);

  echo '<div class="alert success">✅ Produit ajouté avec succès.</div>';
}

// === Modifier un produit ===
if (isset($_POST['modifier_produit'])) {
  $pid = (int)$_POST['product_id'];
  $nom = $mysqli->real_escape_string($_POST['nom'] ?? '');
  $description = $mysqli->real_escape_string($_POST['description'] ?? '');
  $categorie_id = (int)($_POST['categorie_id'] ?? 0);

  $mysqli->query("UPDATE produits SET nom='{$nom}', description='{$description}', categorie_id=".($categorie_id?:'NULL')." WHERE id=$pid");

  // Ajout éventuel de nouveaux médias
  uploadMedias($pid, $_FILES['media']);

  // Mettre à jour les prix
  $mysqli->query("DELETE FROM product_prices WHERE product_id=$pid");
  savePrices($pid, $_POST['price_label'] ?? [], $_POST['price_value'] ?? []);

  echo '<div class="alert success">💾 Produit modifié.</div>';
}

// === Supprimer produit ===
if (isset($_GET['del'])) {
  $id = (int)$_GET['del'];
  $medias = $mysqli->query("SELECT * FROM product_media WHERE product_id=$id");
  while ($m = $medias->fetch_assoc()) {
    @unlink(__DIR__."/uploads/".$m['file']);
  }
  $mysqli->query("DELETE FROM produits WHERE id={$id}");
  echo '<div class="alert success">🗑 Produit supprimé.</div>';
}

// === Supprimer média ===
if (isset($_GET['del_media'])) {
  $id = (int)$_GET['del_media'];
  $m = $mysqli->query("SELECT * FROM product_media WHERE id=$id")->fetch_assoc();
  if ($m) {
    @unlink(__DIR__."/uploads/".$m['file']);
    $mysqli->query("DELETE FROM product_media WHERE id=$id");
  }
  echo "<div class='alert success'>Média supprimé</div>";
}

// === Fonctions utilitaires ===
function uploadMedias($pid, $files) {
  global $mysqli;
  if (!empty($files['name'][0])) {
    $uploadDir = __DIR__ . '/uploads';
    if (!is_dir($uploadDir)) { @mkdir($uploadDir, 0775, true); }

    foreach ($files['name'] as $i => $name) {
      $tmp = $files['tmp_name'][$i];
      if ($tmp == "") continue;
      $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
      $file = uniqid().".".$ext;
      move_uploaded_file($tmp, $uploadDir."/".$file);
      $mysqli->query("INSERT INTO product_media (product_id, file) VALUES ($pid, '".$mysqli->real_escape_string($file)."')");
    }
  }
}

function savePrices($pid, $labels, $values) {
  global $mysqli;
  foreach ($labels as $i=>$label) {
    $label = trim($label);
    $price = (float)($values[$i] ?? 0);
    if ($label !== '' && $price > 0) {
      $label = $mysqli->real_escape_string($label);
      $mysqli->query("INSERT INTO product_prices (product_id, label, price) VALUES ($pid, '{$label}', {$price})");
    }
  }
}
?>

<h2>🛒 Gestion des produits</h2>

<!-- Formulaire ajout produit -->
<form method="POST" enctype="multipart/form-data" action="?key=<?= urlencode($ADMIN_SECRET) ?>&page=produits&action=add">
  <input type="text" name="nom" placeholder="Nom du produit" required><br>
  <textarea name="description" placeholder="Description" required></textarea><br>
  <select name="categorie_id">
    <option value="">-- Catégorie --</option>
    <?php
    $catRes = $mysqli->query("SELECT * FROM categories ORDER BY nom ASC");
    while ($cat = $catRes->fetch_assoc()) {
      echo '<option value="'.$cat['id'].'">'.htmlspecialchars($cat['nom']).'</option>';
    }
    ?>
  </select><br>
  <input type="file" name="media[]" multiple accept="image/*,video/*"><br>

  <h3>Prix :</h3>
  <div id="prices">
      <input name="price_label[]" placeholder="Label (ex: 5g)">
      <input name="price_value[]" type="number" step="0.01" placeholder="Prix">
  </div>
  <button type="button" onclick="addPriceRow()">+ Ajouter un prix</button><br><br>

  <button type="submit">Ajouter produit</button>
</form>

<script>
function addPriceRow() {
  let d = document.createElement('div');
  d.innerHTML = `<input name="price_label[]" placeholder="Label (ex: 10g)">
                 <input name="price_value[]" type="number" step="0.01" placeholder="Prix">`;
  document.getElementById('prices').appendChild(d);
}
</script>

<hr>

<ul class="products-list">
<?php
$res = $mysqli->query("
  SELECT p.*, c.nom AS cat_nom 
  FROM produits p 
  LEFT JOIN categories c ON p.categorie_id=c.id 
  ORDER BY p.id DESC
");
while ($p = $res->fetch_assoc()) {
  echo "<li>";
  echo "<div><strong>".htmlspecialchars($p['nom'])."</strong><br>";
  echo "Catégorie: ".htmlspecialchars($p['cat_nom'] ?? 'Aucune')."<br>";
  echo nl2br(htmlspecialchars($p['description']))."</div>";

  // Médias existants
  $m = $mysqli->query("SELECT * FROM product_media WHERE product_id=".$p['id']);
  if ($m && $m->num_rows) {
    echo '<div style="margin-top:8px">';
    while ($med = $m->fetch_assoc()) {
      $url = 'uploads/'.htmlspecialchars($med['file']);
      $ext = strtolower(pathinfo($med['file'], PATHINFO_EXTENSION));
      if (in_array($ext, ['mp4','webm','ogg','mov','m4v'])) {
        echo '<video src="'.$url.'" style="width:120px;border-radius:6px" controls></video>';
      } else {
        echo '<img src="'.$url.'" style="width:120px;border-radius:6px">';
      }
      echo ' <a class="btn-inline danger" href="?key='.$ADMIN_SECRET.'&page=produits&del_media='.$med['id'].'" onclick="return confirm(\'Supprimer ce média ?\')">🗑</a> ';
    }
    echo '</div>';
  }

  // Prix existants
  $prices = $mysqli->query("SELECT * FROM product_prices WHERE product_id=".$p['id']);
  echo '<div style="margin-top:8px"><strong>Prix :</strong><br>';
  while ($pr = $prices->fetch_assoc()) {
    echo htmlspecialchars($pr['label']).' : '.number_format($pr['price'],2,'.',' ').' €<br>';
  }
  echo '</div>';

  // Formulaire modification produit + prix
  echo '<form method="POST" enctype="multipart/form-data" style="margin-top:8px">';
  echo '<input type="hidden" name="product_id" value="'.$p['id'].'">';
  echo '<input type="text" name="nom" value="'.htmlspecialchars($p['nom']).'" required><br>';
  echo '<textarea name="description">'.htmlspecialchars($p['description']).'</textarea><br>';
  echo '<select name="categorie_id">';
  echo '<option value="">-- Catégorie --</option>';
  $catRes = $mysqli->query("SELECT * FROM categories ORDER BY nom ASC");
  while ($cat = $catRes->fetch_assoc()) {
    $sel = ($p['categorie_id'] == $cat['id']) ? 'selected' : '';
    echo '<option value="'.$cat['id'].'" '.$sel.'>'.htmlspecialchars($cat['nom']).'</option>';
  }
  echo '</select><br>';

  // Éditer les prix
  $prices = $mysqli->query("SELECT * FROM product_prices WHERE product_id=".$p['id']);
  echo '<div id="prices-'.$p['id'].'">';
  while ($pr = $prices->fetch_assoc()) {
    echo '<input name="price_label[]" value="'.htmlspecialchars($pr['label']).'" placeholder="Label">';
    echo '<input name="price_value[]" type="number" step="0.01" value="'.htmlspecialchars($pr['price']).'" placeholder="Prix"><br>';
  }
  echo '<input name="price_label[]" placeholder="Nouveau label">';
  echo '<input name="price_value[]" type="number" step="0.01" placeholder="Prix">';
  echo '</div>';

  echo '<input type="file" name="media[]" multiple accept="image/*,video/*"><br>';
  echo '<button type="submit" name="modifier_produit" class="btn-inline">💾 Sauvegarder</button>';
  echo '</form>';

  echo '<a class="btn-inline danger" href="?key='.$ADMIN_SECRET.'&page=produits&del='.$p['id'].'" onclick="return confirm(\'Supprimer ce produit ?\')">Supprimer produit</a>';
  echo "</li><hr>";
}
?>
</ul>
