<?php 
    if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
    wp_enqueue_script('kirb-custom-common-script', KIRB_PLUGIN_DIR . '/scripts/common.js',array('jquery'), KIRB_VERSION_CONTROL['common_js'], true);
    global $kirb_site_config;
    $kirb_site_config = kirb_get_config_file();
    $kirb_page_ids = json_decode(kirbGetMeta("_page_ids"), true);
    $kirb_config_byor_strip_reload = kirb_get_config("byor_strip_reload", $kirb_site_config);
    $kirb_config_byor_page_reload = kirb_get_config("byor_page_reload", $kirb_site_config);
    if($kirb_config_byor_page_reload && get_the_ID() == $kirb_page_ids['byor-review']) {
        $kirb_config_byor_strip_reload = false;
    }
    wp_localize_script( 'kirb-custom-common-script', 'KIRB_GLOBALS', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('kirb_ajax_nonce'),
            'byor_strip_reload' => $kirb_config_byor_strip_reload ? 'true':'false',
            'page_id' => get_the_ID(),
            'byor_page_uid' => get_query_var('kirb_param')
        ]
    );

    // ======================= START: BYOR Page Specific JS =======================
    
    if(get_the_ID() == $kirb_page_ids['byor-review'] && $kirb_config_byor_page_reload) { ?>
     <script>
        $(document).ready(function(){
            $.ajax({
                url: '<?php echo esc_url(admin_url('admin-ajax.php'));?>',
                type: "GET",
                data: {
                    action: "kirb_fetch_latest_byor_page",
                    page_id: <?php echo esc_attr(get_the_ID());?>,
                    uid: "<?php echo esc_attr(get_query_var('kirb_param')); ?>"
                },
                cache: false,
                success: function(response) {
                    let js_src = $("#kirb-byor-review-page-js-js").attr('src');
                    $(".kirb_main_section").html(response.html);
                    $("#kirb-byor-review-page-js-js").remove();
                    var script = document.createElement('script');
                    script.src = js_src;
                    script.id = "kirb-byor-review-page-js-js";
                    document.head.appendChild(script);
                }
            });
        });
    </script>
    <?php
    }
    // ======================= END: BYOR Page Specific JS =======================