<?php
/**
 * Template: Three Column View
 * Description: This file handles the front-end rendering when using a three column view.
*/

// Ensure dashicons are loaded in frontend
wp_enqueue_style('dashicons');
?>
<div class="Wcmlim_container wcmlim_product wcmlim-threecol_view">
    <div class="Wcmlim_box_wrapper">
        <div class="Wcmlim_box_content simple_text_location-wrapper">
            <div class="Wcmlim_box_header">
                <h4 class="Wcmlim_box_title">
                    <?php
                    $display_text = get_option('wcmlim_location_display_heading_setting');
                    if ($hideDropdown != "on" && !empty($terms)) {
                        echo $display_text;
                    }
                    ?>
                </h4>
            </div>
            <?php

       $selected_location_termid = isset($_COOKIE['wcmlim_selected_location_termid']) ? intval($_COOKIE['wcmlim_selected_location_termid']) : null;

            // Get serialized field order for additional location information
            $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 location taxonomy terms associated with the product
            $priority_order = get_option('wcmlim_location_priority_order');
            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 (!empty($priority_order)) {
                uasort($terms, function($a, $b) use ($priority_order) {
                    $posA = array_search($a->term_id, $priority_order);
                    $posB = array_search($b->term_id, $priority_order);
                    $posA = ($posA === false) ? PHP_INT_MAX : $posA;
                    $posB = ($posB === false) ? PHP_INT_MAX : $posB;
                    return $posA - $posB;
                });
            }

            // Check if thresholds are enabled
            $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;
                }
            }
            ?>
            <?php
            // Add location group selector and mapping
            if ($isLocationsGroup == "on") {
                // Get all location groups
                $location_groups = get_terms(array(
                    'taxonomy' => 'location_group',
                    'hide_empty' => false
                ));
                
                // Create location group to locations mapping for JavaScript
                $group_locations_mapping = array();
                foreach ($location_groups as $group) {
                    $linked_locations = get_term_meta($group->term_id, 'wcmlim_location', true);
                    if (!empty($linked_locations)) {
                        if (is_string($linked_locations)) {
                            $linked_locations = unserialize($linked_locations);
                        }
                        $group_locations_mapping[$group->term_id] = $linked_locations;
                    }
                }
                
                // Display location group selector if groups exist
                if (!empty($location_groups)) {
                    ?>
                    <div class="wcmlim-location-group-selector">
                        <label for="wcmlim-location-group"><?php echo __('Select Location Group:', 'wcmlim'); ?></label>
                        <select id="wcmlim-location-group" class="wcmlim-location-group-dropdown">
                            <option value=""><?php echo __('-- Select a Location Group --', 'wcmlim'); ?></option>
                            <?php 
                            $hide_location_group = get_option('wcmlim_exclude_locations_group_frontend');

                            // Ensure $hide_location_group is an array
                            if (!is_array($hide_location_group)) {
                                $hide_location_group = array();
                            }

                            // Filter out the groups that are in $hide_location_group
                            $location_groups = array_filter($location_groups, function($group) use ($hide_location_group) {
                                return !in_array($group->term_id, $hide_location_group);
                            });

                            // Display the remaining groups
                            foreach ($location_groups as $group) : 
                            ?>
                                <option value="<?php echo esc_attr($group->term_id); ?>">
                                    <?php echo esc_html($group->name); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <script>
                        // Store group to locations mapping
                        var wcmlimGroupLocations = <?php echo json_encode($group_locations_mapping); ?>;
                    </script>
                    <?php
                }
            }

            // Add location group message
            if ($isLocationsGroup == "on"): ?>
            <div id="select-group-message" class="location-group-message">
                <?php echo __('Please select a Location Group to view stock details.', 'wcmlim'); ?>
            </div>
            <?php endif; 

            // Modify existing display logic to account for location groups
            if ($product->is_type('variable')) {
                // For variable products, add a class to handle visibility
                $variableMessageClass = ($isLocationsGroup == "on") ? ' hidden' : '';
                echo '<div id="variable-product-message" class="variable-product-message' . $variableMessageClass . '">Please select a variation to view stock details.</div>';
                
                // Add location-stock-item display settings for variable products
                $displayStyle = ($isLocationsGroup == "on") ? 'display: none;' : 'display: none;';
            }
            $wcmlim_hide_out_of_stock_location = get_option('wcmlim_hide_out_of_stock_location');
           
            
            ?>
             <style>
                        .wcmlim-hide_out_of_stock_location {
                            display: none;
                        }
                    </style>

          <div id="location-stock-text" class="location-stock-text-container three-col-location-container">
    <div class="location-stock-group" style="display: flex; flex-wrap: wrap; gap: 10px;">
        <?php
        // Loop through locations and create location cards
        foreach ($filtered_terms as $k => $term) {

            /**
             * Retrieve location index by term ID
             * 
             * This code fetches all location terms and then identifies the array key (index)
             * of the specific location that matches the current term ID. This ensures we 
             * maintain the correct reference index for the location term even when term order
             * or values have been modified in the database, which could otherwise affect results.
             * 
             * @since 4.2.1
             */
            $locations = get_terms([
                'taxonomy' => 'locations',
                'hide_empty' => false,
            ]);

            // Match current term with location to set key
            foreach ($locations as $location_key => $location) {
                if ($location->term_id == $term->term_id) {
                    $k = $location_key;
                    break;
                }
            }

            $hide_ind_location = get_term_meta($term->term_id, 'wcmlim_location_hide', true);
                        if($hide_ind_location == "yes") {
                            continue; // Skip this location if it is set to hide
                        }

            $default_location = get_option('wcmlim_enable_default_location');
            $default_location_set = get_post_meta($post->ID, 'wcmlim_default_location', true);
            if($product->is_type('simple')) {
                if($default_location == 'on') {
                    if (!empty($default_location_set)) {
                        $formatted_location_key = preg_replace('/[^0-9]/', '', $default_location_set);
                        
                        // Get term directly instead of looping through all locations
                        if (is_numeric($formatted_location_key)) {
                            if($formatted_location_key == $k) {
                                $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_location_termid = $cookie_termId;
                            }
                        }
                    }
                }
            } 
            // Check if it's a variable product
            if ($product->is_type('variable')) {
                // ONLY create variable product location items
                $varStyle = ($isLocationsGroup == "on") ? 'display:none;' : 'display:none;';
                
                // FIX: Initialize stock variable for variable products to avoid undefined variable error
                // For variable products, stock will be determined per variation, so we set a default value here
                $stock = 0;
                $stock_regular_price = get_post_meta($post->ID, "wcmlim_regular_price_at_{$term->term_id}", true);
                    $stock_sale_price = get_post_meta($post->ID, "wcmlim_sale_price_at_{$term->term_id}", true);
                    if ($stock_regular_price == '' || $stock_regular_price == '0.00') {
                        $stock_regular_price = wc_price($product->get_regular_price());
                        $stock_sale_price = wc_price($product->get_sale_price());
                    } 
                    if ( function_exists( 'wmc_get_price' ) ) {
                        $stock_regular_price = wmc_get_price( $stock_regular_price );
                        $stock_sale_price = wmc_get_price( $stock_sale_price );
                    }
                
                // Optionally, you can check if there's a base stock value for the variable product
                // $stock_location_quantity = get_post_meta($post->ID, "wcmlim_stock_at_{$term->term_id}", true);
                // $stock = !empty($stock_location_quantity) ? (int)$stock_location_quantity : 0;
                ?>
                <div class="location-stock-item variable-location-item" 
                    data-location-id="<?php echo $term->term_id; ?>" 
                    data-location-key="<?php echo $k; ?>"
                    style="<?php echo $varStyle; ?>">

                        <div style="display: none;">
                                    <input type="radio" name="select_location" id="select_location_<?php echo $k; ?>" value="<?php echo $k; ?>"
                                        data-lc-qty="<?php echo esc_attr(round(intval($stock))); ?>" data-lc-regular-price="<?php echo esc_attr(wc_price($stock_regular_price)); ?>"
                                                data-lc-sale-price="<?php echo (!empty($stock_sale_price)) ? esc_attr(wc_price($stock_sale_price)) : __('undefined', 'wcmlim'); ?>"
                                    
                                        class="wclimloc_<?php echo $term->slug; ?>"
                                        onchange="handleLocationChange(this)"
                                        style="margin-right: 10px;"
                                        <?php echo ($selected_location_termid === $term->term_id) ? 'checked' : ''; ?>>
                    </div>
                    
                    <div class="location-header">
                        <h3 class="location-name"><?php echo esc_html(ucfirst($term->name)); ?></h3>
                        <span class="stock-display">
                            <span class="wclim-views_subinfo">Loading...</span>
                        </span>
                    </div>
                    
                   
                    <!-- Location details for variable products -->
                    <div class="location-details variable-location-details">
                        <?php 
                        if (!empty($location_details_data[$term->term_id])) {
                            foreach ($location_details_data[$term->term_id] as $detail) {
                                echo '<div class="detail-row"><i class="' . esc_attr($detail['icon']) . '"></i><span class="wclim-views_font_size">' . esc_html($detail['content']) . '</span></div>';
                            }
                        }
                        ?>
                    </div>
                </div>
                <?php
            } 
            // ONLY create simple product location items for simple products
            else{
                // Simple product location item code
                $stock_location_quantity = get_post_meta($post->ID, "wcmlim_stock_at_{$term->term_id}", true);
                $stock = (int)$stock_location_quantity;
                $simpleStyle = ($isLocationsGroup == "on") ? 'display:none;' : '';
                $classname = (($wcmlim_hide_out_of_stock_location == "on" && $stock <= 0)) ? 'wcmlim-hide_out_of_stock_location' : '';
                $stock_regular_price = get_post_meta($post->ID, "wcmlim_regular_price_at_{$term->term_id}", true);
                    $stock_sale_price = get_post_meta($post->ID, "wcmlim_sale_price_at_{$term->term_id}", true);
                    if ($stock_regular_price == '' || $stock_regular_price == '0.00') {
                        $stock_regular_price = wc_price($product->get_regular_price());
                        $stock_sale_price = wc_price($product->get_sale_price());
                    } 
                    if ( function_exists( 'wmc_get_price' ) ) {
                        $stock_regular_price = wmc_get_price( $stock_regular_price );
                        $stock_sale_price = wmc_get_price( $stock_sale_price );
                    }
                
                // Determine stock display text and color
                $enable_css = get_option('wcmlim_custom_css_enable');
                $show_stock_count = get_option('wcmlim_hide_stock_count');
                if ($stock > 0) {
                    if (!empty($location_thresholds)) {
                        $threshold_text = null;
                        foreach ($location_thresholds as $threshold) {
                            if ($stock >= (int)$threshold['min'] && $stock <= (int)$threshold['max']) {
                                $threshold_text = $threshold['text'];
                                break;
                            }
                        }
                        $stock_text = $threshold_text ?: $stock . ' ' . __($instock_btntxt, 'wcmlim');
                        if ($show_stock_count == "on") {
                                $stock_text = $threshold_text ?: __($instock_btntxt, 'wcmlim');
                            }
                    } else {
                        $stock_text = $stock . ' ' . __($instock_btntxt, 'wcmlim');
                        if ($show_stock_count == "on") {
                            $stock_text = __($instock_btntxt, 'wcmlim');
                        }
                    }
                    if($enable_css == "on"){
                        $stock_color = 'green';
                    } else {
                        $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';
                        $stock_radius = get_option('wcmlim_instock_borderradius');
                        $stock_radius = $stock_radius ? $stock_radius: '0px';
                    }
                    
                } else {
                    $stock_text = __($soldout_btntxt, 'wcmlim');
                    if($enable_css == "on"){
                        $stock_color = 'red';
                    } else {
                        $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';
                        $stock_radius = get_option('wcmlim_soldout_borderradius');
                        $stock_radius = $stock_radius ? $stock_radius: '0px';
                    }
                    
                }

                // Check if backorders are allowed
                $isBackorderEnabled = get_post_meta($post->ID, "wcmlim_allow_backorder_at_$term->term_id", true);
                if ($product->backorders_allowed() && $isBackorderEnabled == "Yes") {
                    $stock_text = __($backorderbuttontext, 'woocommerce');
                    $stock_color = $backorder_btntxtcolor ? $backorder_btntxtcolor : '#212529';
                    $stock_bgcolor = $backorder_btnbgcolor ? $backorder_btnbgcolor : '#ffc107';
                    $stock_radius = $backorder_borderradius ? $backorder_borderradius : '0px';
                }

                 $allow_specific_location = get_post_meta($post->ID, 'wcmlim_allow_specific_location_at_' . $term->term_id, true);
                        $allow_specific_location = empty($allow_specific_location) ? 'Yes' : $allow_specific_location;

                        // Check if current user has access to this location
                        $user_has_access = true;
                        if ($allow_specific_location != 'Yes') {
                            $current_user = wp_get_current_user();
                            $user_specific_location = is_user_logged_in() ? get_user_meta($current_user->ID, 'wcmlim_user_specific_location', true) : "No";
                            if ($user_specific_location != $k && $user_specific_location != "No" && $user_specific_location != "-1") {
                                $user_has_access = false;
                            }
                        }
                        
                        if ($user_has_access) {
                            
                            // Set display style for simple products with location groups
                            $displayStyle = $isLocationsGroup == "on" ? 'display:none;' : '';
                            
                ?>
                <div class="location-stock-item <?php echo $classname; ?> <?php echo ($selected_location_termid === $term->term_id) ? 'highlighted' : ''; ?>" 
                    data-location-id="<?php echo $term->term_id; ?>" 
                    data-location-key="<?php echo $k; ?>"
                    style="<?php echo $simpleStyle; ?>">

                     <div style="display: none;">
                                    <input type="radio" name="select_location" id="select_location_<?php echo $k; ?>" value="<?php echo $k; ?>"
                                        data-lc-qty="<?php echo esc_attr(round(intval($stock))); ?>"
                                    
                                        class="wclimloc_<?php echo $term->slug; ?>"
                                        onchange="handleLocationChange(this)"
                                        style="margin-right: 10px;" data-lc-regular-price="<?php echo esc_attr(wc_price($stock_regular_price)); ?>"
                                                data-lc-sale-price="<?php echo (!empty($stock_sale_price)) ? esc_attr(wc_price($stock_sale_price)) : __('undefined', 'wcmlim'); ?>"
                                        <?php echo ($selected_location_termid === $term->term_id) ? 'checked' : ''; ?>>
                    </div>
                    
                    <div class="location-header">
                        <h3 class="location-name"><?php echo esc_html(ucfirst($term->name)); ?></h3>
                         <span class="stock-display" style="color: <?php if(isset($threshold_text) && $threshold_text != "") { echo $stock_color; } else { echo $stock_color; } ?>;background: <?php if(isset($threshold_text) && $threshold_text != "") { echo $stock_bgcolor; } else { echo $stock_bgcolor; } ?>;border-radius: <?php if(isset($threshold_text) && $threshold_text != "") { echo $stock_radius; } else { echo $stock_radius; } ?>;">
                                            <span class="wclim-views_subinfo"> <?php echo esc_html($stock_text);  ?> </span>
                        </span>
                    </div>
                    
                    <!-- Location details for simple products -->
                    <div class="location-details simple-location-details">
                        <?php 
                        if (!empty($location_details_data[$term->term_id])) {
                            foreach ($location_details_data[$term->term_id] as $detail) {
                                echo '<div class="detail-row"><i class="' . esc_attr($detail['icon']) . '" style="vertical-align: sub;"></i><span class="wclim-views_font_size">' . esc_html($detail['content']) . '</span></div>';
                            }
                        }
                        ?>
                    </div>
                </div>
                <?php
                        }
                    }
                }
            ?>
        </div>
    </div>

            <input type="hidden" id="lc_regular_price" name="location_regular_price" value="">
            <input type="hidden" id="lc_sale_price" name="location_sale_price" value="">
            <input type="hidden" id="lc_qty" name="location_qty" value="">
            <input type="hidden" id="wcstdis_format" name="stock_display_format" value="<?php esc_attr_e($stock_display_format); ?>">
            <input type="hidden" id="productOrgPrice" name="product_original_price" value="<?php esc_attr_e($product->get_price_html()); ?>">
            <input type="hidden" id="backorderAllowed" name="backorder_allowed" value="<?php echo esc_attr($product->backorders_allowed()); ?>">
        </div>
    </div>
</div>

<style>
    /* All your original CSS remains unchanged */
    .wcmlim-threecol_view .location-stock-group {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        width: 100%;
    }
    .location-stock-text-container {
        margin: 20px 0;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
    }

    .location-stock-item {
        padding: 15px;
        margin-bottom: 15px;
        border-radius: 5px;
        background-color: #f9f9f9;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
        transition: all 0.2s ease;
        border: 1px solid #eee;
        width: 31%;
        flex: 0 0 31%;
    }

    .location-stock-item:hover {
        transform: translateY(-3px);
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.15);
    }

    .location-stock-item.highlighted {
        background-color: #e8f5e9;
        border-left: 3px solid #4CAF50;
    }

    .stock-display {
        font-weight: 500;
        color: #000;
        background: #a2998c26;
        display: inline-block;
        padding: 5px 10px;
        border-radius: 3px;
        font-size: 12px;
        text-transform: capitalize;
    }

    .location-header {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        margin-bottom: 12px;
        padding-bottom: 8px;
        border-bottom: 1px solid #eee;
    }

    .Wcmlim_box_wrapper {
        margin-bottom: 30px;
    }
   
    .wclim-views_font_size {
        font-size: 14px;
        padding-left: 5px;
    }

    .location-name {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin: 0 0 8px 0 !important;
    }
    .wclim-views_subinfo {
        font-weight: 400;
    }

    .variable-product-message {
        font-style: italic;
        color: #666;
        padding: 10px 0;
    }
    
    /* Location details styles */
    .location-details {
        margin-top: 10px;
        padding-top: 5px;
    }
    
    @media (max-width: 992px) {
        .location-stock-item {
            width: 47%; 
            flex: 0 0 47%;
        }
    }
    
    @media (max-width: 768px) {
        .location-stock-item {
            width: 100%;
            flex: 0 0 100%;
        }
    }

    /* Enhanced Location Group Dropdown Styling for Variable Products */
    .product.type-product.product-type-variable .wcmlim-threecol_view .wcmlim-location-group-selector {
        margin-bottom: 20px;
        padding: 12px 15px;
        background-color: #f5f5f5;
        border-radius: 5px;
        border: 1px solid #e0e0e0;
        box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    }
    
    .product.type-product.product-type-variable .wcmlim-threecol_view .wcmlim-location-group-selector label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
        font-size: 14px;
        color: #333;
    }
    
    .product.type-product.product-type-variable .wcmlim-threecol_view .wcmlim-location-group-dropdown {
        width: 100%;
        padding: 10px 12px;
        height: auto;
        border-radius: 4px;
        border: 1px solid #ddd;
        background-color: #fff;
        font-size: 15px;
        color: #333;
        appearance: menulist;
        -webkit-appearance: menulist;
        cursor: pointer;
        transition: border-color 0.2s ease-in-out;
    }
    
    .product.type-product.product-type-variable .wcmlim-threecol_view .wcmlim-location-group-dropdown:focus {
        border-color: #a5c9e5;
        outline: none;
        box-shadow: 0 0 0 1px rgba(30, 140, 190, 0.2);
    }
    
    .product.type-product.product-type-variable .wcmlim-threecol_view .location-group-message {
        font-style: italic;
        color: #666;
        padding: 15px;
        background-color: #f8f8f8;
        border-radius: 4px;
        margin-bottom: 15px;
        text-align: center;
        border: 1px dashed #ddd;
    }
    
    /* Enhanced Location Group Dropdown Styling for Simple Products */
    .product.type-product.product-type-simple .wcmlim-threecol_view .wcmlim-location-group-selector {
        margin-bottom: 20px;
        padding: 12px 15px;
        background-color: #f5f5f5;
        border-radius: 5px;
        border: 1px solid #e0e0e0;
        box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    }
    
    .product.type-product.product-type-simple .wcmlim-threecol_view .wcmlim-location-group-selector label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
        font-size: 14px;
        color: #333;
    }
    
    .product.type-product.product-type-simple .wcmlim-threecol_view .wcmlim-location-group-dropdown {
        width: 100%;
        padding: 10px 12px;
        height: auto;
        border-radius: 4px;
        border: 1px solid #ddd;
        background-color: #fff;
        font-size: 15px;
        color: #333;
        appearance: menulist;
        -webkit-appearance: menulist;
        cursor: pointer;
        transition: border-color 0.2s ease-in-out;
    }
    
    .product.type-product.product-type-simple .wcmlim-threecol_view .wcmlim-location-group-dropdown:focus {
        border-color: #a5c9e5;
        outline: none;
        box-shadow: 0 0 0 1px rgba(30, 140, 190, 0.2);
    }
    
    .product.type-product.product-type-simple .wcmlim-threecol_view .location-group-message {
        font-style: italic;
        color: #666;
        padding: 15px;
        background-color: #f8f8f8;
        border-radius: 4px;
        margin-bottom: 15px;
        text-align: center;
        border: 1px dashed #ddd;
    }
</style>

<?php
// Make sure views.js is loaded
wp_enqueue_script('wcmlim-views-script');
?>



