<?php
session_start();
require_once 'db.php';

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

$data = $_SESSION['registration_data'];
$intent_id = isset($_GET['intent']) ? $_GET['intent'] : $_SESSION['payment_intent_id'];

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

try {
    $intent = \Stripe\PaymentIntent::retrieve($intent_id);
    
    if ($intent->status === 'succeeded') {
        $stmt = $pdo->prepare("
            UPDATE inscriptions 
            SET payment_status = 'completed', 
                stripe_session_id = ?, 
                payment_date = NOW() 
            WHERE id = ?
        ");
        $stmt->execute([$intent_id, $data['id']]);
        
        $nom_complet = $data['prenom'] . ' ' . $data['nom'];
        $montant = $intent->amount / 100;
        
        $email_subject = "Confirmation - A Sixteen Dream";
        $email_body = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #000; color: #fff; padding: 30px; text-align: center; }
                .content { padding: 30px; background: #f9f9f9; }
                .footer { padding: 20px; text-align: center; font-size: 12px; color: #666; }
                .highlight { color: #000; font-weight: bold; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1 style='margin:0; font-weight: 100; font-size: 32px;'>A Sixteen Dream</h1>
                </div>
                <div class='content'>
                    <h2>Merci {$nom_complet} !</h2>
                    <p>Ton inscription est confirmée et ton cadeau de <span class='highlight'>{$montant} €</span> pour Izhak a été reçu avec succès.</p>
                    
                    <h3>Détails de l'événement :</h3>
                    <p>
                        <strong>Date :</strong> Vendredi 20 Mars 2025<br>
                        <strong>Horaire :</strong> 18h30 - 02h00<br>
                        <strong>Lieu :</strong> Château de la Hulpe - Chaussée de Bruxelles 111, 1310 La Hulpe
                    </p>
                    
                    <p>À très bientôt pour cette soirée exceptionnelle !</p>
                </div>
                <div class='footer'>
                    <p>Présenté par Imators</p>
                </div>
            </div>
        </body>
        </html>
        ";
        
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=utf-8\r\n";
        $headers .= "From: A Sixteen Dream <no-reply@imators.com>\r\n";
        
        mail($data['email'], $email_subject, $email_body, $headers);
        
        $sms_message = "Merci {$data['prenom']} ! Ton inscription pour A Sixteen Dream est confirmée. RDV le 20 Mars 2025 à 18h30 au Château de la Hulpe. - Imators";
        
        $ch = curl_init('https://textbelt.com/text');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
            'phone' => $data['telephone'],
            'message' => $sms_message,
            'key' => '65cc7a4af9b5db94cdbc332fcc2704e7e86604fakMlbReRxuZa89bOISbQ9YIi6G'
        ]));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_exec($ch);
        curl_close($ch);
        
        header('Location: success.php?payment=success');
        exit;
    }
} catch (Exception $e) {
    error_log('Erreur payment success: ' . $e->getMessage());
}

header('Location: cancel.php');
exit;
?>