<?php
session_start();

if (!isset($_SESSION['registration_data'])) {
    header('Location: index.php');
    exit;
}

$data = $_SESSION['registration_data'];
$nom_complet = $data['prenom'] . ' ' . $data['nom'];

if (!isset($data['montant_cadeau']) || empty($data['montant_cadeau'])) {
    header('Location: cancel.php?error=no_amount');
    exit;
}

if ($data['montant_cadeau'] === 'autre') {
    if (!isset($data['montant_personnalise']) || $data['montant_personnalise'] <= 0) {
        header('Location: cancel.php?error=invalid_amount');
        exit;
    }
    $montant_final = (int)$data['montant_personnalise'] * 100;
} else {
    $montant_final = (int)$data['montant_cadeau'] * 100;
}

require_once 'vendor/autoload.php';
\Stripe\Stripe::setApiKey('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');

try {
    $session = \Stripe\Checkout\Session::create([
        'payment_method_types' => ['card', 'bancontact'],
        'line_items' => [[
            'price_data' => [
                'currency' => 'eur',
                'product_data' => [
                    'name' => 'Cadeau pour Izhak - A Sixteen Dream',
                    'description' => 'Contribution de ' . $nom_complet,
                ],
                'unit_amount' => $montant_final,
            ],
            'quantity' => 1,
        ]],
        'mode' => 'payment',
        'success_url' => (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . "/payment_success.php?session_id={CHECKOUT_SESSION_ID}",
        'cancel_url' => (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . "/cancel.php",
        'customer_email' => $data['email'],
        'metadata' => [
            'event' => 'A Sixteen Dream',
            'inscription_id' => $data['id'],
            'nom' => $data['nom'],
            'prenom' => $data['prenom'],
        ],
    ]);
    
    $_SESSION['stripe_session_id'] = $session->id;
    
    header('Location: ' . $session->url);
    exit;
    
} catch (Exception $e) {
    error_log('Erreur Stripe: ' . $e->getMessage());
    header('Location: cancel.php?error=stripe_error');
    exit;
}
?>