<?php
    // prevent direct file access
	if( !defined( 'ABSPATH' ) ) exit;
    
    function pixe_wc_order_summary_page_setting($settings){
        $new_settings = array();

        foreach ( $settings as $setting ) {
            $new_settings[] = $setting;

            // Find the right spot to insert after "My account page"
            if ( isset( $setting['id'] ) && 'woocommerce_myaccount_page_id' === $setting['id'] ) {
                $new_settings[] = array(
                    'title'    => esc_html__('Purchase Summary Page', 'pixebuilder'),
                    'desc'     => esc_html__('Page shown after checkout to display purchase summary.', 'pixebuilder'),
                    'id'       => 'woocommerce_order_summary_page_id',
                    'type'     => 'single_select_page',
                    'class'    => 'wc-enhanced-select-nostd',
                    'css'      => 'min-width:300px;',
                    'default'  => '',
                    'desc_tip' => true,
                    'autoload' => false,
                );
            }
        }

        return $new_settings;
    }
    add_filter('woocommerce_get_settings_advanced', 'pixe_wc_order_summary_page_setting');

    function pixe_wc_order_summary_redirect($order_id){
        $page_id = get_option('woocommerce_order_summary_page_id');
        if( empty($page_id) || get_the_ID() == $page_id ) return;

        $order = wc_get_order($order_id);
        if( $order ){
            $url = get_permalink($page_id) . '?order_id=' . $order_id;
            wp_safe_redirect($url);
            exit;
        }
    }
    add_action('woocommerce_thankyou', 'pixe_wc_order_summary_redirect');

    function pixe_wc_order_summary_body_class($classes){
        $page_id = get_option('woocommerce_order_summary_page_id');

        if( $page_id == get_the_ID() ){
            $classes[] = 'woocommerce-purchase-summary';
        }
        return $classes;
    }
    add_filter('body_class', 'pixe_wc_order_summary_body_class');