<?php

add_action('template_redirect', 'h2j_page_intermediaire_vers_checkout');
function h2j_page_intermediaire_vers_checkout() {
    if (is_page('paiement-valide')) { // Slug de ta page intermédiaire
        if (!isset($_GET['user']) || !isset($_GET['montant'])) {
            wp_redirect(home_url('/erreur-paiement'));
            exit;
        }

        $user = sanitize_text_field($_GET['user']);
        $montant = floatval($_GET['montant']);
        $product_id = 24006;

        if ($montant <= 0) {
            wp_redirect(home_url('/erreur-paiement'));
            exit;
        }

        WC()->cart->empty_cart();
        WC()->cart->add_to_cart($product_id, 1, 0, [], [
            'custom_price' => $montant,
            'gf_user_identifiant' => $user,
        ]);

        add_filter('woocommerce_before_calculate_totals', function($cart) {
            foreach ($cart->get_cart() as $item) {
                if (isset($item['custom_price'])) {
                    $item['data']->set_price($item['custom_price']);
                }
            }
        });

        wp_safe_redirect(wc_get_checkout_url());
        exit;
    }
}