<?php
/**
 * Template: Simple Text View
 * This file handles the front-end rendering when using a simple text view.
 */

// Ensure dashicons are loaded in frontend
wp_enqueue_style('dashicons');
?>
<style>
.wcmlim-hide_out_of_stock_location {
    display: none !important;
}
</style>
<div class="Wcmlim_container wcmlim_product">
    <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
            // 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
                }
            }
            ?>
            
            <div id="location-stock-text" class="location-stock-text-container">
                <?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 
                $wcmlim_hide_out_of_stock_location = get_option('wcmlim_hide_out_of_stock_location');
                if ($product->is_type('variable')) {
                    // Variable Product Logic
                    echo '<div class="variable-product-message">Please select a variation to view stock details.</div>';
                    
                    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
                        }
                        ?>
                        <div class="location-stock-item" 
                            data-location-id="<?php echo $term->term_id; ?>" 
                            data-location-key="<?php echo $k; ?>"
                            style="display: none;">

                            <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;"
                                        <?php echo ($selected_location_termid === $term->term_id) ? 'checked' : ''; ?>>
                                </div>
                                
                            <div class="location-header">
                                <span class="location-name"><?php echo esc_html(ucfirst($term->name)); ?></span> 
                                <span class="stock-display" style="color: grey;"><span class="wclim-views_subinfo">Loading...</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 class="wclim-views_font_size">' . $content . '</span></div>';
                                    }
                                }
                                ?>
                            </div>
                        </div>
                        <?php
                    }
                } else { 
                    // Simple Product Logic
                    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($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;
                                        }
                                    }
                                }
                            }

                        $stock_location_quantity = get_post_meta($post->ID, "wcmlim_stock_at_{$term->term_id}", true);
                        $stock = (int)$stock_location_quantity;
                        $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 );
                        }
                        $enable_css = get_option('wcmlim_custom_css_enable');
                        $show_stock_count = get_option('wcmlim_hide_stock_count');
                        // 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 : '#212529';
                            $stock_bgcolor = $backorder_btnbgcolor ? $backorder_btnbgcolor : '#ffc107';
                            $stock_radius = $backorder_borderradius ? $backorder_borderradius : '0px';
                        }
                        
                        // Get allowed specific locations
                        $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) {
                            $selected_location_termid = isset($_COOKIE['wcmlim_selected_location_termid']) ? intval($_COOKIE['wcmlim_selected_location_termid']) : null;
                            ?>
                            <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; ?>">
                                 <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) {
                                            $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 class="wclim-views_font_size">' . $content . '</span></div>';
                                        }
                                    }
                                    ?>
                            </div>
                            </div>
                            <?php
                        }
                    }
                }
                ?>
            </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>
     .location-details .dashicons,
     .simple_view_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;
    }

    .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-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: 10px;
        border-radius: 5px;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .location-stock-item:hover {
        background-color: #f7f7f7;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
    }

    .Wcmlim_box_wrapper {
        margin-bottom: 30px;
    }

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

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


    .variable-product-message {
        font-style: italic;
        color: #666;
        padding: 10px 0;
    }
    .simple_view_location_details {
        margin: 0;
        font-size: 14px;
    }
    
    /* Location Group Selector Styles */
    .wcmlim-location-group-selector {
        margin-bottom: 20px;
        padding: 10px;
        background-color: #f5f5f5;
        border-radius: 5px;
    }
    
    .wcmlim-location-group-dropdown {
        width: 100%;
        padding: 8px;
        border-radius: 4px;
        border: 1px solid #ddd;
        margin-top: 5px;
    }
    
    .location-group-message {
        font-style: italic;
        color: #666;
        padding: 10px 0;
        text-align: center;
        background-color: #f8f8f8;
        border-radius: 4px;
        margin-bottom: 15px;
    }
    .location-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 10px;
    }
    
    .hidden {
        display: none !important;
    }
</style>


