<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
function kirb_footer_admin() {
    // echo 'Powered By: Keyideas Infotech Pvt. Ltd.';
    echo '';
}
add_filter('admin_footer_text', 'kirb_footer_admin');

function kirb_load() {
    if (!wp_style_is('kirb-base-style', 'registered') || !wp_style_is('kirb-base-style', 'enqueued')) {
        wp_enqueue_style('kirb-base-style', KIRB_PLUGIN_DIR . '/assets/kirb-base.css', array(), KIRB_VERSION, 'all');
    }

    $primary_color = sanitize_hex_color(kirbGetMeta('_setting_primary_color'));
    $accent_color = sanitize_hex_color(kirbGetMeta('_setting_accent_color'));

    $primary_color_components = implode(",", kirbHexToRgb($primary_color));

    $primary_text_color = sanitize_hex_color(kirbGetMeta('_setting_text_primary_color')) ?? '#ffffff';
    $accent_text_color = sanitize_hex_color(kirbGetMeta('_setting_text_accent_color')) ?? '#000000';

    $primary_text_color_filter = esc_html(kirbGetMeta('_setting_text_primary_color_filter')) ?? 'invert(100%) sepia(0%) saturate(7500%) hue-rotate(109deg) brightness(113%) contrast(101%)';
    $accent_text_color_filter = esc_html(kirbGetMeta('_setting_text_accent_color_filter')) ?? 'invert(0%) sepia(0%) saturate(13%) hue-rotate(236deg) brightness(99%) contrast(105%)';

    $primary_color_filter = esc_html(kirbGetMeta('_setting_primary_color_filter'));

    // Prepare the dynamic CSS
    $dynamic_css = "
        :root {
            --kirb-primary-color: {$primary_color};
            --kirb-primary-highlight-bg-color: rgba({$primary_color_components}, 0.1);
            --kirb-accent-color: {$accent_color};
            --kirb-text-primary-color: {$primary_text_color};
            --kirb-text-accent-color: {$accent_text_color};
            --kirb-primary-color-filter: {$primary_color_filter};
            --kirb-text-primary-color-filter: {$primary_text_color_filter};
            --kirb-text-accent-color-filter: {$accent_text_color_filter};
        }
        .kirb_highlight_img_btn, .kirb_highlight_svg {
            filter: {$primary_color_filter} !important;
        }
    ";

    // Add the dynamic CSS
    wp_add_inline_style('kirb-base-style', $dynamic_css);
}

function kirb_check_and_enqueue_styles() {
    global $post;
    if (isset($post->post_content) && (has_shortcode($post->post_content, 'KIRB-RingBuilder-Listing') || has_shortcode($post->post_content, 'KIRB-RingBuilder-DetailPage') || has_shortcode($post->post_content, 'KIRB-RingBuilder-BYORPage'))) {
        include_once('ui/styles_inc.php');
        include_once('ui/libs_inc.php');
    }
}
add_action('wp_enqueue_scripts', 'kirb_check_and_enqueue_styles');

function kirb_listing_shortcode($props) {
    if(!is_admin()) {
        if(!isset($props['category'])) {
            return "Please provide category in shortcode. Example: [KIRB-RingBuilder-Listing category='NATURAL']";
        }else if(!in_array($props['category'], KIRB_ALL_CATEGORIES)) {
            return "Invalid category provided. Valid categories are: " . implode(', ', KIRB_ALL_CATEGORIES);
        }

        $current_category = $props['category'];
        $kirb_catg_control = json_decode(kirbGetMeta('_setting_catg_control'), true);

        if(isset($kirb_catg_control[$current_category]) && !$kirb_catg_control[$current_category]) {
            if(!wp_script_is('kirb-base-script', 'registered') || !wp_script_is('kirb-base-script', 'enqueued')) {
                wp_enqueue_script('kirb-base-script', KIRB_PLUGIN_DIR . '/assets/kirb-base.js', array('jquery'), KIRB_VERSION, true);
            }
            
            $site_url = esc_url(site_url());
            $inline_js = "window.location.href = '{$site_url}';";

            // Add the inline script
            wp_add_inline_script('kirb-base-script', $inline_js);
        }else{
            kirb_load();
            // Enqueue jQuery UI
            wp_enqueue_script('jquery-ui-slider');
            // Enqueue jQuery UI styles
            wp_enqueue_style('kirb-jquery-ui', KIRB_PLUGIN_DIR . '/assets/libs/jquery-ui.min.css', array(), '1.11.2', 'all');

            // Numeral Languages
            wp_enqueue_script('kirb-numeral-lang', KIRB_PLUGIN_DIR . '/assets/libs/numeral-languages.js', array(), '1.0.0', false);
            
            // Numeral JS
            wp_enqueue_script('kirb-numeral-js', KIRB_PLUGIN_DIR . '/assets/libs/numeral.min.js', array(), '2.0.6', false);

            // Enqueue custom styles
            kirb_sideload_css('listing');

            ob_start();
            include_once('ui/diamond-listing.php');
            $content = ob_get_clean();
            $content = "<section class=\"kirb_main_section\">" . $content . "</section>";
            return $content;
        }
    }
}

function kirb_Detailpage_shortcode($props){
    if(!is_admin()) {
        kirb_load();
        // Enqueue custom styles
        kirb_sideload_css('detail');
        include_once('ui/diamond_structures.php'); // Only required for diamond detail page
        ob_start();
        include_once('ui/diamond-detail-page.php');
        $content = ob_get_clean();
        $content = "<section class=\"kirb_main_section\">" . $content . "</section>";
        return $content;
    }
}

function kirb_BYORpage_shortcode($props){
    if(!is_admin()) {
        kirb_load();
        ob_start();
        include_once('ui/byor-review-page.php');
        $content = ob_get_clean();
        $content = "<section class=\"kirb_main_section\">" . $content . "</section>";
        return $content;
    }
}

// register shortcode
add_shortcode('KIRB-RingBuilder-Listing', 'kirb_listing_shortcode');
add_shortcode('KIRB-RingBuilder-DetailPage', 'kirb_Detailpage_shortcode');
add_shortcode('KIRB-RingBuilder-BYORPage', 'kirb_BYORpage_shortcode');
add_shortcode('KIRB-RingBuilder-BYORStrip', 'kirb_byor_header_on_category_page_short');
add_shortcode('KIRB-RingBuilder-SettingButton', 'kirb_byor_setting_button_code');

// Add rewrite rule for detail page
function kirb_custom_init_event() {
    // get page id of detail page
    $kirb_page_ids = json_decode(kirbGetMeta("_page_ids"), true);

    if(!is_null($kirb_page_ids)) {

        $pages = array('diamond-detail', 'loose-diamonds', 'gemstone-diamonds', 'lab-diamonds', 'color-diamonds','byor-review');

        foreach($pages as $page) {
            $page_id = $kirb_page_ids[$page];
            $page_slug = get_post_field( 'post_name', $page_id );
            add_rewrite_rule('^'.$page_slug.'/([^/]*)/?', 'index.php?page_id='.$page_id.'&kirb_param=$matches[1]', 'top');
        }
    }
}
add_action('init', 'kirb_custom_init_event', 10, 0);


add_filter( 'query_vars', 'kirb_rewrite_filter' );
function kirb_rewrite_filter( $query_vars ){
    $query_vars[] = 'kirb_param';
    return $query_vars;
}

add_action('template_redirect', 'kirb_diamond_redirect_product_to_detail_page');

function kirb_diamond_redirect_product_to_detail_page() {
    $current_url_path = isset($_SERVER['REQUEST_URI']) ? wp_parse_url(sanitize_url(wp_unslash($_SERVER['REQUEST_URI'])), PHP_URL_PATH) : "";
    if(str_contains($current_url_path, '/product/')) {
        $current_url_path_components = explode('/', $current_url_path);
        $product_slug = $current_url_path_components[count($current_url_path_components)-2];
        if(str_contains($product_slug, '-')) {
            $product_slug_components = explode('-', $product_slug);
            $uid = end($product_slug_components);
            $is_diamond = kirb_isValidMongoDBObjectId($uid);
            if(!$is_diamond) {
                // Check if the second last component is a valid uid
                // This is for the case when the product slug modified by the wordpress automatically
                $uid = $product_slug_components[count($product_slug_components)-2];
                $is_diamond = kirb_isValidMongoDBObjectId($uid);
            }
            if ($is_diamond) {
                $kirb_page_ids = json_decode(kirbGetMeta("_page_ids"), true);
                $page_id = $kirb_page_ids['diamond-detail'];
                $redirect_url = get_permalink($page_id) . '/' . $product_slug . '/';
                wp_redirect($redirect_url, 301);
                exit;
            }
        }
    }
}


add_action('kirb_clean_event', 'kirb_garbage_cleaner');
if (!wp_next_scheduled('kirb_clean_event')) {
    wp_schedule_event(time(), 'twicedaily', 'kirb_clean_event');
}

////////////// OLD PRESERVED CODE /////////////////
// function kirb_byor_setting_button_code() { 

//     if(!kirbGetMeta('_setting_ring_setting_catg')) {
//         return '';
//     }

//     global $product;

//     if(!$product) {
//         return '';
//     }

//     $product_cat_slugs = kirb_get_parent_slug($product);
//     $setting_cat_slug = kirbGetMeta('_setting_ring_setting_catg');

//     // Get all attributes of the product
//     $attributes = $product->get_attributes();
//     $attribute_keys = array_keys(json_decode(wp_json_encode($attributes), true));

//     if (is_product() && (in_array($setting_cat_slug, $product_cat_slugs))) {
//         if($product->is_type('variable')) {
//             $extra_code = "
//                 kirb_variation_id = document.querySelector('input.variation_id').value;
//                 if(kirb_variation_id.length == 0 || kirb_variation_id == '0') {
//                     alert('Please select a product variation...');
//                     return;
//                 }
//             ";
//         }else{
//             $extra_code = "variation_id = 0;";
//         }

//         $setting_type = 'ring';

//         $byor_data = kirb_getByorDataForCurrentUser();
//         $is_diamond_selected = '0';
//         if($byor_data && isset($byor_data['diamond_uid']) && !empty($byor_data['diamond_uid']) && $byor_data['diamond_uid'] != '0') {
//             $is_diamond_selected = '1';
//         }

//         $kirb_product_id = $product->get_id();
//         $all_btns = "";
//         $catg_lbls = array(
//             'NATURAL' => 'Natural Diamond',
//             'LAB CREATED' => 'Lab Diamond',
//             'GEMSTONE' => 'Center Gemstone',
//             'COLORED DIAMONDS' => 'Colored Diamond'
//         );
//         $catg_control = json_decode(kirbGetMeta('_setting_catg_control'), true);
//         $order = [0, 1, 3, 2];
//         foreach($order as $index) {
//             $catg = KIRB_ALL_CATEGORIES[$index]; // Get the category based on the index
//             if($catg_control[$catg]) {
//                 $all_btns .= '<div class="kirb-btn-catg" data-catg="'.$catg.'">Add a '.ucwords(strtolower($catg_lbls[$catg])).'</div>';
//             }
//         }
//         $dialog_code = '
//             <div id="chooseSettingDialog" class="kirb-modal-nextstep">
//                 <div class="kirb-modal-content">
//                     <div>
//                         <div class="popup-heading">'.esc_html('Select a Center Stone option').'</div>
//                         <span class="close" id="kirb_modal_close">&times;</span>
//                     </div>
//                     <div class="kirb-modal-button">
//                         '.$all_btns.'
//                     </div>
//                 </div>
//             </div>
//         ';
//         $btn_code = '
//             <button class="kirb-btn kirb_byor_select_ring my-2">'.esc_html('Choose This Setting').'</button>
//         ';
//         $script_code = "
//             <script>
//                 try{
//                     $ = jQuery;
//                 } catch(err) {}
//                 let kirb_product_id = $kirb_product_id;
//                 let kirb_attribute_keys = JSON.parse(`".wp_json_encode($attribute_keys)."`);
//                 let kirb_variation_id = 0;
//                 let is_diamond_selected = $is_diamond_selected == '1' ? true : false;
//                 let kirb_ring_attributes = {};

//                 function selectWcrbByorSetting(catg) {
//                     toggle_kirb_loader(true);
//                     kirb_attribute_keys.forEach((key) => {
//                         let val = $('[name=\"attribute_'+key+'\"]').val() ?? '';
//                         kirb_ring_attributes['attribute_'+key] = val;
//                     });

//                     $.get('".admin_url('admin-ajax.php')."', {
//                         action: 'kirb_add_to_byor',
//                         product_id: kirb_product_id,
//                         variation_id: kirb_variation_id,
//                         type: 'ring',
//                         setting_type: '".$setting_type."',
//                         catg: catg,
//                         attributes: JSON.stringify(kirb_ring_attributes),
//                         nonce: '".wp_create_nonce('kirb_ajax_nonce')."'
//                     }, (resp)=>{
//                         if(resp.status == 'success') {
//                             window.location.href = resp.redirect_url;
//                         }else{
//                             toggle_kirb_loader(false);
//                         }
//                     });
//                 }

//                 $(document).ready(function(){
//                     let kirb_byor_btn = document.querySelector('.kirb_byor_select_ring');
//                     kirb_byor_btn.addEventListener('click', function(e) {
//                         e.preventDefault();
//                         $extra_code
//                         if(is_diamond_selected) {
//                             selectWcrbByorSetting('');
//                         }else{
//                             $('#chooseSettingDialog').css('display', 'flex');
//                         }
//                     });
//                     $('#kirb_modal_close').click(()=>{
//                         $('#chooseSettingDialog').css('display', 'none');
//                     });
//                     $('.kirb-btn-catg').click(function(){
//                         selectWcrbByorSetting($(this).data('catg'));
//                     });
//                 });
//             </script>
//         ";
        
//         wp_enqueue_style('kirb-custom-eng-script', KIRB_PLUGIN_DIR . '/assets/setting_style.min.css',  array(), KIRB_VERSION_CONTROL['setting_styles_css'], 'all');

//         kirb_sideload_css('setting');

//         return $btn_code . $dialog_code . $script_code;
//         // $allowed_tags = [
//         //     'button' => [
//         //         'class' => [],
//         //     ],
//         //     'div' => [
//         //         'id' => [],
//         //         'class' => [],
//         //         'data-catg' => [],
//         //     ],
//         //     'span' => [
//         //         'id' => [],
//         //         'class' => [],
//         //     ],
//         // ];
//         // return wp_kses($btn_code . $dialog_code, $allowed_tags);
//     }
// };
////////////// OLD PRESERVED CODE /////////////////


function kirb_byor_setting_button_code() {
    if ( ! kirbGetMeta('_setting_ring_setting_catg') ) return '';
    global $product;
    if ( ! $product ) return '';

    $product_cat_slugs = kirb_get_parent_slug($product);
    $setting_cat_slug  = kirbGetMeta('_setting_ring_setting_catg');

    // bail if not in the right context
    if ( ! ( is_product() && in_array($setting_cat_slug, $product_cat_slugs, true) ) ) {
        return '';
    }

    // variable vs simple
    if ( $product->is_type('variable') ) {
        $extra_code_js = "
            kirb_variation_id = document.querySelector('input.variation_id')?.value || '';
            if (!kirb_variation_id || kirb_variation_id === '0') {
                alert('Please select a product variation...');
                return;
            }
        ";
    } else {
        $extra_code_js = "kirb_variation_id = 0;";
    }

    // data used in JS
    $attributes       = $product->get_attributes();
    $attribute_keys   = array_keys( json_decode( wp_json_encode( $attributes ), true ) );
    $attribute_keysjs = wp_json_encode( $attribute_keys );
    $kirb_product_id  = (int) $product->get_id();

    $byor_data           = kirb_getByorDataForCurrentUser();
    // $is_diamond_selected = ( $byor_data && ! empty($byor_data['diamond_uid']) && $byor_data['diamond_uid'] !== '0' ) ? 'true' : 'false';

    $is_diamond_selected = '0';
    if($byor_data && isset($byor_data['diamond_uid']) && !empty($byor_data['diamond_uid']) && $byor_data['diamond_uid'] != '0') {
        $is_diamond_selected = '1';
    }

    // category buttons (from your logic)
    $catg_lbls = [
        'NATURAL'         => 'Natural Diamond',
        'LAB CREATED'     => 'Lab Diamond',
        'GEMSTONE'        => 'Center Gemstone',
        'COLORED DIAMONDS'=> 'Colored Diamond',
    ];
    $catg_control = json_decode( kirbGetMeta('_setting_catg_control'), true );
    $order        = [0,1,3,2];
    $all_btns     = '';
    foreach ($order as $index) {
        $catg = KIRB_ALL_CATEGORIES[$index];
        if (!empty($catg_control[$catg])) {
            $all_btns .= '<div class="kirb-btn-catg" data-catg="' . esc_attr($catg) . '">Add a ' . esc_html( ucwords(strtolower($catg_lbls[$catg])) ) . '</div>';
        }
    }

    $btn_code = '<button class="kirb-btn kirb_byor_select_ring my-2">' . esc_html('Choose This Setting') . '</button>';

    $dialog_code = '
        <div id="chooseSettingDialog" class="kirb-modal-nextstep">
            <div class="kirb-modal-content">
                <div>
                    <div class="popup-heading">'.esc_html('Select a Center Stone option').'</div>
                    <span class="close" id="kirb_modal_close">&times;</span>
                </div>
                <div class="kirb-modal-button">' . $all_btns . '</div>
            </div>
        </div>
    ';

    $inline_js = "
    jQuery(function($){
        var kirb_product_id       = $kirb_product_id;
        let kirb_attribute_keys   = JSON.parse(`".wp_json_encode($attribute_keys)."`);
        var kirb_variation_id     = 0;
        let is_diamond_selected   = $is_diamond_selected == '1' ? true : false;
        var kirb_ring_attributes  = {};

        function selectWcrbByorSetting(catg) {
            if (typeof toggle_kirb_loader === 'function') toggle_kirb_loader(true);
            kirb_ring_attributes = {};
            kirb_attribute_keys.forEach(function(key){
            var val = $('[name=\"attribute_'+key+'\"]').val() || '';
            kirb_ring_attributes['attribute_'+key] = val;
            });
            $.get('".admin_url('admin-ajax.php')."', {
                action: 'kirb_add_to_byor',
                product_id: kirb_product_id,
                variation_id: kirb_variation_id,
                type: 'ring',
                setting_type: 'ring',
                catg: catg || '',
                attributes: JSON.stringify(kirb_ring_attributes),
                nonce: '".wp_create_nonce('kirb_ajax_nonce')."'
            }).done(function(resp){
                if (resp && resp.status === 'success' && resp.redirect_url) {
                    window.location.href = resp.redirect_url;
                } else {
                    if (typeof toggle_kirb_loader === 'function') toggle_kirb_loader(false);
                }
            }).fail(function() {
                if (typeof toggle_kirb_loader === 'function') toggle_kirb_loader(false);
            });
        }

        $(document).on('click', '.kirb_byor_select_ring', function(e){
            e.preventDefault();
            $extra_code_js
            if (is_diamond_selected) {
            selectWcrbByorSetting('');
            } else {
            $('#chooseSettingDialog').css('display','flex');
            }
        });

        $(document).on('click', '#kirb_modal_close', function(){
            $('#chooseSettingDialog').css('display','none');
        });

        $(document).on('click', '.kirb-btn-catg', function(){
            selectWcrbByorSetting($(this).data('catg'));
        });
    });
    ";

    // ensure jQuery and output our inline script in footer
    wp_enqueue_script('jquery');

    wp_enqueue_style('kirb-custom-eng-script', KIRB_PLUGIN_DIR . '/assets/setting_style.min.css',  array(), KIRB_VERSION_CONTROL['setting_styles_css'], 'all');

    // create a lightweight handle to attach inline code
    if ( ! wp_script_is('kirb-byor-inline', 'registered') ) {
        wp_register_script('kirb-byor-inline', '', ['jquery'], KIRB_VERSION_CONTROL['setting_styles_css'] ?? false, true);
    }
    wp_enqueue_script('kirb-byor-inline');
    wp_add_inline_script('kirb-byor-inline', $inline_js, 'after');

    // finally return sanitized HTML
    return $btn_code . $dialog_code;
}


add_action( 'woocommerce_before_add_to_cart_button', 'kirb_add_byor_button' );
function kirb_add_byor_button() { 
    $addons_data = json_decode(kirbGetMeta('_setting_addon_data'), true);
    if($addons_data['choose_this_setting']['enabled']) {
        $allowed_tags = [
            'div' => [
                'id'      => true,
                'class'   => true,
                'style'   => true,
                'data-*'  => true,
                'aria-*'  => true,
                'role'    => true,
            ],
            'span' => [
                'id'      => true,
                'class'   => true,
                'style'   => true,
                'data-*'  => true,
                'aria-*'  => true,
                'title'   => true,
                'role'    => true,
            ],
            'button' => [
                'id'      => true,
                'class'   => true,
                'style'   => true,
                'type'    => true,
                'name'    => true,
                'value'   => true,
                'disabled'=> true,
                'data-*'  => true,
                'aria-*'  => true,
            ],
            'br' => [],
        ];
        echo wp_kses(kirb_byor_setting_button_code(), $allowed_tags, ['http','https']);
    }
}


// add_action('woocommerce_before_main_content', 'kirb_byor_header_on_product_page', 10);
add_action('woocommerce_before_single_product', 'kirb_byor_header_on_product_page', 5);
add_action('woocommerce_before_shop_loop', 'kirb_byor_header_on_category_page', 10);

function kirb_byor_header_on_product_page() {
    if (is_product()) {
        $product = wc_get_product(get_the_ID());
        $product_cat_slugs = kirb_get_parent_slug($product);
        echo wp_kses_post(kirb_display_byor_strip($product_cat_slugs));
    }
}

function kirb_byor_header_on_category_page_short($attr) {
    if (is_product_category()) {
        $product_cat = get_queried_object();
        if (isset($product_cat->parent) && $product_cat->parent != 0) {
            $product_cat = get_term($product_cat->parent); // Get the parent term object
        } 
        $product_cat_slug = array($product_cat->slug) ?? array('');
        return kirb_display_byor_strip($product_cat_slug);    
    }else if(isset($attr['category']) && $attr['category']!= '') {
        return kirb_display_byor_strip(array($attr['category']));
    }
    
}

function kirb_byor_header_on_category_page() {
    if (is_product_category()) {
        $product_cat = get_queried_object();
        $product_cat_slug = array($product_cat->slug) ?? array('');
        echo wp_kses_post(kirb_display_byor_strip($product_cat_slug));
    }
}

function kirb_display_byor_strip($product_cat_slugs) {
    $setting_cat_slug = kirbGetMeta('_setting_ring_setting_catg');

    if (in_array($setting_cat_slug, $product_cat_slugs)) {
        return kirb_byor_strip_code();
    }
}

function kirb_byor_strip_code() {
    kirb_load();
    ob_start();
    include_once('ui/libs_inc.php');
    include_once('ui/common.php');
    kirbLoadByorStrip();
    return ob_get_clean();
}



function kirb_plugin_uninstall_email() {
    $user_info = kirbGetMeta('_user_info');
    if($user_info) {
        $url = KIRB_ENDPOINT_URL . "/send-woo-mails";
        $shop_name = kirbGetMeta("_shop_name");
        $token = kirbGetMeta("_store_token");
        $user_info = json_decode($user_info, true);
        wp_remote_post($url, array(
            'method' => 'POST',
            'timeout' => 30,
            'headers' => [
                'shop'  => $shop_name,
                'token' => $token
            ],
            'body' => wp_json_encode(array(
                "storeOwner" => $user_info['name'],
                "subject"=> "Plugin Uninstall",
                "company"=> $user_info['company_name'],
                "ownerEmail"=> $user_info['email']
            )),
        ));
    }
}

add_action('before_delete_post', 'kirb_track_deleted_products');
add_action('shutdown', 'kirb_handle_bulk_product_deletion_batch');

$kirb_deleted_products = [];
function kirb_track_deleted_products($post_id) {
    global $kirb_deleted_products;
    if (get_post_type($post_id) === 'product') {
        $kirb_deleted_products[] = $post_id;
    }
}

function kirb_handle_bulk_product_deletion_batch() {
    global $kirb_deleted_products;
    if (!empty($kirb_deleted_products)) {
        kirb_garbage_cleaner();
        $kirb_deleted_products = [];
    }
}

add_filter('woocommerce_cart_item_name', 'kirb_add_sku_to_cart_item', 10, 3);
function kirb_add_sku_to_cart_item($name, $cart_item, $cart_item_key) {
    $product = $cart_item['data'];

    if (isset($cart_item['kirb_custom_data']) || has_term('diamonds', 'product_cat', $product->get_id())) {
        $sku = $product->get_sku();
        
        if ($sku) {
            $name .= '<div class="kirb-cart-item-sku">SKU: ' . esc_html($sku) . '</div>';
        }

        // Add ring size dropdown
        if(isset($cart_item['kirb_custom_data']) && isset($cart_item['kirb_custom_data']['type']) && $cart_item['kirb_custom_data']['type'] == 'byor_setting') {
            $addons_data = json_decode(kirbGetMeta('_setting_addon_data'), true);
            $enable_cart_sizer = kirb_get_config('enable_cart_ring_sizer');
            if($enable_cart_sizer && $addons_data['ring_size']['enabled']) {
                $ring_size = $cart_item['kirb_custom_data']['ring_size'];
                $ring_sizes_array = kirb_getRingSizeList();
                $name .= '<div class="kirb-cart-item-ring-size" style="display:flex;align-items:center;gap:8px;margin:10px 0px;">Select Size: <select name="ring_size" class="kirb-ring-size-dropdown" id="' . esc_attr($cart_item_key) . '" style="padding:5px;height:30px;width:40%;">';
                $pre_selected = "";
                foreach ($ring_sizes_array as $size) {
                    $selected = ($size == $ring_size) ? 'selected' : '';
                    $pre_selected = ($size == $ring_size) ? $size : $pre_selected;
                    $name .= '<option value="' . esc_attr($size) . '" ' . $selected . '>' . esc_html($size) . '</option>';
                }
                $name .= '<option value="' . esc_attr("I don't know") . '"  '.(empty($pre_selected)?'selected':'').'>' . esc_html("I don't know") . '</option>';
                $name .= '</select></div>';
            }
        }
    }
    
    return $name;
}

add_action('wp_footer', 'kirb_ring_size_update_script');
function kirb_ring_size_update_script() {
    if (is_cart()) {
        $addons_data = json_decode(kirbGetMeta('_setting_addon_data'), true);
        if($addons_data['ring_size']['enabled']) {
            $script_code = '
                <script>
                    jQuery(document).ready(function($) {
                        $(".kirb-ring-size-dropdown").change(function() {
                            var cartItemKey = $(this).attr("id");
                            var newSize = $(this).val();
                            var loader = $("<div class=\'kirb-loader\'>Please Wait...</div>");
                            var selectField = $(this);
                            selectField.prop("disabled", true);
                            $(this).parent().append(loader);
                            $.ajax({
                                url: "' . admin_url('admin-ajax.php') . '",
                                type: "POST",
                                data: {
                                    action: "kirb_update_ring_size",
                                    cart_item_key: cartItemKey,
                                    ring_size: newSize,
                                    nonce: "' . wp_create_nonce('kirb_update_ring_size_nonce') . '"
                                },
                                success: function(response) {                            
                                    if(response.success) {
                                        location.reload();
                                    } else {
                                        loader.remove();
                                        selectField.prop("disabled", false);
                                    }
                                },
                                error: function(xhr, status, error) {
                                    loader.remove();
                                    selectField.prop("disabled", false);
                                    console.log(error);
                                }
                            });
                        });
                    });
                </script>
            ';
            echo wp_kses_post($script_code);
            // TEMP - NOT WORKING (Enabled for free version only)
            // if(!wp_script_is('kirb-base-script', 'registered') || !wp_script_is('kirb-base-script', 'enqueued')) {
            //     wp_enqueue_script('kirb-base-script', KIRB_PLUGIN_DIR . '/assets/kirb-base.js');
            // }
            // Add the inline script
            // wp_add_inline_script('kirb-base-script', $script_code);
        }
    }
}

function kirb_rewrite_page_title($title, $id) {
    if (is_admin()) {
        return $title;
    }

    // Check if the title is being used in the navigation menu
    global $post;
    if (!isset($post) || $post->ID != $id) {
        return $title;
    }
    if (!in_the_loop() || !current_filter() == 'the_title') {
        return $title;
    }

    $kirb_page_ids = json_decode(kirbGetMeta("_page_ids"), true);
    $all_page_ids = array();

    if (is_array($kirb_page_ids)) {
        $pages = array('loose-diamonds', 'gemstone-diamonds', 'lab-diamonds', 'color-diamonds');
        $all_page_ids = array_map(function($page) use ($kirb_page_ids) {
            return $kirb_page_ids[$page];
        }, $pages);
    }

    if (in_array($id, $all_page_ids)) {
        $url_shape_preset = get_query_var('kirb_param');
        $shape_slug_config = kirb_get_config("listing_shape_slugs");
        if($shape_slug_config && isset($shape_slug_config[$url_shape_preset])) {
            $title = esc_html(ucfirst($shape_slug_config[$url_shape_preset])) . " " . $title;
        }
    }

    return $title;
}
add_filter('the_title', 'kirb_rewrite_page_title', 10, 2);

// Register lifecycle hooks using one handler
register_activation_hook(KIRB_HOME_FILE, 'kirb_plugin_activate_handler');
register_deactivation_hook(KIRB_HOME_FILE, 'kirb_plugin_deactivate_handler');
register_uninstall_hook(KIRB_HOME_FILE, 'kirb_plugin_uninstall_handler');

function kirb_plugin_activate_handler() {
    kirb_plugin_lifecycle_handler('activate');
}

function kirb_plugin_deactivate_handler() {
    kirb_plugin_lifecycle_handler('deactivate');
}

function kirb_plugin_uninstall_handler() {
    kirb_plugin_lifecycle_handler('uninstall');
}

/**
 * Unified plugin lifecycle handler.
 *
 * @param string $mode 'activate' | 'deactivate' | 'uninstall'
 */
function kirb_plugin_lifecycle_handler($mode) {
    switch ($mode) {
        case 'activate':
            if (!is_plugin_active( 'woocommerce/woocommerce.php')) {
                deactivate_plugins(plugin_basename(KIRB_HOME_FILE));
                wp_die( 'Sorry, but this plugin requires WooCommerce. Please install and activate WooCommerce to use this plugin.' );
            }else{
                kirb_set_pages_status('publish');
                include_once('admin/plugin_pre_activation_hook.php');
            }
            if ( function_exists('flush_rewrite_rules') ) {
                flush_rewrite_rules();
            }
            break;

        case 'deactivate':
            // Draft sample products and tag them for restoration
            kirb_set_pages_status('draft');
            break;

        case 'uninstall':
            // Delete published sample products and previously drafted ones
            kirb_plugin_uninstall_email();
            break;
    }
}

add_action('wp_head', function () {
    $diamonds_catg_array = array('kirb-diamonds', 'kirb-lab-diamonds', 'kirb-loose-diamonds', 'kirb-gemstone-diamonds', 'kirb-color-diamonds');

    if (is_product()) {
        $product = wc_get_product(get_the_ID());
        $product_cat_slugs = kirb_get_parent_slug($product);
        if(count(array_intersect($diamonds_catg_array, $product_cat_slugs)) > 0) {
            echo '<meta name="robots" content="noindex, nofollow">';
        }
    }else if(is_product_category()) {
        $term = get_queried_object();
        if ($term && in_array($term->slug, $diamonds_catg_array, true)) {
            echo '<meta name="robots" content="noindex, nofollow">';
        }
    }else{
        $kirb_page_ids = array_values(json_decode(kirbGetMeta("_page_ids"), true));
        if (is_page($kirb_page_ids)) {
            echo '<meta name="robots" content="noindex, nofollow">';
        }
    }        
});


add_action('plugins_loaded', function () {
    $locale  = determine_locale();
    $mofile  = plugin_dir_path(__FILE__) . 'translations/diamond-ring-builder-jewelry-' . $locale . '.mo';
    if (file_exists($mofile)) {
        load_textdomain('diamond-ring-builder-jewelry', $mofile);
    }
});


add_filter('wp_kses_allowed_html', function ($tags, $context) {
    if ($context !== 'kirb_ui') return $tags;

    // start from 'post'
    $allowed = wp_kses_allowed_html('post');

    // helpers to DRY attributes
    $common = [
        'id'      => true,
        'class'   => true,
        'style'   => true,     // still whitelisted via safe_style_css
        'title'   => true,
        'role'    => true,
        'aria-*'  => true,
        'data-*'  => true,     // wildcard for all data-*
    ];

    // inline elements / common blocks
    foreach (['div','span','p','a','i','b','strong','em'] as $t) {
        $allowed[$t] = array_merge($allowed[$t] ?? [], $common);
    }
    // links
    $allowed['a'] = array_merge($allowed['a'] ?? [], [
        'href'    => true,
        'target'  => true,
        'rel'     => true,
    ] + $common);

    // images
    $allowed['img'] = array_merge($allowed['img'] ?? [], [
        'src'       => true,
        'srcset'    => true,
        'sizes'     => true,
        'alt'       => true,
        'width'     => true,
        'height'    => true,
        'loading'   => true,
        'decoding'  => true,
        'onerror'   => true,  // allowed the onerror => true , so that onerror will not get removed by wp.
    ] + $common);

    // iframe (e.g., loupe360)
    $allowed['iframe'] = [
        'src'             => true,
        'width'           => true,
        'height'          => true,
        'title'           => true,
        'loading'         => true,
        'referrerpolicy'  => true,
        'allow'           => true,
        'allowfullscreen' => true,
        'frameborder'     => true,
    ] + $common;

    // table markup for LIST VIEW
    foreach (['table','thead','tbody','tfoot','tr','td','th'] as $t) {
        $allowed[$t] = array_merge($allowed[$t] ?? [], $common);
    }
    $allowed['td']['colspan'] = true;
    $allowed['td']['rowspan'] = true;
    $allowed['th']['scope']   = true;

    // buttons (Choose Diamond etc.)
    $allowed['button'] = [
        'type'     => true,
        'name'     => true,
        'value'    => true,
        'disabled' => true,
    ] + $common;

    // misc
    $allowed['br'] = [];

    return $allowed;
}, 10, 2);

// Widen inline CSS allow-list for style="..."
add_filter('safe_style_css', function ($props) {
    $extra = [
        // layout/visibility
        'display','visibility','opacity','overflow','position','top','right','bottom','left','z-index',
        // sizing
        'width','height','min-width','min-height','max-width','max-height',
        // spacing/border
        'margin','margin-top','margin-right','margin-bottom','margin-left',
        'padding','padding-top','padding-right','padding-bottom','padding-left',
        'border','border-width','border-style','border-color','border-radius','box-shadow',
        // background
        'background','background-color','background-image','background-size','background-position','background-repeat',
        // text
        'color','font','font-size','font-weight','line-height','text-align','text-transform','letter-spacing','white-space',
        // transforms/animation
        'transform','transition','filter','backdrop-filter',
        // media helpers
        'object-fit','object-position','aspect-ratio',
        // flex/grid
        'flex','flex-grow','flex-shrink','flex-basis','align-items','justify-content','gap',
        'grid','grid-template-columns','grid-template-rows','place-items','place-content'
    ];
    return array_values(array_unique(array_merge($props, $extra)));
});

/**
 * Admin Review Notice: Show on plugin dashboard with 30-day snooze on dismiss
 */
function kirb_handle_review_notice_dismiss() {
    if(!is_admin() || !current_user_can('manage_options')) return;

    if(isset($_GET['kirb_dismiss_review']) && wp_unslash(esc_html($_GET['kirb_dismiss_review'])) === '1') {
        if(!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'kirb_dismiss_review')) {
            return;
        }

        update_option('kirb_review_notice_dismissed_at', time());

        // Clean the URL and redirect to avoid repeated actions on refresh
        $redirect = remove_query_arg(array('kirb_dismiss_review','_wpnonce'));
        wp_safe_redirect($redirect);
        exit;
    }
}
add_action('admin_init', 'kirb_handle_review_notice_dismiss');

function kirb_should_show_review_notice() {
    $dismissed_at = intval(get_option('kirb_review_notice_dismissed_at', 0));

    if($dismissed_at > 0) {
        // Show again only after one month
        if((time() - $dismissed_at) < MONTH_IN_SECONDS) {
            return false;
        }
    }
    return true;
}

function kirb_render_review_notice() {
    if(!is_admin() || !current_user_can('manage_options') || !kirb_should_show_review_notice()) return;

    $dismiss_url = wp_nonce_url(add_query_arg('kirb_dismiss_review', '1'), 'kirb_dismiss_review');

    echo '<div class="notice notice-info is-dismissible" style="display:block;">'
        . '<p><strong>' . esc_html__( 'Enjoying Keyideas RingBuilder - Jewelry?', 'diamond-ring-builder-jewelry' ) . '</strong></p>'
        . '<p>' . esc_html__( 'If our plugin helps your store, please consider leaving a 5-star review. Your feedback motivates us and helps others discover the plugin.', 'diamond-ring-builder-jewelry' ) . '</p>'
        . '<p>'
            . '<a class="button button-primary" target="_blank" rel="noopener" href="' . esc_url(KIRB_REVIEW_URL) . '">' . esc_html__('Leave a Review', 'diamond-ring-builder-jewelry' ) . '</a> '
            . '<a class="button" href="' . esc_url($dismiss_url) . '">' . esc_html__('Dismiss for 30 days', 'diamond-ring-builder-jewelry' ) . '</a>'
        . '</p>'
    . '</div>';
}
add_action('admin_notices', 'kirb_render_review_notice');
