/* 
Theme Name: Hello Elementor Child
Theme URI: https://github.com/elementor/hello-theme-child/
Description: Hello Elementor Child is a child theme of Hello Elementor, created by Elementor team
Author: Elementor Team
Author URI: https://elementor.com/
Template: hello-elementor
Version: 2.0.0
Text Domain: hello-elementor-child
License: GNU General Public License v3 or later.
License URI: https://www.gnu.org/licenses/gpl-3.0.html
Tags: flexible-header, custom-colors, custom-menu, custom-logo, editor-style, featured-images, rtl-language-support, threaded-comments, translation-ready
*/

/* Add your custom styles here */
// Rescata al cliente que Eventin manda de vuelta a /eventin-purchase/checkout/
// después de un pago exitoso con Mercado Pago / WooCommerce.
add_action( 'template_redirect', 'zoquital_fix_eventin_post_payment_redirect', 1 );
function zoquital_fix_eventin_post_payment_redirect() {
    // Solo actuar en la ruta de checkout de Eventin
    if ( strpos( $_SERVER['REQUEST_URI'], '/eventin-purchase/checkout' ) === false ) {
        return;
    }

    // Buscar parámetros que delaten un retorno de gateway
    $order_id   = isset( $_GET['order_id'] )   ? absint( $_GET['order_id'] )       : 0;
    $order_key  = isset( $_GET['key'] )        ? sanitize_text_field( $_GET['key'] ) : '';
    $mp_status  = isset( $_GET['status'] )     ? sanitize_text_field( $_GET['status'] ) : '';
    $collection = isset( $_GET['collection_status'] ) ? sanitize_text_field( $_GET['collection_status'] ) : '';

    // Si viene de MP aunque no pase el order_id, intentamos recuperar el último pedido del usuario
    if ( ! $order_id && ( $mp_status || $collection ) && is_user_logged_in() ) {
        $customer_orders = wc_get_orders( array(
            'customer' => get_current_user_id(),
            'limit'    => 1,
            'orderby'  => 'date',
            'order'    => 'DESC',
        ) );
        if ( ! empty( $customer_orders ) ) {
            $order_id = $customer_orders[0]->get_id();
        }
    }

    if ( $order_id ) {
        $order = wc_get_order( $order_id );
        if ( $order ) {
            $url = $order->get_checkout_order_received_url();
            wp_safe_redirect( $url );
            exit;
        }
    }

    // Fallback: si no logramos identificar el pedido pero el cliente pagó,
    // mándalo al menos a "Mis pedidos" para que vea el estatus.
    if ( $mp_status === 'approved' || $collection === 'approved' ) {
        wp_safe_redirect( wc_get_account_endpoint_url( 'orders' ) );
        exit;
    }
}