<?php
session_start();

// Définir la constante pour le config
define('STRIPE_CONFIG', true);

// Inclure le fichier de configuration
require_once('config.php');

// Déterminer l'environnement (test ou live)
$env = isset($_GET['env']) && $_GET['env'] === 'live' ? 'live' : 'test';

// Initialiser Stripe et obtenir les clés
$stripe_keys = initializeStripe($env);

// Vérifier que les clés sont définies
if (empty($stripe_keys['publishable_key']) || empty($stripe_keys['secret_key'])) {
    die('Erreur: Les clés Stripe ne sont pas configurées correctement.');
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Paiement - 2Me</title>
    <script src="https://js.stripe.com/v3/"></script>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-black min-h-screen flex items-center justify-center p-4">
    <div class="max-w-md w-full space-y-8 bg-gray-900 p-8 rounded-xl shadow-2xl">
        <div class="text-center">
            <h2 class="text-3xl font-extrabold text-white">Paiement 2Me</h2>
            <p class="mt-2 text-gray-400">Effectuez votre paiement en toute sécurité</p>
        </div>

        <!-- Toggle Environnement -->
        <div class="flex justify-end">
            <a href="?env=test" class="<?php echo $env === 'test' ? 'bg-blue-600' : 'bg-gray-700'; ?> px-3 py-1 rounded-l text-white text-sm">Test</a>
            <a href="?env=live" class="<?php echo $env === 'live' ? 'bg-blue-600' : 'bg-gray-700'; ?> px-3 py-1 rounded-r text-white text-sm">Live</a>
        </div>

        <form id="payment-form" class="mt-8 space-y-6">
            <div class="space-y-4">
                <div>
                    <label for="email" class="block text-sm font-medium text-gray-300">
                        Adresse email
                    </label>
                    <input type="email" id="email" name="email" required 
                           class="mt-1 block w-full bg-gray-800 border border-gray-700 rounded-md shadow-sm py-2 px-3 text-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-300">
                        Informations de carte
                    </label>
                    <div id="card-element" class="mt-1 block w-full bg-gray-800 border border-gray-700 rounded-md shadow-sm py-3 px-3">
                        <!-- Stripe Card Element will be inserted here -->
                    </div>
                    <div id="card-errors" class="mt-2 text-sm text-red-500" role="alert"></div>
                </div>
            </div>

            <button type="submit" id="submit-button"
                    class="w-full flex justify-center py-3 px-4 border border-transparent rounded-md shadow-sm text-lg font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
                Payer
            </button>
        </form>
    </div>

    <script>
        // Initialiser Stripe
        const stripe = Stripe('<?php echo $stripe_keys['publishable_key']; ?>');
        const elements = stripe.elements({
            appearance: {
                theme: 'night',
                variables: {
                    colorPrimary: '#3b82f6',
                    colorBackground: '#1f2937',
                    colorText: '#fff',
                    colorDanger: '#dc2626',
                    fontFamily: 'system-ui, -apple-system, sans-serif',
                }
            }
        });

        // Créer l'élément de carte
        const cardElement = elements.create('card');
        cardElement.mount('#card-element');

        // Gérer la soumission du formulaire
        const form = document.getElementById('payment-form');
        const submitButton = document.getElementById('submit-button');

        form.addEventListener('submit', async (event) => {
            event.preventDefault();
            submitButton.disabled = true;
            submitButton.textContent = 'Traitement en cours...';

            const email = document.getElementById('email').value;

            try {
                const {paymentMethod, error} = await stripe.createPaymentMethod({
                    type: 'card',
                    card: cardElement,
                    billing_details: {
                        email: email,
                    },
                });

                if (error) {
                    const errorElement = document.getElementById('card-errors');
                    errorElement.textContent = error.message;
                    submitButton.disabled = false;
                    submitButton.textContent = 'Payer';
                    return;
                }

                // Envoyer le paymentMethod.id au serveur
                const response = await fetch('process-payment.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        payment_method_id: paymentMethod.id,
                        email: email,
                        env: '<?php echo $env; ?>'
                    })
                });

                const result = await response.json();

                if (result.error) {
                    const errorElement = document.getElementById('card-errors');
                    errorElement.textContent = result.error;
                    submitButton.disabled = false;
                    submitButton.textContent = 'Payer';
                } else {
                    // Redirection ou message de succès
                    window.location.href = '/success.php';
                }
            } catch (error) {
                console.error('Error:', error);
                const errorElement = document.getElementById('card-errors');
                errorElement.textContent = 'Une erreur est survenue. Veuillez réessayer.';
                submitButton.disabled = false;
                submitButton.textContent = 'Payer';
            }
        });
    </script>
</body>
</html>