<?php
if (!defined('ABSPATH')) {exit;}
/* phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.SchemaChange */

include_once('src/'.KRFSAPP_THEME.'/theme-ajax-handler.php');

add_action('wp_ajax_krfs_load_more_prods', 'krfsapp_load_prods');
add_action('wp_ajax_nopriv_krfs_load_more_prods', 'krfsapp_load_prods');
add_action('wp_ajax_krfs_filter_products', 'krfsapp_load_prods');
add_action('wp_ajax_nopriv_krfs_filter_products', 'krfsapp_load_prods');
add_action('wp_ajax_krfs_get_attribute_terms', 'krfsapp_get_attribute_terms');
add_action('wp_ajax_nopriv_krfs_get_attribute_terms', 'krfsapp_get_attribute_terms');

function krfsapp_load_prods() {
    global $krfsapp_minprice, $krfsapp_maxprice;
    if (isset($_GET['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['nonce'])),'krfs_nonce')) {
        $nextpage = isset($_GET['nextpage']) ? sanitize_text_field(wp_unslash($_GET['nextpage'])) : 1;
        $currentcategory = isset($_GET['catg']) ? sanitize_text_field(wp_unslash($_GET['catg'])) : '';
        $filters = array(
            'shape' => isset($_GET['shape']) ? str_replace("shape_","",str_replace("shape_","",sanitize_text_field(wp_unslash($_GET['shape'])))) : '',
            'stone' => isset($_GET['stone']) ? str_replace("sidestone_","",sanitize_text_field(wp_unslash($_GET['stone']))) : '',
            // 'style' => isset($_GET['style']) ? preg_replace('/^(style_|wedmen_)/', '', sanitize_text_field(wp_unslash($_GET['style']))) : '',
            // 'metal' => isset($_GET['metal']) ? str_replace("metal_","",sanitize_text_field(wp_unslash($_GET['metal']))) : '',
            'minprice' => isset($_GET['minprice']) ? floatval(wp_unslash($_GET['minprice'])) : $krfsapp_minprice,
            'maxprice' => isset($_GET['maxprice']) ? floatval(wp_unslash($_GET['maxprice'])) : $krfsapp_maxprice,
            'sort' => isset($_GET['sort']) ? sanitize_text_field(wp_unslash($_GET['sort'])) : '',
            "search" => isset($_GET['search']) ? sanitize_text_field(wp_unslash($_GET['search'])) : '' ,
            "result_set" => isset($_GET['result_set']) ? sanitize_text_field(wp_unslash($_GET['result_set'])) : '' ,
            "home_preview" => isset($_GET['home_preview']) ? sanitize_text_field(wp_unslash($_GET['home_preview'])) : ''
        );

        // for styles array
        if (isset($_GET['style']) && !empty($_GET['style'])) {
            $style_arr = (array) wp_unslash($_GET['style']);
            $style_arr = array_values($style_arr); // formatting indexes
            foreach($style_arr as $style) {
                $filters['style'][] = preg_replace('/^(style_|wedmen_|wedwomen_)/', '', sanitize_text_field($style));
            }
        }

        $filters['style_taxonomy'] = 'pa_krfs_style_attr';

        if(isset($_GET['style'][0]) && !empty($_GET['style'][0])) {
            $first_style = '';
            $style_check_arr = (array) wp_unslash($_GET['style']);
            if (isset($style_check_arr[0])) {
                $first_style = sanitize_text_field($style_check_arr[0]);
            }
            if(str_contains($first_style, 'wedmen_')) {
                $filters['style_taxonomy'] = 'pa_krfs_wed_men_attr';
            } elseif(str_contains($first_style, 'wedwomen_')) {
                $filters['style_taxonomy'] = 'pa_krfs_wed_women_attr';
            }
        }
        
        // for metals array
        if (isset($_GET['metal']) && !empty($_GET['metal'])) {
            $metal_arr = (array) wp_unslash($_GET['metal']);
            foreach($metal_arr as $metal) {
                $filters['metal'][] = str_replace("metal_","",sanitize_text_field($metal));
            }
        }
        
        $response = krfsapp_fetch_products_by_attributes($filters, $currentcategory, $nextpage);
        $res = krfsapp_prepare_ring_listing($response['products'], $currentcategory, $response['pagination'], $filters);
        wp_send_json($res);
    }else{
        wp_send_json_error(array('message' => 'Access denied!'));
    }
}

function krfsapp_get_attribute_terms() {
    if (
        !isset($_POST['attribute'])
        || empty($_POST['attribute'])
        || !isset($_POST['term_selector'])
        || empty($_POST['term_selector'])
        || !isset($_POST['ring_type'])
        || empty($_POST['ring_type'])
    ) {
        wp_send_json_error(array('message' => 'Something went wrong!'));
    }

    $attribute = isset($_POST['attribute']) ? sanitize_text_field(wp_unslash($_POST['attribute'])) : '';
    $terms = get_terms([
        'taxonomy'   => 'pa_'.$attribute,
        'hide_empty' => false,
    ]);

    $options = '';

    $krfs_attributes_mapping = json_decode(krfsapp_getMeta('attributes_mapping'), true);
    $terms_key = isset($_POST['terms_key']) ? sanitize_text_field(wp_unslash($_POST['terms_key'])) : '';

    $terms_key_prefix = [
        'engagement_ring_style_terms' => 'krfs_style_',
        'engagement_ring_sidestone_terms' => 'krfs_sidestone_',
        'wedding_ring_terms_wedmen' => 'krfs_wedmen_',
        'wedding_ring_terms_wedwomen' => 'krfs_wedwomen_',
        'metal_terms' => 'krfs_metal_',
        'shape_terms' => 'krfs_shape_',
    ];

    $prefix = $terms_key_prefix[$terms_key] ?? false;
    $selected_items = array();
    if($prefix) {
        foreach ($krfs_attributes_mapping[$terms_key] as $key => $value) {
            if($value) {
                $selected_items[$prefix.$key] = $value;
            }
        }
    }

    if (!empty($terms) && !is_wp_error($terms)) {
        $options .= '<option value="">Select Term</option>';
        foreach ($terms as $term) {
            $options .= '<option value="' . esc_attr($term->slug) . '">' . esc_html($term->name) . '</option>';
        }
    } else {
        $options .= '<option value="">No terms found</option>';
    }

    wp_send_json_success(['options' => $options, 'selected_terms' => $selected_items]);
}

/* phpcs:enable */
