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

$display_text = get_option('wcmlim_location_display_heading_setting');
?>
<style>
                        .wcmlim-hide_out_of_stock_location {
                            display: none;
                        }
                    </style>
<div class="Wcmlim_container wcmlim_product wcmlim-popup_view">
    <div class="Wcmlim_box_wrapper">
        <div class="Wcmlim_box_content popup_text_location-wrapper">
            <div class="wcmlim-popup_content_sec">
                <button type="button" id="wcmlim-popup_view_btn"><?php echo $display_text; ?></button>
            </div>
            <div id="wcmlim-modalPopup" class="wcmlim-modal_popup">
                <div class="wcmlim-modal_content">
                    <div class="Wcmlim_box_header">
                        <h4 class="Wcmlim_box_title">
                            <?php
                            if ($hideDropdown != "on" && !empty($terms)) {
                                echo $display_text;
                            }
                            ?>
                        </h4>
                        <button type="button" id="wcmlim-closePopupBtn" class="wcmlim-close_btn">&times;</button>
                    </div>
                    <?php
                    // 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="popup-location-container" class="popup-location-container">
                    <?php
                            $i = 0;
                            $total = count($filtered_terms);
                            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;
                                                }
                                            }
                                        }
                                    }
                                }
                                // Only process odd-indexed items for right column
                                if ($i % 2 == 0) {
                                    echo '<div class="">';
                                }
                                    $enable_css = get_option('wcmlim_custom_css_enable');
                                    $show_stock_count = get_option('wcmlim_hide_stock_count');
                                    $stock_location_quantity = get_post_meta($post->ID, "wcmlim_stock_at_{$term->term_id}", true);
                                    $stock = (int)$stock_location_quantity;
                                    $wcmlim_hide_out_of_stock_location = get_option('wcmlim_hide_out_of_stock_location');
                    if($product->is_type('simple')) {
                        $classname = (($wcmlim_hide_out_of_stock_location == "on" && $stock <= 0)) ? 'wcmlim-hide_out_of_stock_location' : '';
                    } else {
                        $classname = '';
                    }
                                    $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';
                                    }
                                    
                                    $displayStyle = $product->is_type('variable') || ($isLocationsGroup == "on") ? 'display:none;' : '';
                                    $selected_location_termid = isset($_COOKIE['wcmlim_selected_location_termid']) ? intval($_COOKIE['wcmlim_selected_location_termid']) : null;
                                    
                                    // Render location item
                                    ?>
                                    <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 $displayStyle; ?>">
                                        <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>
                                        
                                        <div class="location-details">
                                            <?php 
                                            if (!empty($location_details_data[$term->term_id])) {
                                                foreach ($location_details_data[$term->term_id] as $detail) {
                                                    echo '<span class="' . esc_attr($detail['icon']) . '" style="vertical-align: sub;"></span><span class="wclim-views_font_size">' . esc_html($detail['content']) . '</span> <br>';
                                                }
                                            }
                                            ?>
                                        </div>
                                    </div>
                                    <?php
                                if ($i % 2 == 1 || $i == $total - 1) {
                                    echo '</div>'; // Close .location-row
                                }
                                $i++;
                            }
                            ?>
                    </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>
    </div>
</div>

<style>
    .Wcmlim_box_header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-top: 0 !important;
        padding-right: 20px !important;
        padding-left: 20px !important;
        background: #e9e9e97a;
    }
    .location-header {
        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 .dashicons {
        width: 24px;
        height: 24px;
        font-size: 18px;
        display: inline;
        line-height: unset;
    }
    .wclim-views_subinfo {
        padding-left: 5px;
        padding-right: 5px;
        font-weight: 400;
    }
    .wclim-views_font_size {
        font-size: 14px;
    }

    .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;
    }

    #popup-location-container {
        padding: 20px;
    }

    .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-details p,
    ..location-details span {
        margin: 8px 0;
        font-size: 14px;
        line-height: 1.4;
        color: #6d6d6d;
    }

    /* 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%;
    }
    .Wcmlim_box_wrapper {
        margin-bottom: 30px;
    }

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

    .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);
    }

    #wcmlim-popup_view_btn {
        font-size: 16px;
        cursor: pointer;
    }

    .extra-details p {
        margin: 0;
    }

    .wcmlim-modal_popup {
        display: none; 
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5); 
        z-index: 999999;
        justify-content: center;
        align-items: center;
    }

    .wcmlim-modal_content {
        background-color: white;
        width: 80%; 
        max-width: 600px;
        max-height: 90%;
        overflow-y: auto; 
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    .wcmlim-close_btn {
        font-size: 36px;
        color: #000;
        border: none;
        background: none;
        padding: 0;
        cursor: pointer;
    }


    .wcmlim-close_btn:hover {
        background-color: #fff;
        border-color: #fff;
        color: #333333;
    }
</style>

<script>
    const openPopupBtn = document.getElementById('wcmlim-popup_view_btn');
    const modalPopup = document.getElementById('wcmlim-modalPopup');
    const closePopupBtn = document.getElementById('wcmlim-closePopupBtn');

    // Open the modal when the button is clicked
    openPopupBtn.onclick = function() {
        modalPopup.style.display = 'flex'; // Show the modal
    };

    // Close the modal when the close button is clicked
    closePopupBtn.onclick = function() {
        modalPopup.style.display = 'none'; // Hide the modal
    };

    // Close the modal when clicking outside of it
    window.onclick = function(event) {
        if (event.target === modalPopup) {
            modalPopup.style.display = 'none';
        }
    };
</script>