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

// Ensure dashicons are loaded in frontend
wp_enqueue_style('dashicons');
?>
<div class="Wcmlim_container wcmlim_product wcmlim-twocol_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
            // Get selected location from cookie if it exists
            $selected_location_termid = isset($_COOKIE['wcmlim_selected_location_termid']) ? intval($_COOKIE['wcmlim_selected_location_termid']) : null;
            // Check if location group option is enabled
            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
                }
            }

            ?>
            
            <?php 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; ?>
            
            <?php 
            // Show variable product message if applicable
            if ($product->is_type('variable')) : ?>
            <div id="variable-product-message" class="location-group-message" <?php echo ($isLocationsGroup == "on") ? 'style="display:none;"' : ''; ?>>
                <?php echo __('Please select a variation to view stock details.', 'wcmlim'); ?>
            </div>
            <?php endif; ?>

         <div id="two-col-location-container" class="two-col-location-container">
            <div class="location-column">
                <?php
                // Loop through terms and divide them into left and right columns
                foreach ($filtered_terms as $index => $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) {
                            $index = $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 == $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_location_termid = $cookie_termId;
                                    }
                                }
                            }
                        }
                    } 
                    
                    
                    $stock_location_quantity = get_post_meta($post->ID, "wcmlim_stock_at_{$term->term_id}", true);
                    $stock = (int)$stock_location_quantity;
                    $enable_css = get_option('wcmlim_custom_css_enable');
                    $show_stock_count = get_option('wcmlim_hide_stock_count');
                    $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
                    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 : 'orange';
                        $stock_bgcolor = $backorder_btnbgcolor ? $backorder_btnbgcolor : '#f0ad4e';
                        $stock_radius = $backorder_borderradius ? $backorder_borderradius : '0px';
                    }

                    $wcmlim_hide_out_of_stock_location = get_option('wcmlim_hide_out_of_stock_location');
                    $displayStyle = ($isLocationsGroup == "on" || ($wcmlim_hide_out_of_stock_location == "on" && $stock <= 0)) ? 'none;' : '';
                    if($product->is_type('simple')) {
                        $classname = (($wcmlim_hide_out_of_stock_location == "on" && $stock <= 0)) ? 'wcmlim-hide_out_of_stock_location' : '';
                    } else {
                        $classname = '';
                    }
                    
                    ?>
                    <style>
                        .wcmlim-hide_out_of_stock_location {
                            display: none;
                        }
                    </style>
                    
                        <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 $index; ?>"
                            style="display:<?php echo $displayStyle; ?>" >
 
                            <div style="display: none;">
                                <input type="radio" name="select_location" id="select_location_<?php echo $index; ?>" value="<?php echo $index; ?>"
                                    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>
                            
                            <div class="location-details">
                                <?php 
                                if (!empty($location_details_data[$term->term_id])) {
                                    foreach ($location_details_data[$term->term_id] as $detail) {
                                        $content = isset($detail['is_html']) && $detail['is_html'] 
                                            ? $detail['content'] 
                                            : esc_html($detail['content']);
                                        echo '<div class="location-detail-item"><i class="' . esc_attr($detail['icon']) . '" style="vertical-align: sub;"></i> <span>' . $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>
    .wclim-views_subinfo {
        padding-left: 5px;
        padding-right: 5px;
        font-weight: 400;
    }
    .wclim-views_font_size {
        font-size: 14px;
    }
/* Base container styles */
.Wcmlim_container.wcmlim_product.wcmlim-twocol_view {
    width: 100%;
    max-width: 100%;
    margin: 0 0 1.5em 0;
    box-sizing: border-box;
}

.Wcmlim_box_content {
    width: 100%;
}

/* Location Group Selector Styles */
.wcmlim-location-group-selector {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f7f7f7;
    border-radius: 5px;
    border: 1px solid #e0e0e0;
}
.Wcmlim_box_wrapper {
    margin-bottom: 30px;
}

.wcmlim-location-group-selector label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
}

.wcmlim-location-group-dropdown {
    width: 100%;
    padding: 10px;
    border-radius: 4px;
    border: 1px solid #ddd;
    background-color: #fff;
    font-size: 15px;
    color: #333;
    height: auto;
    min-height: 42px;
}

/* Message Styles */
.location-group-message {
    font-style: italic;
    color: #666;
    padding: 15px;
    text-align: center;
    background-color: #f8f8f8;
    border-radius: 5px;
    margin: 15px 0;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

/* Two Column Layout Styles */
.two-col-location-container {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin: 15px 0;
    width: 100%;
}
.wcmlim-twocol_view .location-stock-group {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 10px;
    }
.location-column {
    display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 10px;
}

/* Location Item Styles */
.location-stock-item {
    padding: 10px;
    margin-bottom: 15px;
    border-radius: 5px;
    background-color: #f9f9f9;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: all 0.2s ease;
    border: 1px solid #eee;
}

.location-stock-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

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

.location-header {
    /* display: flex;
    justify-content: space-between; */
    align-items: center;
    padding-bottom: 10px;
}

.location-name {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

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

.location-details p {
    margin: 8px 0;
    font-size: 14px;
    line-height: 1.4;
}

/* Mobile Responsiveness */
@media (max-width: 768px) {
    .two-col-location-container {
        flex-direction: column;
        gap: 10px;
    }
    
    .location-column {
        width: 100%;
        min-width: 100%;
    }
    
    .location-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .stock-display {
        margin-top: 8px;
    }
}
</style>


<script type="text/javascript">
jQuery(document).ready(function($) {
    // Handle location item click to select the radio button
    $('.location-stock-item').on('click', function() {
        var locationKey = $(this).data('location-key');
        
        // Select the corresponding radio button
        $('#select_location_' + locationKey).prop('checked', true).trigger('change');
        
        // Highlight the selected location
        $('.location-stock-item').removeClass('highlighted');
        $(this).addClass('highlighted');
    });
    
    // Function to handle location change - ensure this is defined globally
    window.handleLocationChange = function(radioElement) {
        // If function is already defined somewhere else, this won't override it
        if (typeof(originalHandleLocationChange) === "function") {
            originalHandleLocationChange(radioElement);
        } else {
            // Basic location change handling
            var locationKey = $(radioElement).val();
            var locationId = $('.location-stock-item[data-location-key="' + locationKey + '"]').data('location-id');
            
            // Set cookie with the selected location
            document.cookie = "wcmlim_selected_location_termid=" + locationId + "; path=/";
            
            // You might want to update quantity fields or other elements here
            var locationQty = $(radioElement).data('lc-qty');
            $('#lc_qty').val(locationQty);
            
            // Add any additional logic you need for location selection
        }
    };
});
</script>

