
/**
 * Passes custom event data (like price and title) to the WooCommerce cart.
 *
 * Add this code using the "Code Snippets" plugin.
 */

// 1. Add custom data to the cart item when the "Buy Now" button is clicked.
add_filter( 'woocommerce_add_cart_item_data', 'add_event_data_to_cart_item', 10, 3 );
function add_event_data_to_cart_item( $cart_item_data, $product_id, $variation_id ) {
    // Check if our custom event ID is in the URL.
    if ( isset( $_REQUEST['event_id'] ) ) {
        $event_id = intval( $_REQUEST['event_id'] );
        $cart_item_data['custom_event_id'] = $event_id;
    }
    return $cart_item_data;
}


// 2. Override the product price in the cart with the event's custom price from ACF.
add_action( 'woocommerce_before_calculate_totals', 'set_event_price_in_cart', 20, 1 );
function set_event_price_in_cart( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    // Loop through each item in the cart.
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // Check if our custom event ID is present.
        if ( isset( $cart_item['custom_event_id'] ) ) {
            $event_id = $cart_item['custom_event_id'];
            
            // Get the 'ticket_price' from the ACF field for that event.
            $event_price = get_field( 'ticket_price', $event_id );

            // If we found a price, set it as the product's price in the cart.
            if ( $event_price ) {
                $cart_item['data']->set_price( $event_price );
            }
        }
    }
}


// 3. Change the product name in the cart to the event's title.
add_filter( 'woocommerce_cart_item_name', 'change_event_name_in_cart', 10, 3 );
function change_event_name_in_cart( $product_name, $cart_item, $cart_item_key ) {
    // Check if our custom event ID is present.
    if ( isset( $cart_item['custom_event_id'] ) ) {
        $event_id = $cart_item['custom_event_id'];
        $event_title = get_the_title( $event_id );
        
        // If we found a title, return it as the new product name.
        if ( $event_title ) {
            return $event_title;
        }
    }
    return $product_name;
}
