<?php
/**
 * Location Archive Pricing Handler
 * Sets location cookies and applies location-specific pricing on location taxonomy archive pages
 */

// Hook into WordPress to detect location archive pages
add_action('template_redirect', 'wcmlim_handle_location_archive');

function wcmlim_handle_location_archive() {
    // Only run on location taxonomy archive pages
    if (is_tax('locations')) {
        $current_location = get_queried_object();
        
        if ($current_location) {
            // Check if this location is excluded from frontend
            $excluded_locations = get_option('wcmlim_exclude_locations_from_frontend');
            if (!empty($excluded_locations) && is_array($excluded_locations) && in_array($current_location->term_id, $excluded_locations)) {
                // Before redirecting, check if we have wcmlim_selected_location_termid and set proper cookies
                $selected_termid = isset($_COOKIE['wcmlim_selected_location_termid']) ? $_COOKIE['wcmlim_selected_location_termid'] : '';
                
                if (!empty($selected_termid)) {
                    // Get all locations to find the index
                    $locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
                    $cookie_time = time() + (30 * 24 * 60 * 60); // 30 days
                    
                    foreach ($locations as $key => $location) {
                        if ($location->term_id == $selected_termid) {
                            // Set wcmlim_selected_location with the index
                            setcookie('wcmlim_selected_location', $key, $cookie_time, '/');
                            
                            // Set wcmlim_nearby_location with location data
                            $location_address = get_term_meta($selected_termid, 'wcmlim_street_address', true);
                            $location_city = get_term_meta($selected_termid, 'wcmlim_city', true);
                            $location_state = get_term_meta($selected_termid, 'wcmlim_state', true);
                            $location_postcode = get_term_meta($selected_termid, 'wcmlim_postcode', true);
                            
                            // Combine location info for nearby_location cookie
                            $nearby_location_parts = array_filter([$location_city, $location_state, $location_postcode]);
                            $nearby_location = implode('%20', $nearby_location_parts);
                            
                            if (!empty($nearby_location)) {
                                setcookie('wcmlim_nearby_location', $nearby_location, $cookie_time, '/');
                            }
                            break;
                        }
                    }
                }
                
                // Location is hidden from frontend, redirect to shop page
                wp_redirect(wc_get_page_permalink('shop'));
                exit;
            }
            
            // Check if cookies are already set for this location to avoid infinite reload
            $current_cookie_termid = isset($_COOKIE['wcmlim_selected_location_termid']) ? $_COOKIE['wcmlim_selected_location_termid'] : '';
            
            // If cookies are not set or different location, set them and reload
            if ($current_cookie_termid != $current_location->term_id) {
                // Set the location cookies that the plugin uses
                $cookie_time = time() + (30 * 24 * 60 * 60); // 30 days
                setcookie('wcmlim_selected_location_termid', $current_location->term_id, $cookie_time, '/');
                
                // Find the location index for wcmlim_selected_location cookie
                $locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
                foreach ($locations as $key => $location) {
                    if ($location->term_id == $current_location->term_id) {
                        setcookie('wcmlim_selected_location', $key, $cookie_time, '/');
                        break;
                    }
                }
                
                // Reload the page once after setting cookies
                wp_redirect($_SERVER['REQUEST_URI']);
                exit;
            }
            
            // Apply location-specific pricing filters (only after cookies are set)
            add_filter('woocommerce_get_price_html', 'wcmlim_location_price_html', 20, 2); // Higher priority
            add_filter('woocommerce_product_get_price', 'wcmlim_location_get_price', 10, 2);
            add_filter('woocommerce_product_get_regular_price', 'wcmlim_location_get_regular_price', 10, 2);
            add_filter('woocommerce_product_get_sale_price', 'wcmlim_location_get_sale_price', 10, 2);
            
            // For variable products
            add_filter('woocommerce_product_variation_get_price', 'wcmlim_location_get_price', 10, 2);
            add_filter('woocommerce_product_variation_get_regular_price', 'wcmlim_location_get_regular_price', 10, 2);
            add_filter('woocommerce_product_variation_get_sale_price', 'wcmlim_location_get_sale_price', 10, 2);
            add_filter('woocommerce_variation_get_price_html', 'wcmlim_location_price_html', 20, 2); // Higher priority
        }
    }
}

// Price HTML filter - shows location-specific pricing or falls back to regular pricing
function wcmlim_location_price_html($price_html, $product) {
    $current_location = get_queried_object();
    if (!$current_location || $current_location->taxonomy !== 'locations') {
        return $price_html;
    }
    
    $location_id = $current_location->term_id;
    $product_id = $product->get_id();
    
    // Handle variable products
    if ($product->is_type('variable')) {
        $variations = $product->get_available_variations();
        $variations_id = wp_list_pluck($variations, 'variation_id');
        
        $locRP = array();
        $locSP = array();
        
        foreach ($variations_id as $var_id) {
            $rp = get_post_meta($var_id, "wcmlim_regular_price_at_{$location_id}", true);
            $sp = get_post_meta($var_id, "wcmlim_sale_price_at_{$location_id}", true);
            
            if (!empty($rp)) $locRP[] = floatval($rp);
            if (!empty($sp)) $locSP[] = floatval($sp);
        }
        
        if (!empty($locRP)) {
            $locRP = array_unique($locRP);
            sort($locRP);
            $cp = (int)count($locRP) - 1;
            
            if (function_exists('wmc_get_price')) {
                $rminPrice = wmc_get_price($locRP[0]);
                $rmaxPrice = wmc_get_price($locRP[$cp]);
            } else {
                $rminPrice = wc_price($locRP[0]);
                $rmaxPrice = wc_price($locRP[$cp]);
            }
            
            if (!empty($locSP)) {
                $locSP = array_unique($locSP);
                sort($locSP);
                $cps = (int)count($locSP) - 1;
                
                if (function_exists('wmc_get_price')) {
                    $sminPrice = wmc_get_price($locSP[0]);
                    $smaxPrice = wmc_get_price($locSP[$cps]);
                } else {
                    $sminPrice = wc_price($locSP[0]);
                    $smaxPrice = wc_price($locSP[$cps]);
                }
                
                if ($locRP[0] == $locRP[$cp] && $locSP[0] == $locSP[$cps]) {
                    // Same prices across variations
                    return "<del>{$rminPrice}</del><ins>{$sminPrice}</ins>";
                } else {
                    // Price range with sale prices
                    return "<del>{$rminPrice} - {$rmaxPrice}</del><ins>{$sminPrice} - {$smaxPrice}</ins>";
                }
            } else {
                if ($locRP[0] == $locRP[$cp]) {
                    // Same price across variations
                    return $rminPrice;
                } else {
                    // Price range
                    return "{$rminPrice} - {$rmaxPrice}";
                }
            }
        }
        
        // No location-specific prices for variable product, return original
        return $price_html;
    }
    
    // Handle simple products
    $location_regular_price = get_post_meta($product_id, "wcmlim_regular_price_at_{$location_id}", true);
    $location_sale_price = get_post_meta($product_id, "wcmlim_sale_price_at_{$location_id}", true);
    
    // If location prices exist, use them; otherwise use regular WooCommerce pricing
    if (!empty($location_regular_price) || !empty($location_sale_price)) {
        if (!empty($location_sale_price)) {
            // Sale price exists - show crossed out regular price and sale price
            $regular_formatted = function_exists('wmc_get_price') ? wmc_get_price($location_regular_price) : wc_price($location_regular_price);
            $sale_formatted = function_exists('wmc_get_price') ? wmc_get_price($location_sale_price) : wc_price($location_sale_price);
            return "<del>{$regular_formatted}</del><ins>{$sale_formatted}</ins>";
        } elseif (!empty($location_regular_price)) {
            // Only regular price exists
            return function_exists('wmc_get_price') ? wmc_get_price($location_regular_price) : wc_price($location_regular_price);
        }
    }
    
    // No location-specific pricing - return original price
    return $price_html;
}

// Get location-specific price or fall back to default
function wcmlim_location_get_price($price, $product) {
    return wcmlim_get_location_specific_price($price, $product, 'price');
}

function wcmlim_location_get_regular_price($price, $product) {
    return wcmlim_get_location_specific_price($price, $product, 'regular_price');
}

function wcmlim_location_get_sale_price($price, $product) {
    return wcmlim_get_location_specific_price($price, $product, 'sale_price');
}

// Helper function to get location-specific pricing
function wcmlim_get_location_specific_price($default_price, $product, $price_type) {
    $current_location = get_queried_object();
    if (!$current_location || $current_location->taxonomy !== 'locations') {
        return $default_price;
    }
    
    $location_id = $current_location->term_id;
    $product_id = $product->get_id();
    
    // Get the appropriate location-specific price
    switch ($price_type) {
        case 'regular_price':
            $location_price = get_post_meta($product_id, "wcmlim_regular_price_at_{$location_id}", true);
            break;
        case 'sale_price':
            $location_price = get_post_meta($product_id, "wcmlim_sale_price_at_{$location_id}", true);
            break;
        case 'price':
            // For current price, check sale first, then regular
            $sale_price = get_post_meta($product_id, "wcmlim_sale_price_at_{$location_id}", true);
            if (!empty($sale_price)) {
                $location_price = $sale_price;
            } else {
                $location_price = get_post_meta($product_id, "wcmlim_regular_price_at_{$location_id}", true);
            }
            break;
        default:
            $location_price = '';
    }
    
    // Return location price if it exists, otherwise return default price
    return !empty($location_price) ? $location_price : $default_price;
}
