<?php
require 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

// Récupération et nettoyage
$nom = trim($_POST['nom_structure'] ?? '');
$email = trim($_POST['email'] ?? '');
$contact = trim($_POST['contact'] ?? '');
$besoins = trim($_POST['besoins_specifiques'] ?? '');

$qte_innovateur = (int)($_POST['qte_innovateur'] ?? 0);
$qte_ong = (int)($_POST['qte_ong'] ?? 0);

// Validation
if (empty($nom) || empty($email) || empty($contact)) {
    die("Erreur : veuillez remplir tous les champs obligatoires.");
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    die("Erreur : email invalide.");
}
if ($qte_innovateur <= 0 && $qte_ong <= 0) {
    die("Erreur : vous devez sélectionner au moins un stand.");
}
if ($qte_innovateur < 0 || $qte_ong < 0 || $qte_innovateur > 10 || $qte_ong > 10) {
    die("Erreur : quantité invalide (max 10 par type).");
}

// Calcul du montant total
$montant = ($qte_innovateur * 80000) + ($qte_ong * 200000);

// Déduire la catégorie principale (optionnel)
$categorie = 'mixte';
if ($qte_innovateur > 0 && $qte_ong == 0) $categorie = 'innovateur';
if ($qte_ong > 0 && $qte_innovateur == 0) $categorie = 'ong';

try {
    // Générer le numéro de facture
    $count = $pdo->query("SELECT COUNT(*) FROM inscriptions")->fetchColumn();
    $numero_seq = str_pad($count + 1, 3, '0', STR_PAD_LEFT);
    $annee = date('Y');
    $numero_facture = "SITAHO-$annee-$numero_seq";

    // Insérer l'inscription avec quantités
    $stmt = $pdo->prepare("
        INSERT INTO inscriptions 
        (nom_structure, email, contact, categorie, qte_innovateur, qte_ong, besoins_specifiques, montant, numero_facture)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $nom, $email, $contact, $categorie, 
        $qte_innovateur, $qte_ong, 
        $besoins, $montant, $numero_facture
    ]);

    $id_inscription = $pdo->lastInsertId();
    header("Location: merci.php?id=" . $id_inscription);
    exit;

} catch (Exception $e) {
    die("Erreur lors de l'inscription : " . htmlspecialchars($e->getMessage()));
}
?>