<?php
global $wpdb, $post;
$hideDropdown = get_option('wcmlim_hide_show_location_dropdown');

// Get maximum location count setting
$max_location_count = get_option('wcmlim_maximum_location_count', '');

// for out of stock button text
$soldoutbuttontext = get_option("wcmlim_soldout_button_text");
$soldbtntext = array(
  'keys' => $soldoutbuttontext,
);
$plugin_name = isset($this->plugin_name) ? $this->plugin_name :'wcmlim';
wp_localize_script( $plugin_name, 'passedSoldbtn', $soldbtntext );

// for in stock button text
$instockbuttontext = get_option("wcmlim_instock_button_text");
$instobtntext = array(
  'keys' => $instockbuttontext,
);
wp_localize_script( $plugin_name, 'passedinstockbtn', $instobtntext);

// for backorder button text
$backorderbuttontext = get_option("wcmlim_onbackorder_button_text");
$backbtntext = array(
  'keys' => $backorderbuttontext,
);
wp_localize_script( $plugin_name, 'passedbackorderbtn', $backbtntext);

$restrictGuest = get_option('wcmlim_enable_restrict_guestuser_location');
$selectedGuestLoc = get_option('wcmlim_restrict_guest_user_location');

$restrictUser = get_option('wcmlim_enable_userspecific_location');
$current_user_id = get_current_user_id();
$current_ui = isset($current_user_id) ? $current_user_id : "";
$user_selected_location = get_user_meta($current_ui, 'wcmlim_user_specific_location', true);

$excludeLocations = get_option("wcmlim_exclude_locations_from_frontend");

// Include the distance utility class
require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'includes/class-wcmlim-distance-util.php';

// Check if proximity filtering is enabled
$enable_proximity_filter = get_option('wcmlim_enable_filter_by_proximity') === 'on';

// Get unfiltered terms first
if ($restrictGuest == 'on' && !empty($selectedGuestLoc) && !is_user_logged_in()){
    $unfiltered_terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0, 'include' => $selectedGuestLoc));
} elseif ($restrictUser == 'on' && !empty($user_selected_location) && is_user_logged_in()){
    $unfiltered_terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0, 'include' => $user_selected_location)); 
} elseif (!empty($excludeLocations)) {
    $unfiltered_terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0, 'exclude' => $excludeLocations));
} else {
    $unfiltered_terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
}

// Get product information early
$product = wc_get_product($post->ID);

// Initialize parent_id as false
$parent_id = false;

// Check if product is variable and get parent ID
if ($product && $product->is_type('variable')) {
    $parent_id = $product->get_id();
}

$lined_terms = wp_get_object_terms( $post->ID, 'locations', array('fields' => 'ids'));

// Filter terms to only include those associated with the product
$filtered_terms = [];
foreach ($unfiltered_terms as $term) {
    if (in_array($term->term_id, $lined_terms)) {
        $filtered_terms[] = $term;
    }
}
// Use filtered terms if any are found, otherwise stick with all terms
$terms = !empty($filtered_terms) ? $filtered_terms : $unfiltered_terms;


// Apply proximity filtering if enabled and user coordinates are available
if ($enable_proximity_filter) {
    // Get user location from cookies
    $user_lat = isset($_COOKIE['wcmlim_user_lat']) ? sanitize_text_field($_COOKIE['wcmlim_user_lat']) : null;
    $user_lng = isset($_COOKIE['wcmlim_user_lng']) ? sanitize_text_field($_COOKIE['wcmlim_user_lng']) : null;
    
    if ($user_lat && $user_lng) {
        $filtered_terms = array();
        
        foreach ($unfiltered_terms as $term) {
            $loc_lat = get_term_meta($term->term_id, 'wcmlim_lat', true);
            $loc_lng = get_term_meta($term->term_id, 'wcmlim_lng', true);
            $loc_radius = get_term_meta($term->term_id, 'wcmlim_radius', true);
            
            // Default radius if not set
            if (empty($loc_radius)) {
                $loc_radius = 50; // Default radius in km
            }
            
            // If location has valid coordinates
            if (!empty($loc_lat) && !empty($loc_lng)) {
                // Check if user is within the location's radius
                if (WCMLIM_Distance_Util::is_within_radius($user_lat, $user_lng, $loc_lat, $loc_lng, $loc_radius)) {
                    $filtered_terms[] = $term;
                }
            } else {
                // Include locations that don't have coordinates set
                $filtered_terms[] = $term;
            }
        }
        
        // Replace terms with filtered list if we have results
        if (!empty($filtered_terms)) {
            $terms = $filtered_terms;
        }
    }
}

$selected_location = getLocation('wcmlim_selected_location');
$preffLocation = ($selected_location !== false && $selected_location !== 'default') ? $selected_location : '';
$enable_price = 'on';

// Define all option keys in an array
$option_keys = [
    'woocommerce_stock_format',
    'wcmlim_preview_stock_bgcolor',
    'wcmlim_txt_stock_info',
    'wcmlim_txtcolor_stock_info',
    'wcmlim_display_stock_info',
    'wcmlim_txt_preferred_location',
    'wcmlim_txtcolor_preferred_loc',
    'wcmlim_display_preferred_loc',
    'wcmlim_txt_nearest_stock_loc',
    'wcmlim_txtcolor_nearest_stock',
    'wcmlim_display_nearest_stock',
    'wcmlim_separator_linecolor',
    'wcmlim_display_separator_line',
    'wcmlim_oncheck_button_text',
    'wcmlim_oncheck_button_color',
    'wcmlim_oncheck_button_text_color',
    'wcmlim_soldout_button_text',
    'wcmlim_soldout_button_color',
    'wcmlim_soldout_button_text_color',
    'wcmlim_instock_button_text',
    'wcmlim_instock_button_color',
    'wcmlim_instock_button_text_color',
    'wcmlim_next_closest_location',
    'wcmlim_preview_stock_width',
    'wcmlim_sel_padding_top',
    'wcmlim_sel_padding_right',
    'wcmlim_sel_padding_bottom',
    'wcmlim_sel_padding_left',
    'wcmlim_inp_padding_top',
    'wcmlim_inp_padding_right',
    'wcmlim_inp_padding_bottom',
    'wcmlim_inp_padding_left',
    'wcmlim_btn_padding_top',
    'wcmlim_btn_padding_right',
    'wcmlim_btn_padding_bottom',
    'wcmlim_btn_padding_left',
    'wcmlim_display_icon',
    'wcmlim_iconcolor_loc',
    'wcmlim_iconsize_loc',
    'wcmlim_is_padding_top',
    'wcmlim_is_padding_bottom',
    'wcmlim_is_padding_right',
    'wcmlim_is_padding_left',
    'wcmlim_sbox_padding_top',
    'wcmlim_sbox_padding_bottom',
    'wcmlim_sbox_padding_right',
    'wcmlim_sbox_padding_left',
    'wcmlim_selbox_bgcolor',
    'wcmlim_select_or_dropdown',
    'wcmlim_enable_location_group',
    'wcmlim_onbackorder_button_text',
    'wcmlim_onbackorder_button_color',
    'wcmlim_onbackorder_button_text_color',
    'wcmlim_onbackorder_borderradius'
];

$placeholders = implode(',', array_fill(0, count($option_keys), '%s'));

$stock_view = get_option('wcmlim_backend_display_stock_view');



// Fetch options in a single query
$query = "
    SELECT option_name, option_value
    FROM {$wpdb->options}
    WHERE option_name IN ($placeholders)
";
$results = $wpdb->get_results($wpdb->prepare($query, $option_keys), OBJECT_K);

// Transform results into an associative array
$options = [];
foreach ($results as $key => $row) {
    $options[$key] = maybe_unserialize($row->option_value);
}

// Fetch product information only once
$product = wc_get_product($post->ID);
$regprice = wc_price($product->get_price_html());

// Now assign the options to their respective variables
$stock_display_format   = $options['woocommerce_stock_format'] ?? '';
$stockbox_color         = $options['wcmlim_preview_stock_bgcolor'] ?? '';
$txt_stock_inf          = $options['wcmlim_txt_stock_info'] ?? '';
$txtcolor_stock_inf     = $options['wcmlim_txtcolor_stock_info'] ?? '';
$display_stock_inf      = $options['wcmlim_display_stock_info'] ?? '';
$txt_preferred          = $options['wcmlim_txt_preferred_location'] ?? '';
$txtcolor_preferred     = $options['wcmlim_txtcolor_preferred_loc'] ?? '';
$display_preferred      = $options['wcmlim_display_preferred_loc'] ?? '';
$txt_nearest            = $options['wcmlim_txt_nearest_stock_loc'] ?? '';
$txtcolor_nearest       = $options['wcmlim_txtcolor_nearest_stock'] ?? '';
$display_nearest        = $options['wcmlim_display_nearest_stock'] ?? '';
$color_separator        = $options['wcmlim_separator_linecolor'] ?? '';
$display_separator      = $options['wcmlim_display_separator_line'] ?? '';
$oncheck_btntxt         = $options['wcmlim_oncheck_button_text'] ?? '';
$oncheck_btnbgcolor     = $options['wcmlim_oncheck_button_color'] ?? '';
$oncheck_btntxtcolor    = $options['wcmlim_oncheck_button_text_color'] ?? '';
$soldout_btntxt         = $options['wcmlim_soldout_button_text'] ?? '';
$soldout_btnbgcolor     = $options['wcmlim_soldout_button_color'] ?? '';
$soldout_btntxtcolor    = $options['wcmlim_soldout_button_text_color'] ?? '';
$instock_btntxt         = $options['wcmlim_instock_button_text'] ?? '';
$instock_btnbgcolor     = $options['wcmlim_instock_button_color'] ?? '';
$instock_btntxtcolor    = $options['wcmlim_instock_button_text_color'] ?? '';
$showNxtLoc             = $options['wcmlim_next_closest_location'] ?? '';
$boxwidth               = $options['wcmlim_preview_stock_width'] ?? '';
$sel_padtop             = $options['wcmlim_sel_padding_top'] ?? '';
$sel_padright           = $options['wcmlim_sel_padding_right'] ?? '';
$sel_padbottom          = $options['wcmlim_sel_padding_bottom'] ?? '';
$sel_padleft            = $options['wcmlim_sel_padding_left'] ?? '';
$inp_padtop             = $options['wcmlim_inp_padding_top'] ?? '';
$inp_padright           = $options['wcmlim_inp_padding_right'] ?? '';
$inp_padbottom          = $options['wcmlim_inp_padding_bottom'] ?? '';
$inp_padleft            = $options['wcmlim_inp_padding_left'] ?? '';
$btn_padtop             = $options['wcmlim_btn_padding_top'] ?? '';
$btn_padright           = $options['wcmlim_btn_padding_right'] ?? '';
$btn_padbottom          = $options['wcmlim_btn_padding_bottom'] ?? '';
$btn_padleft            = $options['wcmlim_btn_padding_left'] ?? '';
$iconshow               = $options['wcmlim_display_icon'] ?? '';
$icon_color             = $options['wcmlim_iconcolor_loc'] ?? '';
$icon_size              = $options['wcmlim_iconsize_loc'] ?? '';
$is_padtop              = $options['wcmlim_is_padding_top'] ?? '';
$is_padbottom           = $options['wcmlim_is_padding_bottom'] ?? '';
$is_padright            = $options['wcmlim_is_padding_right'] ?? '';
$is_padleft             = $options['wcmlim_is_padding_left'] ?? '';
$sbox_padtop            = $options['wcmlim_sbox_padding_top'] ?? '';
$sbox_padbottom         = $options['wcmlim_sbox_padding_bottom'] ?? '';
$sbox_padright          = $options['wcmlim_sbox_padding_right'] ?? '';
$sbox_padleft           = $options['wcmlim_sbox_padding_left'] ?? '';
$sbox_bgcolor           = $options['wcmlim_selbox_bgcolor'] ?? '';
$optiontype_loc         = $options['wcmlim_select_or_dropdown'] ?? '';
$isLocationsGroup       = $options['wcmlim_enable_location_group'] ?? '';
$backorderbuttontext    = $options['wcmlim_onbackorder_button_text'] ?? '';
$backorder_btnbgcolor   = $options['wcmlim_onbackorder_button_color'] ?? '';
$backorder_btntxtcolor  = $options['wcmlim_onbackorder_button_text_color'] ?? '';
$backorder_borderradius = $options['wcmlim_onbackorder_borderradius'] ?? '';

// Initialize missing border and styling variables
$border_option          = $options['wcmlim_border_option'] ?? '';
$border_color           = $options['wcmlim_border_color'] ?? '';
$border_width           = $options['wcmlim_border_width'] ?? '';
$border_radius          = $options['wcmlim_border_radius'] ?? '';
$refborder_radius       = $options['wcmlim_refborder_radius'] ?? '';
$input_radius           = $options['wcmlim_input_radius'] ?? '';
$oncheck_radius         = $options['wcmlim_oncheck_radius'] ?? '';
$instock_radius         = $options['wcmlim_instock_radius'] ?? '';
$soldout_radius         = $options['wcmlim_soldout_radius'] ?? '';
$customcss_enable       = $options['wcmlim_customcss_enable'] ?? '';

// Check for the custom field value for each term
foreach ($terms as $term) {
    if ($product->is_type('variable') && !$product->is_downloadable() && !$product->is_virtual()) {
        $variations = $product->get_available_variations();
        if (!empty($variations)) {
            foreach ($variations as $key => $value) {
                $check_taxanomy_variable = get_post_meta($value['variation_id'], "wcmlim_stock_at_{$term->term_id}", true);
            }
        }
    } elseif ($product instanceof WC_Product && $product->is_type('simple') && !$product->is_downloadable() && !$product->is_virtual()) {
        $check_taxanomy = get_post_meta($post->ID, "wcmlim_stock_at_{$term->term_id}", true);
    }
}

// For variable product type: check variations for stock management
if ($product->is_type('variable') && !$product->is_downloadable() && !$product->is_virtual()) {
    $variations = $product->get_available_variations();
    $manage_stock_yes = false; 
    if (!empty($variations)) {
        foreach ($variations as $variation) {
            $variation_id = $variation['variation_id'];
            $manage_stock = get_post_meta($variation_id, '_manage_stock', true);
            if ($manage_stock == 'yes') {
                $manage_stock_yes = true;
                break;
            }
        }
    }
    if (!$manage_stock_yes) {
        foreach ($variations as $variation) {
            $variation_id = $variation['variation_id'];
            $manage_stock = get_post_meta($variation_id, '_manage_stock', true);
            if ($manage_stock == 'no') {
                return;
            }
        }
    }
}
if ($hideDropdown == "on") {
        ?>
        <style>
            .wcmlim_product { display: none !important; }
        </style>
        <?php
    } else {
        ?>
        <style>
            .wcmlim_product { display: block !important; }
        </style>
        <?php
    }

 // Retrieve the setting for proximity-based sorting.
 $priority_order_by_proximity = get_option('wcmlim_enable_sorting_by_proximity');

 // Select the appropriate priority order based on the proximity setting:
 // - If disabled, use the admin-defined order stored in options.
 // - If enabled, use the user-location-based order stored in a cookie (if available).
 $priority_order = ($priority_order_by_proximity != 'on') 
     ? get_option('wcmlim_location_priority_order') 
     : (isset($_COOKIE['wcmlim_location_priority_order_by_user_loc']) ? $_COOKIE['wcmlim_location_priority_order_by_user_loc'] : '');

 // If the priority order is a non-empty string and proximity sorting is on,
 // attempt to decode it from JSON.
 if (is_string($priority_order) && !empty($priority_order) && ($priority_order_by_proximity == 'on')) {
     $priority_order = json_decode($priority_order, true);
     // If JSON decoding fails or the result isn't an array, convert the string to an array manually.
     if (json_last_error() !== JSON_ERROR_NONE || !is_array($priority_order)) {
         $priority_order = array_map('intval', explode(',', trim($priority_order, '[] ')));
     }
 }

 // Ensure the priority order is an array.
 if (!is_array($priority_order)) {
     $decoded = json_decode($priority_order, true);
     if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
         $priority_order = $decoded;
     } else {
         $priority_order = array_map('intval', explode(',', trim($priority_order, '[] ')));
     }
 }

 // If a priority order exists, sort the $terms array according to it.
 if (!empty($priority_order)) {
     uasort($terms, function($a, $b) use ($priority_order) {
         // Find positions of each term ID in the priority order array.
         $posA = array_search($a->term_id, $priority_order);
         $posB = array_search($b->term_id, $priority_order);
         // If a term is not found, assign it the maximum possible position.
         $posA = ($posA === false) ? PHP_INT_MAX : $posA;
         $posB = ($posB === false) ? PHP_INT_MAX : $posB;
         return $posA - $posB;
     });
 }

// --------------------------------------------------------------------------------
// --- Enhanced Filter locations based on rules in wcmlim_saved_rules ---
// --------------------------------------------------------------------------------

$saved_rules = get_option('wcmlim_saved_rules');
$enable_rules = get_option('wcmlim_enable_rules');
$filtered_terms = array();

foreach ($terms as $term) {
    $show_location = true;
    // Check global rules
    if ($enable_rules === 'yes' && !empty($saved_rules)) {
        $rules = maybe_unserialize($saved_rules);
        $results = array();
        foreach ($rules as $rule) {
            $relation = isset($rule['relation']) ? strtoupper($rule['relation']) : 'AND';
            $conditions = isset($rule['conditions']) ? $rule['conditions'] : array();
            $condition_results = array();
            foreach ($conditions as $condition) {
                $type = isset($condition['type']) ? $condition['type'] : '';
                $operator = isset($condition['operator']) ? $condition['operator'] : '';
                $value = isset($condition['value']) ? $condition['value'] : array();
                $result = true;
                // Product
                if ($type == 'Product') {
                    if ($operator === 'Includes') {
                        $result = !empty($value) ? in_array($product->get_id(), $value) : false;
                    } else {
                        $result = !empty($value) ? !in_array($product->get_id(), $value) : true;
                    }
                }
                // Product Category
                elseif ($type == 'Product Category') {
                    $product_cats = wp_get_post_terms($product->get_id(), 'product_cat', array('fields' => 'ids'));
                    if ($operator === 'Includes') {
                        $result = !empty($value) ? !empty(array_intersect($product_cats, $value)) : false;
                    } else {
                        $result = !empty($value) ? empty(array_intersect($product_cats, $value)) : true;
                    }
                }
                // Product Tag
                elseif ($type == 'Product Tag') {
                    $product_tags = wp_get_post_terms($product->get_id(), 'product_tag', array('fields' => 'ids'));
                    if ($operator === 'Includes') {
                        $result = !empty($value) ? !empty(array_intersect($product_tags, $value)) : false;
                    } else {
                        $result = !empty($value) ? empty(array_intersect($product_tags, $value)) : true;
                    }
                }
                // Product Brand (assuming taxonomy 'product_brand')
                elseif ($type == 'Product Brand') {
                    $product_brands = wp_get_post_terms($product->get_id(), 'product_brand', array('fields' => 'ids'));
                    if ($operator === 'Includes') {
                        $result = !empty($value) ? !empty(array_intersect($product_brands, $value)) : false;
                    } else {
                        $result = !empty($value) ? empty(array_intersect($product_brands, $value)) : true;
                    }
                }
                // Product Attributes (assuming $value is array of attribute slugs)
                elseif ($type == 'Product Attributes') {
                    $attributes = $product->get_attributes();
                    $attr_match = false;
                    if (!empty($value)) {
                        foreach ($attributes as $attr_obj) {
                            if (method_exists($attr_obj, 'get_name')) {
                                $attr_name = $attr_obj->get_name();
                                if (in_array($attr_name, $value)) {
                                    $attr_match = true;
                                    break;
                                }
                            }
                        }
                    }
                    if ($operator == 'Includes') {
                        $result = !empty($value) ? $attr_match : false;
                    } else {
                        $result = !empty($value) ? !$attr_match : true;
                    }
                }
                $condition_results[] = $result;
            }
            $results[] = in_array(true, $condition_results, true);
        }
        if (in_array(false, $results, true)) {
            $show_location = false;
        }
    }
    // Check individual location rules
    $term_enable_rules = get_term_meta($term->term_id, 'wcmlim_enable_rules', true);
    $term_saved_rules = get_term_meta($term->term_id, 'wcmlim_saved_rules', true);
    if ($term_enable_rules === 'on' && !empty($term_saved_rules)) {
        $rules = json_decode($term_saved_rules, true);
        if (is_array($rules)) {
            $results = array();
            foreach ($rules as $rule) {
                $relation = isset($rule['relation']) ? strtoupper($rule['relation']) : 'AND';
                $conditions = isset($rule['conditions']) ? $rule['conditions'] : array();
                $condition_results = array();
                foreach ($conditions as $condition) {
                    $type = isset($condition['type']) ? $condition['type'] : '';
                    $operator = isset($condition['operator']) ? $condition['operator'] : '';
                    $value = isset($condition['value']) ? $condition['value'] : array();
                    $result = true;
                    // Product
                    if ($type == 'Product') {
                        if ($operator === 'Includes') {
                            $result = !empty($value) ? in_array($product->get_id(), $value) : false;
                        } else {
                            $result = !empty($value) ? !in_array($product->get_id(), $value) : true;
                        }
                    }
                    // Product Category
                    elseif ($type == 'Product Category') {
                        $product_cats = wp_get_post_terms($product->get_id(), 'product_cat', array('fields' => 'ids'));
                        if ($operator === 'Includes') {
                            $result = !empty($value) ? !empty(array_intersect($product_cats, $value)) : false;
                        } else {
                            $result = !empty($value) ? empty(array_intersect($product_cats, $value)) : true;
                        }
                    }
                    // Product Tag
                    elseif ($type == 'Product Tag') {
                        $product_tags = wp_get_post_terms($product->get_id(), 'product_tag', array('fields' => 'ids'));
                        if ($operator === 'Includes') {
                            $result = !empty($value) ? !empty(array_intersect($product_tags, $value)) : false;
                        } else {
                            $result = !empty($value) ? empty(array_intersect($product_tags, $value)) : true;
                        }
                    }
                    // Product Brand (assuming taxonomy 'product_brand')
                    elseif ($type == 'Product Brand') {
                        $product_brands = wp_get_post_terms($product->get_id(), 'product_brand', array('fields' => 'ids'));
                        if ($operator === 'Includes') {
                            $result = !empty($value) ? !empty(array_intersect($product_brands, $value)) : false;
                        } else {
                            $result = !empty($value) ? empty(array_intersect($product_brands, $value)) : true;
                        }
                    }
                    // Product Attributes (assuming $value is array of attribute slugs)
                    elseif ($type == 'Product Attributes') {
                        $attributes = $product->get_attributes();
                        $attr_match = false;
                        if (!empty($value)) {
                            foreach ($attributes as $attr_obj) {
                                if (method_exists($attr_obj, 'get_name')) {
                                    $attr_name = $attr_obj->get_name();
                                    if (in_array($attr_name, $value)) {
                                        $attr_match = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if ($operator == 'Includes') {
                            $result = !empty($value) ? $attr_match : false;
                        } else {
                            $result = !empty($value) ? !$attr_match : true;
                        }
                    }
                    $condition_results[] = $result;
                }
                $results[] = in_array(true, $condition_results, true);
            }
            if (in_array(false, $results, true)) {
                $show_location = false;
            }
        }
    }
    if ($show_location) {
        $filtered_terms[] = $term;
    }
}

$terms = $filtered_terms; // Update terms with the filtered list

// --------------------------------------------------------------------------------
// --- End enhanced rules filtering ---
// --------------------------------------------------------------------------------

 // Check if thresholds are enabled
 // Pass location_thresholds to the view template
 $enable_threshold = get_option('wcmlim_enable_location_thresholds');
 $location_thresholds = [];
 if ($enable_threshold == "on") {
     $thresholds = maybe_unserialize(get_option('wcmlim_location_thresholds'));
     if (is_array($thresholds)) {
         $location_thresholds = $thresholds;
     }
 }

 // Get serialized field order for additional location information
 // Pass field_order to the view template
 $serialized_field_order = get_option('wcmlim_backend_display_feilds_settings');
 if (is_string($serialized_field_order)) {
     $field_order = unserialize($serialized_field_order);
 } else {
     $field_order = $serialized_field_order;
 }
 if (!is_array($field_order)) {
     $field_order = [];
 }

 // Get section order from admin settings
 $section_order = get_option('wcmlim_backend_display_feilds_settings_order');
 $default_section_keys = array('general', 'address', 'location_note', 'contact', 'business_hours');
 if (!is_array($section_order) || empty($section_order)) {
     $section_order = $default_section_keys;
 }

// Build location details data array for views organized by sections
$location_details_data = array();
foreach ($terms as $term) {
    $location_details_data[$term->term_id] = array();
    
    // Group fields by category
    $address_fields = array();
    $contact_fields = array();
    $timing_fields = array();
    $note_field = '';
    $distance_content = '';
    
    foreach ($field_order as $field) {
        if($field == 'postcode'){
            $field = 'postal_code';
        }
        $field_value = get_term_meta($term->term_id, 'wcmlim_' . $field, true);
        $loc_note = get_term_meta($term->term_id, 'wcmlim_location_note', true);
        if ($field_value) {
            // Categorize fields
            if (in_array($field, array('address', 'route', 'street_number', 'city', 'state', 'postal_code', 'country', 'locality'))) {
                $address_fields[$field] = $field_value;
            } elseif (in_array($field, array('email', 'phone'))) {
                $contact_fields[$field] = $field_value;
            } elseif (in_array($field, array('start_time', 'end_time'))) {
                $timing_fields[$field] = $field_value;
            } elseif (in_array($field, array('location_note'))) {
                $note_field = $loc_note;
            } 
        }
    }
    
    // Get distance content if enabled
    if (in_array('distance', $field_order)) {
        $distance_content = wcmlim_get_distance_to_location($term->term_id);
    }
    
    // Build sections data according to section order
    $sections_data = array();
    
    foreach ($section_order as $section_key) {
        switch ($section_key) {
            case 'general':
                if (!empty($distance_content)) {
                    $sections_data['general'] = array(
                        'section_key' => 'general',
                        'icon' => 'dashicons dashicons-location',
                        'content' => $distance_content
                    );
                }
                break;
                
            case 'address':
                if (!empty($address_fields)) {
                    $sections_data['address'] = array(
                        'section_key' => 'address',
                        'icon' => 'dashicons dashicons-admin-home',
                        'content' => implode(', ', $address_fields)
                    );
                }
                break;
                
            case 'location_note':
                if (!empty($note_field)) {
                    $sections_data['location_note'] = array(
                        'section_key' => 'location_note',
                        'icon' => 'dashicons dashicons-welcome-write-blog',
                        'content' => $note_field
                    );
                }
                break;
                
            case 'contact':
                if (!empty($contact_fields)) {
                    $contact_str = array();
                    if (isset($contact_fields['email'])) {
                        $contact_str[] = $contact_fields['email'];
                    }
                    if (isset($contact_fields['phone'])) {
                        $contact_str[] = $contact_fields['phone'];
                    }
                    $sections_data['contact'] = array(
                        'section_key' => 'contact',
                        'icon' => 'dashicons dashicons-email',
                        'content' => implode(' , ', $contact_str)
                    );
                }
                break;
                
            case 'business_hours':
                if (!empty($timing_fields)) {
                    $timing_str = array();
                    if (isset($timing_fields['start_time']) && isset($timing_fields['end_time'])) {
                        $timing_str[] = $timing_fields['start_time'] . ' - ' . $timing_fields['end_time'];
                    } elseif (isset($timing_fields['start_time'])) {
                        $timing_str[] = $timing_fields['start_time'];
                    } elseif (isset($timing_fields['end_time'])) {
                        $timing_str[] = $timing_fields['end_time'];
                    }
                    if (!empty($timing_str)) {
                        $sections_data['business_hours'] = array(
                            'section_key' => 'business_hours',
                            'icon' => 'dashicons dashicons-clock',
                            'content' => implode(' , ', $timing_str)
                        );
                    }
                }
                break;
                
            case 'google_rating':
                // Get Google rating for this location
                $place_id = get_term_meta($term->term_id, 'google_place_id', true);
                $api_key = get_option('wcmlim_google_api_key', '');
                
                if (!empty($place_id) && !empty($api_key)) {
                    // Check cache first
                    $cache_key = 'wcmlim_rating_' . md5($term->term_id . '_' . $place_id);
                    $cached_data = get_transient($cache_key);
                    
                    if (false === $cached_data) {
                        // Fetch from Google Places API
                        $url = add_query_arg(
                            array(
                                'place_id' => $place_id,
                                'fields'   => 'rating,user_ratings_total',
                                'key'      => $api_key,
                            ),
                            'https://maps.googleapis.com/maps/api/place/details/json'
                        );
                        
                        $response = wp_remote_get($url, array('timeout' => 10));
                        
                        if (!is_wp_error($response)) {
                            $body = wp_remote_retrieve_body($response);
                            $data = json_decode($body, true);
                            
                            if (!empty($data['result'])) {
                                $cached_data = array(
                                    'rating' => isset($data['result']['rating']) ? floatval($data['result']['rating']) : 0,
                                    'total'  => isset($data['result']['user_ratings_total']) ? intval($data['result']['user_ratings_total']) : 0,
                                );
                                set_transient($cache_key, $cached_data, 24 * HOUR_IN_SECONDS);
                            }
                        }
                    }
                    
                    if (!empty($cached_data) && isset($cached_data['rating']) && $cached_data['rating'] > 0) {
                        // Generate stars
                        $rating = floatval($cached_data['rating']);
                        $review_count = isset($cached_data['total']) ? intval($cached_data['total']) : 0;
                        
                        $full_stars = floor($rating);
                        $half_star = ($rating - $full_stars) >= 0.5 ? 1 : 0;
                        $empty_stars = 5 - $full_stars - $half_star;
                        
                        $stars_html = '<span class="wcmlim-inline-stars">';
                        for ($i = 0; $i < $full_stars; $i++) {
                            $stars_html .= '<span style="color:#FFD700;">★</span>';
                        }
                        if ($half_star) {
                            $stars_html .= '<span style="color:#FFD700;opacity:0.7;">★</span>';
                        }
                        for ($i = 0; $i < $empty_stars; $i++) {
                            $stars_html .= '<span style="color:#ddd;">☆</span>';
                        }
                        $stars_html .= '</span>';
                        
                        // Create Google Maps link
                        $google_maps_url = 'https://www.google.com/maps/search/?api=1&query=Google&query_place_id=' . urlencode($place_id);
                        
                        // Build rating content with proper null checks
                        $rating_content = $stars_html . ' <span style="font-weight:600;">' . number_format($rating, 1) . '</span>';
                        
                        if ($review_count > 0) {
                            $rating_content .= ' <a href="' . esc_url($google_maps_url) . '" target="_blank" rel="noopener noreferrer" style="color:#1a73e8;text-decoration:underline;font-size:0.9em;">(' . number_format($review_count) . ' reviews)</a>';
                        }
                        
                        $sections_data['google_rating'] = array(
                            'section_key' => 'google_rating',
                            'icon' => 'dashicons dashicons-star-filled',
                            'content' => $rating_content,
                            'is_html' => true // Flag to indicate content contains HTML
                        );
                    }
                }
                break;
        }
    }
    
    // Convert sections_data to indexed array maintaining the order
    $location_details_data[$term->term_id] = array_values($sections_data);
}

// Finally, render the appropriate front-end view template.
// Instead of require/include, use the new loader for all views
require_once WCMLIM_DIR_PATH . 'includes/helper/wcmlim-view-loader.php';

$view_vars = compact(
    'wpdb',
    'post',
    'hideDropdown',
    'max_location_count',
    'soldoutbuttontext',
    'soldbtntext',
    'plugin_name',
    'instockbuttontext',
    'instobtntext',
    'backorderbuttontext',
    'backorder_btnbgcolor',
    'backorder_btntxtcolor',
    'backorder_borderradius',
    'backbtntext',
    'restrictGuest',
    'selectedGuestLoc',
    'restrictUser',
    'current_user_id',
    'current_ui',
    'user_selected_location',
    'excludeLocations',
    'enable_proximity_filter',
    'unfiltered_terms',
    'product',
    'parent_id',
    'lined_terms',
    'filtered_terms',
    'terms',
    'selected_location',
    'preffLocation',
    'enable_price',
    'option_keys',
    'placeholders',
    'stock_view',
    'options',
    'regprice',
    'stock_display_format',
    'stockbox_color',
    'txt_stock_inf',
    'txtcolor_stock_inf',
    'display_stock_inf',
    'txt_preferred',
    'txtcolor_preferred',
    'display_preferred',
    'txt_nearest',
    'txtcolor_nearest',
    'display_nearest',
    'color_separator',
    'display_separator',
    'oncheck_btntxt',
    'oncheck_btnbgcolor',
    'oncheck_btntxtcolor',
    'soldout_btntxt',
    'soldout_btnbgcolor',
    'soldout_btntxtcolor',
    'instock_btntxt',
    'instock_btnbgcolor',
    'instock_btntxtcolor',
    'border_option',
    'border_color',
    'border_width',
    'border_radius',
    'refborder_radius',
    'input_radius',
    'oncheck_radius',
    'instock_radius',
    'soldout_radius',
    'showNxtLoc',
    'boxwidth',
    'sel_padtop',
    'sel_padright',
    'sel_padbottom',
    'sel_padleft',
    'inp_padtop',
    'inp_padright',
    'inp_padbottom',
    'inp_padleft',
    'btn_padtop',
    'btn_padright',
    'btn_padbottom',
    'btn_padleft',
    'iconshow',
    'icon_color',
    'icon_size',
    'is_padtop',
    'is_padbottom',
    'is_padright',
    'is_padleft',
    'sbox_padtop',
    'sbox_padbottom',
    'sbox_padright',
    'sbox_padleft',
    'sbox_bgcolor',
    'optiontype_loc',
    'isLocationsGroup',
    'backorderbuttontext',
    'backorder_btnbgcolor',
    'backorder_btntxtcolor',
    'backorder_borderradius',
    'priority_order_by_proximity',
    'priority_order',
    'enable_threshold',
    'location_thresholds',
    'serialized_field_order',
    'field_order',
    'customcss_enable',
    'location_details_data'
);

switch ($stock_view) {
    case 'list_view':
    case '':
        wcmlim_load_view('wcmlim-list-view-new', $view_vars);
        break;
    case 'select_view':
        wcmlim_load_view('wcmlim-select-view', $view_vars);
        break;
    case 'expanded_view':
        wcmlim_load_view('wcmlim-expanded-view', $view_vars);
        break;
    case 'card_view':
        wcmlim_load_view('wcmlim-card-view', $view_vars);
        break;
    case 'table_view':
        wcmlim_load_view('wcmlim-table-view', $view_vars);
        break;
    case 'simple_text_view':
        wcmlim_load_view('wcmlim-simple-text-view', $view_vars);
        break;
    case 'twocol_view':
        wcmlim_load_view('wcmlim-twocol-view', $view_vars);
        break;
    case 'threecol_view':
        wcmlim_load_view('wcmlim-threecol-view', $view_vars);
        break;
    case 'drawer_view':
        wcmlim_load_view('wcmlim-drawer-view', $view_vars);
        break;
    case 'popup_view':
        wcmlim_load_view('wcmlim-popup-view', $view_vars);
        break;
    default:
        wcmlim_load_view('wcmlim-list-view-new', $view_vars);
        break;
}

// Custom CSS remains unchanged

if (isset($customcss_enable) && $customcss_enable == "") {
    ?>
    <style>
        .wcmlim_product .loc_dd.Wcmlim_prefloc_sel {
            border-radius: <?php echo $refborder_radius ?? ''; ?> !important;
            padding-top: <?php echo $sbox_padtop ?? ''; ?>px !important;
            padding-right: <?php echo $sbox_padright ?? ''; ?>px !important;
            padding-bottom: <?php echo $sbox_padbottom ?? ''; ?>px !important;
            padding-left: <?php echo $sbox_padleft ?? ''; ?>px !important;
            background: <?php echo $sbox_bgcolor ?? ''; ?> !important;
        }
        .Wcmlim_have_stock,
        .Wcmlim_over_stock {
            padding-top: <?php echo $is_padtop ?? ''; ?>px !important;
            padding-right: <?php echo $is_padright ?? ''; ?>px !important;
            padding-bottom: <?php echo $is_padbottom ?? ''; ?>px !important;
            padding-left: <?php echo $is_padleft ?? ''; ?>px !important;
        }
        .wcmlim_product .loc_dd.Wcmlim_prefloc_sel .Wcmlim_sel_loc {
            padding-top: <?php echo $sel_padtop ?? ''; ?>px !important;
            padding-right: <?php echo $sel_padright ?? ''; ?>px !important;
            padding-bottom: <?php echo $sel_padbottom ?? ''; ?>px !important;
            padding-left: <?php echo $sel_padleft ?? ''; ?>px !important;
        }
        .wcmlim_product .postcode-checker-div input[type="text"] {
            padding-top: <?php echo $inp_padtop ?? ''; ?>px !important;
            padding-right: <?php echo $inp_padright ?? ''; ?>px !important;
            padding-bottom: <?php echo $inp_padbottom ?? ''; ?>px !important;
            padding-left: <?php echo $inp_padleft ?? ''; ?>px !important;
            border-radius: <?php echo $input_radius ?? ''; ?> !important;
        }
        .wcmlim_product #submit_postcode_product {
            padding-top: <?php echo $btn_padtop ?? ''; ?>px !important;
            padding-right: <?php echo $btn_padright ?? ''; ?>px !important;
            padding-bottom: <?php echo $btn_padbottom ?? ''; ?>px !important;
            padding-left: <?php echo $btn_padleft ?? ''; ?>px !important;
        }
        .wcmlim_product .loc_dd.Wcmlim_prefloc_sel .fa-map-marker-alt {
            color: <?php echo $icon_color ?? ''; ?> !important;
            font-size: <?php echo $icon_size ?? ''; ?>px !important;
        }
        <?php if ($iconshow == "on") { ?>
        .wcmlim_product .loc_dd.Wcmlim_prefloc_sel .fa-map-marker-alt {
            display: none !important;
        }
        <?php } ?>
        .Wcmlim_container.wcmlim_product {
            background-color: <?php echo $stockbox_color ?? ''; ?>;
            border-radius: <?php echo $border_radius ?? ''; ?>;
            border-color: <?php echo $border_color ?? ''; ?>;
            border-width: <?php echo $border_width ?? ''; ?>;
            width: <?php echo $boxwidth ?? ''; ?>%;
        }
        <?php if (isset($border_option) && $border_option == "none") { ?>
        .Wcmlim_container.wcmlim_product {
            max-width: 438px;
            width: 100%;
            border-style: none;
            padding: 0;
        }
        <?php } ?>
        <?php if (isset($border_option) && $border_option == "solid") { ?>
        .Wcmlim_container.wcmlim_product {
            border-style: solid;
            max-width: 438px;
            width: 100%;
        }
        <?php } ?>
        <?php if (isset($border_option) && $border_option == "dotted") { ?>
        .Wcmlim_container.wcmlim_product {
            max-width: 438px;
            width: 100%;
            border-style: dotted;
        }
        <?php } ?>
        <?php if (isset($border_option) && $border_option == "double") { ?>
        .Wcmlim_container.wcmlim_product {
            border-style: double;
            max-width: 438px;
            width: 100%;
        }
        <?php } ?>
        <?php if (isset($border_option) && $border_option == "dashed") { ?>
        .Wcmlim_container.wcmlim_product {
            border-style: dashed;
            max-width: 438px;
            width: 100%;
        }
        <?php } ?>
        .wcmlim_product #submit_postcode_product,
        .wcmlim_product #submit_postcode_global {
            border-radius: <?php echo $oncheck_radius ?? ''; ?> !important;
            color: <?php echo $oncheck_btntxtcolor ?? ''; ?> !important;
            background-color: <?php echo $oncheck_btnbgcolor ?? ''; ?> !important;
        }
        .wcmlim_product .Wcmlim_box_title {
            color: <?php echo $txtcolor_stock_inf ?? ''; ?> !important;
        }
        .wcmlim_product .loc_dd {
            color: <?php echo $txtcolor_preferred ?? ''; ?> !important;
        }
        .wcmlim_product .postcode-checker-title {
            color: <?php echo $txtcolor_nearest ?? ''; ?> !important;
        }
        .wcmlim_product .Wcmlim_line_seperator {
            background-color: <?php echo $color_separator ?? ''; ?>;
        }
        .wcmlim_product #submit_postcode_product,
        .wcmlim_product #submit_postcode_global {
            border-radius: <?php echo $oncheck_radius ?? ''; ?> !important;
            color: <?php echo $oncheck_btntxtcolor ?? ''; ?> !important;
            background-color: <?php echo $oncheck_btnbgcolor ?? ''; ?> !important;
        }
        .Wcmlim_have_stock {
            border-radius: <?php echo $instock_radius ?? ''; ?>;
            color: <?php echo $instock_btntxtcolor ?? ''; ?> !important;
            background-color: <?php echo $instock_btnbgcolor ?? ''; ?> !important;
        }
        .Wcmlim_over_stock {
            border-radius: <?php echo $soldout_radius ?? ''; ?>;
            color: <?php echo $soldout_btntxtcolor ?? ''; ?> !important;
            background-color: <?php echo $soldout_btnbgcolor ?? ''; ?> !important;
        }
        <?php if ( isset($display_stock_inf) && $display_stock_inf == "on") { ?>
        .Wcmlim_box_header { display: none; }
        <?php } ?>
        <?php if ( isset($display_preferred) && $display_preferred == "on") { ?>
        .Wcmlim_sloc_label { display: none; }
        <?php } ?>
        <?php if ( isset($display_nearest) && $display_nearest == "on") { ?>
        .postcode-checker-title { display: none; }
        <?php } ?>
        <?php if ( isset($display_separator) && $display_separator == "on") { ?>
        .Wcmlim_line_seperator { display: none; }
        <?php } else { ?>
        .Wcmlim_line_seperator { display: block; }
        <?php } ?>
    </style>
    
    <!-- Maximum Location Count JavaScript -->
    <script type="text/javascript">
    (function() {
        var maxLocationCount = <?php echo !empty($max_location_count) && is_numeric($max_location_count) ? intval($max_location_count) : 0; ?>;
        
        if (maxLocationCount > 0) {
            // Function to apply maximum location count
            function wcmlimApplyMaxLocationCount() {
                // First, remove the max-count-hidden class and show all previously hidden items
                jQuery('.wcmlim-max-count-hidden').removeClass('wcmlim-max-count-hidden').show().prop('disabled', false);
                
                var selectors = [
                    '.location-stock-card',           // Card view
                    '.location-list-item',             // Expanded view
                    '.location-stock-item',            // Simple text, two-col, three-col, popup, drawer
                    '.location-stock-row',             // Table view
                    '.wcmlim_radio_option',            // List view
                    'select.select_location option'    // Select view (dropdown options)
                ];
                
                selectors.forEach(function(selector) {
                    var visibleCount = 0;
                    
                    jQuery(selector).each(function() {
                        var $el = jQuery(this);
                        
                        // Skip if it's the default "Select Location" option
                        if ($el.is('option') && ($el.val() === '-1' || $el.val() === '')) {
                            return; // continue to next iteration
                        }
                        
                        // Check if element is currently visible (not hidden by other filters)
                        var isVisible = $el.is(':visible') && 
                                       !$el.hasClass('wcmlim-hide_out_of_stock_location') &&
                                       !$el.hasClass('hidden') &&
                                       $el.css('display') !== 'none';
                        
                        if (isVisible) {
                            visibleCount++;
                            
                            if (visibleCount > maxLocationCount) {
                                // Hide this location as it exceeds the maximum count
                                $el.addClass('wcmlim-max-count-hidden');
                                
                                if ($el.is('option')) {
                                    $el.prop('disabled', true).hide();
                                } else {
                                    $el.hide();
                                }
                            }
                        }
                    });
                });
                
                console.log('WCMLIM: Applied max location count of ' + maxLocationCount);
            }
            
            // Apply immediately on page load
            jQuery(document).ready(function() {
                // Small delay to ensure all other scripts have run
                setTimeout(wcmlimApplyMaxLocationCount, 100);
            });
            
            // Re-apply when variation stock updates complete (for variable products)
            jQuery(document).on('wcmlim_location_visibility_applied', function() {
                console.log('WCMLIM: Variation stock updated, applying max count...');
                setTimeout(wcmlimApplyMaxLocationCount, 100);
            });
            
            // Re-apply when location group changes
            jQuery(document).on('change', '.wcmlim-location-group-dropdown, #wcmlim-location-group', function() {
                console.log('WCMLIM: Location group changed, applying max count...');
                // Small delay to allow group filtering to complete
                setTimeout(wcmlimApplyMaxLocationCount, 200);
            });
        }
    })();
    </script>
    
    <?php
}
?>
