<?php
/**
 * Address Management Public Handler
 *
 * @link       http://www.techspawn.com
 * @since      1.0.0
 *
 * @package    Wcmlim
 * @subpackage Wcmlim/public
 */

/**
 * Handle enqueuing of address management assets
 *
 * @package    Wcmlim
 * @subpackage Wcmlim/public
 * @author     techspawn1 <contact@techspawn.com>
 */
class WCMLIM_Address_Management_Public {
    
    /**
     * Plugin name
     */
    private $plugin_name;

    /**
     * Plugin version
     */
    private $version;

    /**
     * Constructor
     */
    public function __construct($plugin_name, $version) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;

        // Hook to enqueue scripts
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        
        // Register shortcode for address selector
        add_shortcode('wcmlim_address_selector', array($this, 'render_address_selector'));
        
        // Register widget
        add_action('widgets_init', array($this, 'register_address_widget'));
    }
    
    /**
     * Register the address widget
     */
    public function register_address_widget() {
        register_widget('WCMLIM_Address_Widget');
    }
    
    /**
     * Shortcode to render address selector
     */
    public function render_address_selector($atts = array()) {
        // Check if feature is enabled
        $is_enabled = get_option('wcmlim_enable_user_address_management');
        
        if ($is_enabled !== 'on' || !is_user_logged_in()) {
            return '';
        }
        
        ob_start();
        ?>
        <div class="wcmlim-address-header">
            <button class="wcmlim-address-trigger" type="button">
                <svg class="wcmlim-address-icon" width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
                </svg>
                <span class="wcmlim-address-text">Select Address</span>
                <svg class="wcmlim-address-arrow" width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M7 10l5 5 5-5z"/>
                </svg>
            </button>
            <div class="wcmlim-address-dropdown">
                <div class="wcmlim-address-dropdown-header">
                    <h3 class="wcmlim-address-dropdown-title">My Addresses</h3>
                    <button class="wcmlim-add-address-btn" type="button">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
                        </svg>
                        Add New
                    </button>
                </div>
                <div class="wcmlim-address-list"></div>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Enqueue scripts and styles for address management
     */
    public function enqueue_scripts() {
        // Check if feature is enabled
        $is_enabled = get_option('wcmlim_enable_user_address_management');
        
        // Debug: Add console log to check if condition is met
        if (current_user_can('manage_options')) {
            add_action('wp_footer', function() use ($is_enabled) {
                $logged_in = is_user_logged_in() ? 'yes' : 'no';
                echo '<script>console.log("WCMLIM Address Debug - Enabled: ' . esc_js($is_enabled) . ', Logged in: ' . esc_js($logged_in) . '");</script>';
            }, 1);
        }
        
        if ($is_enabled !== 'on' || !is_user_logged_in()) {
            return;
        }

        // Get Google Maps API key
        $api_key = get_option('wcmlim_google_maps_api_key_address');
        
        if (empty($api_key)) {
            // Don't load if API key is not set
            if (current_user_can('manage_options')) {
                add_action('wp_footer', function() {
                    echo '<script>console.warn("WCMLIM: Google Maps API key not set for address management");</script>';
                });
            }
            return;
        }

        // Check if Google Maps is already loaded in the page
        // Don't enqueue if already present to avoid conflicts
        if (!wp_script_is('google-maps-api', 'enqueued') && 
            !wp_script_is('google-maps', 'enqueued') &&
            !wp_script_is('google-maps-js-api', 'enqueued')) {
            
            // Only load if page doesn't already have Google Maps
            // Use async loading to avoid performance warnings
            add_action('wp_footer', function() use ($api_key) {
                ?>
                <script>
                if (typeof google === 'undefined' || typeof google.maps === 'undefined') {
                    var script = document.createElement('script');
                    script.src = 'https://maps.googleapis.com/maps/api/js?key=<?php echo esc_js($api_key); ?>&libraries=places&loading=async';
                    script.async = true;
                    script.defer = true;
                    document.head.appendChild(script);
                }
                </script>
                <?php
            }, 1);
        }

        // Enqueue CSS
        wp_enqueue_style(
            'wcmlim-address-management',
            plugin_dir_url(__FILE__) . 'css/wcmlim-address-management.css',
            array(),
            $this->version,
            'all'
        );

        // Enqueue JavaScript
        $dependencies = array('jquery');
        // Add Google Maps as dependency if we enqueued it
        if (wp_script_is('google-maps-api', 'enqueued')) {
            $dependencies[] = 'google-maps-api';
        } elseif (wp_script_is('google-maps', 'enqueued')) {
            $dependencies[] = 'google-maps';
        }
        
        wp_enqueue_script(
            'wcmlim-address-management',
            plugin_dir_url(__FILE__) . 'js/wcmlim-address-management.js',
            $dependencies,
            $this->version,
            true
        );

        // Localize script with necessary data
        $autodetect_enabled = get_option('wcmlim_distance_calculator_by_coordinates') === 'on' ? '1' : '0';
        
        wp_localize_script(
            'wcmlim-address-management',
            'wcmlim_address_vars',
            array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('wcmlim_address_nonce'),
                'enabled' => '1',
                'autodetect_enabled' => $autodetect_enabled,
                'messages' => array(
                    'delete_confirm' => __('Are you sure you want to delete this address?', 'wcmlim'),
                    'error_generic' => __('An error occurred. Please try again.', 'wcmlim'),
                    'success_saved' => __('Address saved successfully!', 'wcmlim'),
                    'success_deleted' => __('Address deleted successfully!', 'wcmlim'),
                    'success_selected' => __('Address selected successfully!', 'wcmlim'),
                )
            )
        );
    }
}
