<?php
/**
 * AJAX handler class for WooCommerce Multi Locations Inventory Management
 */
class WCMLIM_Ajax {
    
    /**
     * Constructor for the AJAX handler class
     */
    public function __construct() {
        // Register AJAX actions
        add_action('wp_ajax_wcmlim_get_variation_location_stock', array($this, 'get_variation_location_stock'));
        add_action('wp_ajax_nopriv_wcmlim_get_variation_location_stock', array($this, 'get_variation_location_stock'));

        // Register AJAX action for triggering location price
        add_action('wp_ajax_wcmlim_trigger_location_price', array($this, 'wcmlim_trigger_location_price'));
        add_action('wp_ajax_nopriv_wcmlim_trigger_location_price', array($this, 'wcmlim_trigger_location_price'));

    }

    /**
     * Trigger location price
     * This function is called via AJAX to get the selected location term ID from the cookie
     */
    function wcmlim_trigger_location_price() {
        // Check nonce for security if needed
        check_ajax_referer('wcmlim_locations_nonce', 'security');

        if(isset($_POST['security']) && !wp_verify_nonce($_POST['security'], 'wcmlim_locations_nonce')) {
            wp_send_json(array(
                'success' => false,
                'message' => 'Invalid nonce'
            ));
            return;
        }
        // get the cookie
        $selected_location = getLocation('wcmlim_selected_location_termid');
        // echo $selected_location;
        wp_send_json_success($selected_location);
        return;
    }
    
    /**
     * Get stock information for a specific variation at a specific location
     */
    public function get_variation_location_stock() {
        // Check nonce if needed
        check_ajax_referer('wcmlim_locations_nonce', 'security');
        
        if(isset($_POST['security']) && !wp_verify_nonce($_POST['security'], 'wcmlim_locations_nonce')) {
            wp_send_json(array(
                'success' => false,
                'message' => 'Invalid nonce'
            ));
            return;
	    }

        $variation_id = isset($_POST['variation_id']) ? intval($_POST['variation_id']) : 0;
        $location_id = isset($_POST['location_id']) ? intval($_POST['location_id']) : 0;

        if (!$variation_id || !$location_id) {
            wp_send_json_error(array('message' => 'Missing required parameters'));
            return;
        }

        $default_location = get_option('wcmlim_enable_default_location');
        $default_location_set = get_post_meta($variation_id, 'wcmlim_default_location', true);
        $selected_location_termid = '';
        $selected_loc_key = '';
		if($default_location == 'on') {
			if (!empty($default_location_set)) {
				$formatted_location_key = preg_replace('/[^0-9]/', '', $default_location_set);
				$terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
				// Get term directly instead of looping through all locations
				if (is_numeric($formatted_location_key)) {
					foreach ($terms as $index => $term) {
						if($formatted_location_key == $index) {
							$loc_key = $formatted_location_key;
							$termid = $term->term_id;
							// Set the location cookies
							setLocation("wcmlim_selected_location", $loc_key, 36000);
							setLocation("wcmlim_selected_location_termid", $termid, 36000);
                            
                            // Re-fetch cookies using getLocation()
                            $selected_store = getLocation('wcmlim_selected_location') ?: "";
                            $cookie_termId = getLocation('wcmlim_selected_location_termid') ?: "";
                            
                            // Set selected location term ID for display
                            $selected_loc_key = $selected_store;
                            $selected_location_termid = $cookie_termId;
						} 
					}
				}
			} else {
                setLocation("wcmlim_selected_location", "", 36000);
                setLocation("wcmlim_selected_location_termid", "", 36000);
            }
		}
        
        // Get stock quantity for this variation at this location
        $stock_location_quantity = get_post_meta($variation_id, "wcmlim_stock_at_{$location_id}", true);
        $wcmlim_hide_out_of_stock_location = get_option('wcmlim_hide_out_of_stock_location');
        
        // Check if this location is actually linked to this variation
        $linked_terms = wp_get_object_terms($variation_id, 'locations', array('fields' => 'ids'));
        $is_location_linked = in_array($location_id, $linked_terms);
        
        // If location is not linked to this variation, check parent product
        if (!$is_location_linked) {
            $variation = wc_get_product($variation_id);
            if ($variation && $variation->get_parent_id()) {
                $parent_linked_terms = wp_get_object_terms($variation->get_parent_id(), 'locations', array('fields' => 'ids'));
                $is_location_linked = in_array($location_id, $parent_linked_terms);
            }
        }
        
        // Note: We removed the early return here to allow frontend to handle hiding
        // The frontend will use the should_hide_location flag to determine visibility 
        
        // Get price information
        $stock_regular_price = get_post_meta($variation_id, "wcmlim_regular_price_at_{$location_id}", true);
        $stock_sale_price = get_post_meta($variation_id, "wcmlim_sale_price_at_{$location_id}", true);
        if ( function_exists( 'wmc_get_price' ) ) {
            $stock_regular_price = wc_price(wmc_get_price( $stock_regular_price ));
            $stock_sale_price = wc_price(wmc_get_price( $stock_sale_price ));
        }
        
        // Check if backorders are allowed
        $variation = wc_get_product($variation_id);
        $isBackorderEnabled = get_post_meta($variation_id, "wcmlim_allow_backorder_at_{$location_id}", true);
        $backorder_allowed = $variation && $variation->backorders_allowed() && ($isBackorderEnabled == "Yes");
        
        // Format stock display text
        if ($backorder_allowed) {
            $stock_text = __('Available on backorder', 'woocommerce');
            $stock_color = 'orange';
        } else if (empty($stock_location_quantity) || $stock_location_quantity <= 0) {
            $stocktext = get_option('wcmlim_soldout_button_text');
            if($stocktext) {
                $stock_text = $stocktext;
            } else {
                $stock_text = __('Out of stock', 'woocommerce');
            }
            $stock_color_set = get_option('wcmlim_soldout_button_text_color');
            $stock_color = $stock_color_set ? $stock_color_set: 'red';
            $stock_bgcolor_set = get_option('wcmlim_soldout_button_color');
            $stock_bgcolor = $stock_bgcolor_set ? $stock_bgcolor_set: '#a2998c26';
        } else {
            // Check if thresholds are enabled
            $enable_threshold = get_option('wcmlim_enable_location_thresholds');
            $display_text = $stock_location_quantity;
            
            if ($enable_threshold == "on") {
                $thresholds = maybe_unserialize(get_option('wcmlim_location_thresholds'));
                if (is_array($thresholds)) {
                    foreach ($thresholds as $threshold) {
                        if ((int)$stock_location_quantity >= (int)$threshold['min'] && (int)$stock_location_quantity <= (int)$threshold['max']) {
                            $display_text = $threshold['text'];
                            break;
                        }
                    }
                }

                $stock_text = $display_text;
                $stock_color_set = get_option('wcmlim_instock_button_text_color');
                $stock_color = $stock_color_set ? $stock_color_set: 'green'; 
                $stock_bgcolor_set = get_option('wcmlim_instock_button_color');
                $stock_bgcolor = $stock_bgcolor_set ? $stock_bgcolor_set: '#a2998c26';
            } else {
                $stocktext = get_option('wcmlim_instock_button_text');
                if($stocktext) {
                    $stock_text = $stock_location_quantity . ' ' . $stocktext;
                } else {
                    $stock_text = $stock_location_quantity . ' ' . __('In stock', 'woocommerce'); 
                }
                           
                $stock_color_set = get_option('wcmlim_instock_button_text_color');
                $stock_color = $stock_color_set ? $stock_color_set: 'green'; 
                $stock_bgcolor_set = get_option('wcmlim_instock_button_color');
                $stock_bgcolor = $stock_bgcolor_set ? $stock_bgcolor_set: '#a2998c26';
            }
        }
        
        // Group location fields by category
        $address_fields = array();
        $contact_fields = array();
        $timing_fields = array();
        
        // Get the field order from options
        $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 and categorize field values
        foreach ($field_order as $field) {
            if ($field == 'postcode') {
                $field = 'postal_code';
            }
            
            $field_value = get_term_meta($location_id, 'wcmlim_' . $field, true);
             $loc_note = get_term_meta($location_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;
                                    }
            }
        }
        
        // Format grouped location fields
        $location_fields = array();
        
        // Format address fields
        if (!empty($address_fields)) {
            $location_fields['address'] = implode(', ', $address_fields);
        }
        
        // Format contact fields
        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'];
            }
            $location_fields['contact'] = implode(' | ', $contact_str);
        }
        
        // Format timing fields
        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'];
            }
            $location_fields['timing'] = implode(' | ', $timing_str);
        }
        
        // Add distance field only if it's enabled in the field order
        if (in_array('distance', $field_order)) {
            $location_fields['distance'] = wcmlim_get_distance_to_location($location_id);
        }

        // Determine if location should be hidden
        // Hide if: 1) Location is not linked to this variation/product, OR
        //          2) Hide out of stock option is on AND stock is 0 or empty
        $should_hide_location = !$is_location_linked || 
                               ($wcmlim_hide_out_of_stock_location == 'on' && (empty($stock_location_quantity) || $stock_location_quantity <= 0));
        
        // Return response with stock data and location fields
        wp_send_json_success(array(
            'stock_text' => $stock_text,
            'stock_color' => $stock_color, 
            'stock_qty' => $stock_location_quantity,
            'regular_price' => $stock_regular_price,
            'sale_price' => $stock_sale_price,
            'location_fields' => $location_fields,
            'location_note' => isset($note_field) ? $note_field : '',
            'selected_location_termid' => $selected_location_termid,
            'selected_loc_key' => $selected_loc_key,
            'stock_bgcolor' => $stock_bgcolor,
            'stock_radius' => isset($stock_radius) ? $stock_radius : '',
            'wcmlim_hide_out_of_stock_location' => $wcmlim_hide_out_of_stock_location,
            'stock_location_quantity' => $stock_location_quantity,
            'data_location_id' => $location_id,
            'should_hide_location' => $should_hide_location,
            'is_location_linked' => $is_location_linked,
        ));
    }
}

// Initialize the class
new WCMLIM_Ajax();
