<?php

if (!defined('ABSPATH')) { exit; }

class AIEO_Address_Provider_Google extends WC_Address_Provider {

    const PROVIDER_ID = 'aieo-google-places';

    public function __construct() {
        $this->id            = self::PROVIDER_ID;
        $this->name          = __('Google Places (AIEO)', 'ai-eshop-optimizer');
        $this->branding_html = '<small style="color:#6b7280;font-size:11px;">'
            . esc_html__('powered by Google', 'ai-eshop-optimizer')
            . '</small>';
    }

    
    public static function register() {
        if (!class_exists('WC_Address_Provider')) { return; }

        add_filter('woocommerce_address_providers', array(__CLASS__, 'register_provider'), 10, 1);
        add_action('wp_enqueue_scripts', array(__CLASS__, 'enqueue_provider_script'), 30);
    }

    
    public static function register_provider($providers) {
        if (!is_array($providers)) { return $providers; }
        $providers[] = new self();
        return $providers;
    }

    
    public static function enqueue_provider_script() {
        if (is_admin()) { return; }
        if (!function_exists('is_checkout')) { return; }
        if (!is_checkout() && !is_cart()) { return; }

        $settings = self::get_settings();
        $autocomplete_on = ($settings['enabled'] === 'yes') && !empty($settings['google_api_key']);
        $geolocation_on  = (isset($settings['geolocation_enabled']) && $settings['geolocation_enabled'] === 'yes')
            && !empty($settings['google_api_key']);

        
        
        
        
        $wc_master_on = (get_option('woocommerce_address_autocomplete_enabled') === 'yes');

        $register_provider = $autocomplete_on && $wc_master_on;
        if (!$register_provider && !$geolocation_on) { return; }

        $api_key  = (string) $settings['google_api_key'];
        $language = (string) $settings['language'];
        $country  = strtoupper((string) $settings['country']);
        $version  = defined('AIEO_VERSION') ? AIEO_VERSION : '1.0';

        
        
        
        
        
        
        wp_enqueue_script(
            'google-maps-places',
            'https://maps.googleapis.com/maps/api/js?key=' . urlencode($api_key)
                . '&libraries=places&language=' . urlencode($language) . '&loading=async',
            array(), AIEO_VERSION ,
            true
        );

        $rel = 'assets/js/aieo-address-autocomplete-wc-provider.js';
        $rel = 'assets/js/aieo-address-autocomplete-wc-provider.js';
        $abs = AIEO_DIR . $rel;
        if (!file_exists($abs)) { return; }

        
        
        
        $css_rel = 'assets/css/aieo-address-autocomplete.css';
        $css_abs = AIEO_DIR . $css_rel;
        if (file_exists($css_abs)) {
            wp_enqueue_style(
                'aieo-address-autocomplete',
                AIEO_URI . $css_rel,
                array(),
                (string) filemtime($css_abs)
            );
        }

        wp_enqueue_script(
            'aieo-address-autocomplete-wc-provider',
            AIEO_URI . $rel,
            
            
            
            array('wp-data', 'wc-blocks-checkout', 'wc-address-autocomplete', 'google-maps-places'),
            (string) filemtime($abs),
            true
        );

        
        
        
        
        $wc_states = array();
        if (function_exists('WC') && WC()->countries) {
            $list = WC()->countries->get_states($country);
            if (is_array($list)) { $wc_states = $list; }
        }

        
        
        
        
        $postcode_map = self::build_postcode_map($country);

        wp_localize_script('aieo-address-autocomplete-wc-provider', 'aieoAddressProvider', array(
            'providerId'          => self::PROVIDER_ID,
            'country'             => $country,
            'language'            => $language,
            'wcStates'            => $wc_states,
            'postcodeMap'         => $postcode_map,
            'autocompleteEnabled' => $register_provider ? 1 : 0,
            'geolocationEnabled'  => $geolocation_on ? 1 : 0,
            'i18n'                => array(
                'useMyLocation'       => __('Use my current location', 'ai-eshop-optimizer'),
                'permissionDenied'    => __('Permission denied for location access', 'ai-eshop-optimizer'),
                'unsupported'         => __('Geolocation not supported by this browser', 'ai-eshop-optimizer'),
                'timeout'             => __('Location request timed out', 'ai-eshop-optimizer'),
                'genericError'        => __('Could not get your location', 'ai-eshop-optimizer'),
                'noResults'           => __('No address found for these coordinates', 'ai-eshop-optimizer'),
                'reverseGeocodeFail'  => __('Reverse geocoding failed', 'ai-eshop-optimizer'),
            ),
        ));
    }

    
    private static function build_postcode_map($country) {
        $country = strtoupper((string) $country);
        if ($country !== 'GR' || !class_exists('AIEO_Greek_Nomi')) { return array(); }

        $map = array();
        
        
        
        
        for ($pc = 100; $pc <= 859; $pc++) {
            $code = AIEO_Greek_Nomi::postcode_to_nomos((string) $pc);
            if ($code !== '') {
                $map[(string) $pc] = $code;
            }
        }
        
        
        
        $two_digit = array();
        for ($pc = 100; $pc <= 859; $pc++) {
            $code = isset($map[(string) $pc]) ? $map[(string) $pc] : '';
            if ($code === '') { continue; }
            $p2 = (string) (int) substr((string) $pc, 0, 2);
            if (!isset($two_digit[$p2])) { $two_digit[$p2] = array(); }
            $two_digit[$p2][$code] = isset($two_digit[$p2][$code]) ? ($two_digit[$p2][$code] + 1) : 1;
        }
        foreach ($two_digit as $p2 => $tally) {
            arsort($tally);
            $map[$p2] = (string) array_key_first($tally);
        }
        return $map;
    }

    
    public static function get_settings() {
        $stored = get_option('aieo_dmm_address_autocomplete', array());
        if (!is_array($stored)) { $stored = array(); }
        $legacy = get_option('om_checkout_settings', array());
        if (!is_array($legacy)) { $legacy = array(); }
        return array_merge(array(
            'enabled'        => isset($legacy['autocomplete_enabled']) ? (string) $legacy['autocomplete_enabled'] : 'no',
            'google_api_key' => isset($legacy['google_api_key']) ? (string) $legacy['google_api_key'] : '',
            'language'       => isset($legacy['autocomplete_language']) ? (string) $legacy['autocomplete_language'] : 'el',
            'country'        => isset($legacy['autocomplete_country']) ? (string) $legacy['autocomplete_country'] : 'GR',
        ), $stored);
    }
}
