<?php

/**
 * This file responsible for location popup shortcode
 *
 * @link       http://www.techspawn.com
 * @since      1.2.11
 *
 * @package    Wcmlim
 * @subpackage Wcmlim/public
 */

class Wcmlim_Location_Popup
{
    public function __construct()
    {
        add_shortcode('wcmlim_locations_popup', [$this, 'wcmlim_locations_popup_cb']);
        add_action('wp_enqueue_scripts', [$this, 'my_plugin_assets']);
      
        // *popup position as per setting if set
        add_action("wp_head", [$this, 'wcmlim_set_inline_css']);
        
        // Automatically insert popup in footer if force to select location is enabled
        add_action('wp_footer', [$this, 'auto_insert_popup_restrict_forced']);
    }


    public function wcmlim_set_inline_css() {
        $popuppos = get_option('wcmlim_popup_icon_position');
    
        if (isset($popuppos) && $popuppos !== "default") {
            $css = '';
    
            if ($popuppos == "bottom") {
                $css .= ".set-def-store-popup-btn {margin-right: -39px; padding-bottom:40px;}";
            }
            if ($popuppos == "top") {
                $css .= ".set-def-store-popup-btn {padding-top: 35px !important; margin-right: -43px;}";
            }
            if ($popuppos == "left") {
                $css .= ".set-def-store-popup-btn {padding-left: 30px !important; padding-top:2px;  }";
            }
            if ($popuppos == "right") {
                $css .= ".set-def-store-popup-btn {margin-right: -90px; padding-right: 40px;}";
            }
    
            // Add a generic rule for background-position
            $css .= ".set-def-store-popup-btn {background-position: {$popuppos} !important;}";
    
            // Echo the combined CSS
            echo "<style>{$css}</style>";
        }
    }

    public function my_plugin_assets()
    {
        $show_in_popup = get_option("wcmlim_show_in_popup");
        if (empty($show_in_popup)) {
            $inline_location = get_option("wcmlim_listing_inline_location");
            $show_in_popup = !empty($inline_location) ? 'list' : '';
        } else {
            $show_in_popup = 'select';
        }
        $force_to_select = get_option("wcmlim_force_to_select_location");
        
        // Get location data from server-side cookies
        $selected_location = getLocation('wcmlim_selected_location');
        $selected_location_termid = getLocation('wcmlim_selected_location_termid');
        
        // Handle cases where getLocation returns null but cookie might exist with -1
        if ($selected_location === null && isset($_COOKIE['wcmlim_selected_location'])) {
            $selected_location = $_COOKIE['wcmlim_selected_location'];
        }
        if ($selected_location_termid === null && isset($_COOKIE['wcmlim_selected_location_termid'])) {
            $selected_location_termid = $_COOKIE['wcmlim_selected_location_termid'];
        }
        
        wp_enqueue_style('wcmlim-magnificPopup', WCMLIM_URL_PATH . 'public/css/magnific-popup-min.css', array(), rand(), 'all');
        wp_enqueue_style('wcmlim-popupcss', WCMLIM_URL_PATH . 'public/css/wcmlim-popup-min.css', array(), rand(), 'all');
        wp_enqueue_script('wcmlim-magnificPopup', WCMLIM_URL_PATH . 'public/js/jquery.magnific-popup.js', array('jquery'), rand(), true);
        wp_enqueue_script('wcmlim-popupjs', WCMLIM_URL_PATH . 'public/js/wcmlim-popup-min.js', array('jquery'), rand(), true);
        wp_localize_script('wcmlim-popupjs', 'multi_inventory_popup', array(
            'ajaxurl' => admin_url('admin-ajax.php'), 
            'show_in_popup' => $show_in_popup ?? "false", 
            'force_to_select' => $force_to_select,
            'selected_location' => $selected_location,
            'selected_location_termid' => $selected_location_termid,
            'popup_mode' => $show_in_popup, // Pass the popup mode for JavaScript reference
        ));
    }

    public function wcmlim_locations_popup_cb()
    {
        $isEditor = $uri = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        if(strpos($isEditor, 'wp-json/wp/')){
            return;
        }
        $wcmlim_this_style_absolution_postition = '';
        $wcmlim_this_post = get_post();
        // $wcmlim_this_content = $wcmlim_this_post->post_content;
        if($wcmlim_this_post && is_object($wcmlim_this_post)){
            $wcmlim_this_content = $wcmlim_this_post->post_content;

             if($wcmlim_this_content != ''){
            $wcmlim_this_has_shortcode = has_shortcode( $wcmlim_this_content, 'wcmlim_locations_switch' );
            $wcmlim_this_style_absolution_postition = ($wcmlim_this_has_shortcode) ? 'style="position:absolute;"' : '';
        }
            
        } 
       
    
        if( current_user_can('administrator') ) {
            $admins =get_users(array('role' => 'administrator'));
            foreach ($admins as $admin) {
                $current_user_id = $admin->ID;
            }
        } else{
            $current_user_id = get_current_user_id();
        }
        
        $user_location = get_user_meta($current_user_id, 'wcmlim_user_specific_location', true);

        $disable_button_style = '';

        if (get_option('wcmlim_enable_userspecific_location') == 'on') {

            if ($user_location != '0') {
                $disable_button_style = 'pointer-events: none;';
            } else {
                $disable_button_style = 'pointer-events: unset;';
            }
        }

        // Replace cookie fetch with getLocation() for selected location
        $selected_location = getLocation('wcmlim_selected_location');
        if ($selected_location !== null && $selected_location != -1) {
            $locations_list = $this->get_locations_lists();
            $select_location = isset($locations_list[$selected_location]) ? $locations_list[$selected_location] : null;
            $select_location['location_name'] = isset($select_location['location_name']) ? $select_location['location_name'] : '';
            echo '<a id="set-def-store-popup-btn" class="set-def-store-popup-btn" href="#set-def-store" style="'.$disable_button_style.'">' . $select_location['location_name'] . '</a>';
        } else {
            $isLocEx = get_option("wcmlim_exclude_locations_from_frontend");
            if (!empty($isLocEx)) {
                $terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0, 'exclude' => $isLocEx));
            }
            echo '<a id="set-def-store-popup-btn" class="set-def-store-popup-btn" href="#set-def-store" '.$wcmlim_this_style_absolution_postition.'>' .esc_html('- Select Location -', 'wcmlim'). '</a>';
        }
    
        if ($selected_location !== null && $selected_location != -1)  {
            echo '<div id="set-def-store" class="zoom-anim-dialog set-def-store-popup-div mfp-hide">';
        } else {
            echo '<div id="set-def-store" class="zoom-anim-dialog set-def-store-popup-div mfp-hide hide-close">';
        }
        echo '<div>' . do_shortcode("[wcmlim_locations_switch]") . '</div>';
        echo '<button class="mfp-close" title="Close (Esc)" type="button">×</button>';
        echo '</div>';
    }
    

    public function get_locations_lists()
    {
        $isLocEx = get_option("wcmlim_exclude_locations_from_frontend");
        if (!empty($isLocEx)) {
            $terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0, 'exclude' => $isLocEx));
        } else {
            $terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
        }
        $result = [];
        $i = 0;
        foreach ($terms as $k => $term) {
            $term_meta = get_option("taxonomy_$term->term_id");
            $term_meta = array_map(function ($term) {
                if (!is_array($term)) {
                    return $term;
                }
            }, $term_meta);
            $result[$i]['location_address'] = implode(" ", array_filter($term_meta));
            $result[$i]['location_name'] = $term->name;
            $i++;
        }
        return $result;
    }

    /**
     * Automatically insert popup in footer if force to select location setting is enabled
     * This ensures the popup HTML is always available when the setting is on
     */
    public function auto_insert_popup_restrict_forced()
    {
        $force_to_select = get_option("wcmlim_force_to_select_location");
        
        // Only auto-insert if the setting is enabled
        if ($force_to_select === 'on') {
            // Check if location is already selected via cookies
            $location_termid = isset($_COOKIE['wcmlim_selected_location_termid']) ? $_COOKIE['wcmlim_selected_location_termid'] : '';
            $location = isset($_COOKIE['wcmlim_selected_location']) ? $_COOKIE['wcmlim_selected_location'] : '';
            
            // If location is already selected, don't show popup
            if (!empty($location_termid) && !empty($location) && 
                $location_termid !== '-1' && $location !== '-1') {
                return;
            }
            
            global $post;
            
            // Check if the shortcode is already present in the current page content
            $has_shortcode_in_content = false;
            if ($post && has_shortcode($post->post_content, 'wcmlim_locations_popup')) {
                $has_shortcode_in_content = true;
            }
            
            // Only insert if shortcode is not already present in content
            if (!$has_shortcode_in_content) {
                // Directly output the popup HTML
                echo '<div id="wcmlim-auto-popup-wrapper" style="display: none;">';
                $this->wcmlim_locations_popup_cb();
                echo '</div>';
                
                // Add JavaScript to make the popup visible and initialize it
                echo '<script type="text/javascript">
                    document.addEventListener("DOMContentLoaded", function() {
                        var autoPopupWrapper = document.getElementById("wcmlim-auto-popup-wrapper");
                        if (autoPopupWrapper) {
                            autoPopupWrapper.style.display = "block";
                        }
                    });
                </script>';
            }
        }
    }
}
new Wcmlim_Location_Popup();

