<?php
/**
 * Template: Card View
 * This file handles the front-end rendering of locations in a card view.
 */

// Ensure dashicons are loaded in frontend 
wp_enqueue_style('dashicons');
?>
<div class="Wcmlim_container wcmlim_product">
    <div class="Wcmlim_box_wrapper">
        <div class="Wcmlim_box_content card_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 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;
                }
            }
            
            // 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
                }
            }
            $wcmlim_hide_out_of_stock_location = get_option('wcmlim_hide_out_of_stock_location');

            
            // Add location group message
            if ($isLocationsGroup == "on"): ?>
            <div id="select-group-message" class="card-message">
                <?php echo __('Please select a Location Group to view stock details.', 'wcmlim'); ?>
            </div>
            <?php endif; ?>
            <style>
                                .wcmlim-hide_out_of_stock_location {
                                    display: none !important;
                                }
                            </style>
            <div id="location-stock-cards" class="location-stock-cards" <?php echo ($isLocationsGroup == "on") ? 'data-group-enabled="true"' : ''; ?>>
                <?php
                if ($product->is_type('variable')) {
                    // Message for variable products
                    echo '<div id="variable-product-message" class="card-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,
                        ]);
                        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
                        }

                        // FIX: Initialize stock variable for variable products to avoid undefined variable error
                        $stock = 0; // Set default stock value for variable products

                        ?>
                        <div class="location-stock-card location-stock-item <?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;"
                                        <?php echo ($selected_location_termid === $term->term_id) ? 'checked' : ''; ?>>
                                </div>

                            <div class="location-icon-name">
                                <div class="location-stock">
                                    <div>
                                        <i class="fa fa-map-marker location-icon"></i>
                                        <span class="location-name"><?php echo esc_html(ucfirst($term->name)); ?></span>
                                    </div>
                                    
                                    <span class="stock-display">
                                            <span class="wclim-views_subinfo"> Loading..... </span>
                                        </span>
                                </div>
                            </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: center;"></i><span>' . $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,
                        ]);
                        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;
                                                }
                                            }
                                        }
                                    }
                                }
                        
                        $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 );
                    }
                    $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');
                                }
                            }
                            $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';
                        } else {
                            $stock_text = __($soldout_btntxt, 'wcmlim');
                            $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';
                        }
                        
                        // 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) {
                            
                            // Set display style for simple products with location groups
                            $displayStyle = $isLocationsGroup == "on" ? 'display:none;' : '';
                            ?>
                           
                            <div class="location-stock-card 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-icon-name">
                                    
                                    <div class="location-stock">
                                        <div>
                                        <i class="fa fa-map-marker location-icon"></i>
                                        <span class="location-name"><?php echo esc_html(ucfirst($term->name)); ?></span>
                                        </div> 
                                        
                                        <span class="stock-display" style="color: <?php echo $stock_color; ?>;background: <?php echo $stock_bgcolor; ?>;">
                                            <span class="wclim-views_subinfo"> <?php echo esc_html($stock_text); ?> </span>
                                        </span>
                                    </div>
                                </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: center;"></i><span>' . $content . '</span></div>';
                                        }
                                    }
                                    ?>
                                </div>
                            </div>
                            <?php
                        }
                    }
                }
                ?>
            </div>
            
            <?php
            $geolocation = get_option('wcmlim_geo_location');
            if ($geolocation == "on") :
            ?>
                <div class="postcode-checker">
                    <p class="postcode-checker-title">
                        <strong>
                            <?php echo $txt_nearest ? $txt_nearest : __('Check your nearest stock location :', 'wcmlim'); ?>
                        </strong>
                    </p>
                    <div class="postcode-checker-div postcode-checker-div-show">
                        <?php
                        $globpin = getLocation('wcmlim_nearby_location') ?: "";
                        $loc_dis_un = get_option('wcmlim_location_distance');
                        ?>
                        <input type="text" placeholder="<?php _e('Enter Location', 'wcmlim'); ?>" class="class_post_code" name="post_code" value="<?php esc_html_e(getLocation('wcmlim_nearby_location') ?: ""); ?>" id="elementId">
                        <button class="button" type="button" id="submit_postcode_product" style="line-height: 1.4;border: 0;">
                            <i class="fa fa-map-marker-alt"></i>
                            <?php echo $oncheck_btntxt ? $oncheck_btntxt : __('Check', 'wcmlim'); ?>
                        </button>
                        <input type="hidden" name="global_postal_check" id="global-postal-check" value="true">
                        <input type="hidden" name="product_postal_location" id="product-postal-location" value="<?php esc_html_e($globpin); ?>">
                        <input type="hidden" name="product_location_distance" id="product-location-distance" value="<?php esc_html_e($loc_dis_un); ?>">
                    </div>
                    <div class="search_rep" style="display: inline-flex;">
                        <div class="postcode-checker-response"></div>
                        <a class="postcode-checker-change postcode-checker-change-show" href="#" data-wpzc-form-open="" style="display: none;">
                            <i class="fa fa-edit" aria-hidden="true"></i>
                        </a>
                    </div>
                </div>
            <?php
            endif;
            ?>
            
            <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>

<script>
// Card view functionality has been moved to views.js in the setupCardView() function
// Keeping this script block for PHP variable output

// Output the isVariableProduct value for views.js to use
var wcmlim_cardview_is_variable = <?php echo json_encode($product->is_type('variable')); ?>;
</script>

<style>  
    .Wcmlim_box_wrapper {
        margin-bottom: 30px;
    }  
    .location-stock-cards {
        display: block;
        padding: 0;
    }

    .location-stock-card {
        margin-bottom: 20px;
        width: 100%;
        background-color: #f9f9f9;
        padding: 15px;
        border-radius: 5px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        text-align: left;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
        cursor: pointer;
        box-sizing: border-box;
    }

    .location-stock-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    }

    .location-icon-name {
        margin-bottom: 10px;
    }

    .location-icon {
        font-size: 20px;
        margin-bottom: 5px;
        color: #333;
    }

    .location-name {
        font-size: 16px;
        font-weight: bold;
        color: #444;
        margin-bottom: 0px;
        margin-left: 10px;
    }

    .location-stock {
        font-size: 14px;
        color: #555;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .location-stock-card.highlighted {
        border: 2px solid #4CAF50;
        background-color: #e8f5e9;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    .location-stock-card.selected .location-icon {
        color: #4CAF50;
    }

    .location-stock-card.selected .location-name {
        color: #388E3C;
    }
    
    .card-message {
        width: 100%;
        background-color: #f8f8f8;
        padding: 15px;
        text-align: center;
        border-radius: 5px;
        margin-bottom: 10px;
        color: #555;
        font-weight: bold;
    }
    
    /* Add styles for location details in cards */
    .location-details {
        padding-top: 10px;
        text-align: left;
    }

    .wclim-views_subinfo {
        padding-left: 5px;
        padding-right: 5px;
        font-weight: 400;
    }
    .wclim-views_font_size {
        font-size: 14px;
    }
    
    .location-details p {
        margin: 5px 0;
        font-size: 15px;
        line-height: 1.4;
    }

    .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 Group Selector Styles */
    .wcmlim-location-group-selector {
        margin-bottom: 20px;
        padding: 10px;
        background-color: #f5f5f5;
        border-radius: 5px;
        border: 1px solid #ddd;
    }

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

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

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




