<?php

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

class AIEO_DMM_Address_Autocomplete extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_dmm_address_autocomplete';

    public function get_id()       { return 'address_autocomplete'; }
    public function get_label()    { return __('Address Autocomplete', 'ai-eshop-optimizer'); }
    public function get_priority() { return 20; }
    public function get_group()    { return 'checkout_handling'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_address_autocomplete_save', array($this, 'ajax_save'));

        
        
        if (defined('REST_REQUEST') && REST_REQUEST) { return; }

        $settings = $this->get_settings();
        if ($settings['enabled'] !== 'yes' || empty($settings['google_api_key'])) { return; }

        add_filter('woocommerce_checkout_fields', array($this, 'inject_search_field'), 5);
        add_action('wp_enqueue_scripts',          array($this, 'enqueue_assets'));
    }

    public function get_settings() {
        $stored = get_option(self::OPTION_KEY, 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',
            'field_label'              => isset($legacy['autocomplete_field_label']) ? (string) $legacy['autocomplete_field_label'] : __('Αναζήτηση διεύθυνσης', 'ai-eshop-optimizer'),
            'field_placeholder'        => isset($legacy['autocomplete_field_placeholder']) ? (string) $legacy['autocomplete_field_placeholder'] : __('Πληκτρολογήστε τη διεύθυνσή σας...', 'ai-eshop-optimizer'),
            'hide_for_repeat_visitors' => isset($legacy['hide_for_repeat_visitors']) ? (string) $legacy['hide_for_repeat_visitors'] : 'yes',
            
            
            
            
            'geolocation_enabled'      => 'no',
        ), $stored);
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        $patch = array(
            'enabled'                  => !empty($_POST['enabled']) ? 'yes' : 'no',
            'google_api_key'           => isset($_POST['google_api_key']) ? sanitize_text_field(wp_unslash($_POST['google_api_key'])) : '',
            'language'                 => isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : 'el',
            'country'                  => isset($_POST['country']) ? strtoupper(sanitize_text_field(wp_unslash($_POST['country']))) : 'GR',
            'field_label'              => isset($_POST['field_label']) ? sanitize_text_field(wp_unslash($_POST['field_label'])) : '',
            'field_placeholder'        => isset($_POST['field_placeholder']) ? sanitize_text_field(wp_unslash($_POST['field_placeholder'])) : '',
            'hide_for_repeat_visitors' => !empty($_POST['hide_for_repeat_visitors']) ? 'yes' : 'no',
            'geolocation_enabled'      => !empty($_POST['geolocation_enabled']) ? 'yes' : 'no',
        );
        update_option(self::OPTION_KEY, $patch, false);
        wp_send_json_success(array('message' => __('Address autocomplete settings saved.', 'ai-eshop-optimizer')));
    }

    
    public function inject_search_field($fields) {
        if (!function_exists('is_checkout') || !is_checkout()) { return $fields; }
        $settings = $this->get_settings();
        if ($settings['hide_for_repeat_visitors'] === 'yes' && $this->user_has_full_address()) {
            return $fields;
        }

        $field_def = array(
            'type'         => 'text',
            'label'        => (string) $settings['field_label'],
            'placeholder'  => (string) $settings['field_placeholder'],
            'class'        => array('form-row-wide', 'om-ai-autocomplete-field'),
            'priority'     => 49,
            'required'     => false,
            'autocomplete' => 'off',
        );

        foreach (array('billing', 'shipping') as $section) {
            if (empty($fields[$section]) || !isset($fields[$section][$section . '_address_1'])) { continue; }
            $rebuilt = array();
            foreach ($fields[$section] as $key => $f) {
                if ($key === $section . '_address_1') {
                    $rebuilt[$section . '_address_search'] = $field_def;
                }
                $rebuilt[$key] = $f;
            }
            $fields[$section] = $rebuilt;
        }
        return $fields;
    }

    public function enqueue_assets() {
        if (!function_exists('is_checkout') || !is_checkout()) { return; }
        $settings = $this->get_settings();
        if ($settings['hide_for_repeat_visitors'] === 'yes' && $this->user_has_full_address()) { return; }

        $api_key = (string) $settings['google_api_key'];
        $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((string) $settings['language']) . '&loading=async',
            array(), AIEO_VERSION , true
        );
        wp_enqueue_style(
            'aieo-address-autocomplete',
            plugins_url('assets/css/aieo-address-autocomplete.css', AIEO_FILE),
            array(), $version
        );
        wp_enqueue_script(
            'aieo-address-autocomplete',
            plugins_url('assets/js/aieo-address-autocomplete.js', AIEO_FILE),
            array('jquery', 'google-maps-places'), $version, true
        );
        
        
        wp_localize_script('aieo-address-autocomplete', 'omAI', array(
            'language' => (string) $settings['language'],
            'country'  => strtolower((string) $settings['country']),
        ));
    }

    
    private function user_has_full_address() {
        if (!is_user_logged_in()) { return false; }
        $uid = get_current_user_id();
        $required = array('billing_address_1', 'billing_city', 'billing_postcode', 'billing_country');
        foreach ($required as $key) {
            if (trim((string) get_user_meta($uid, $key, true)) === '') { return false; }
        }
        return true;
    }

    public function render_subtab() {
        $settings = $this->get_settings();
        $nonce = wp_create_nonce(AIEO_DMM::NONCE_ACTION);
        $ajax  = admin_url('admin-ajax.php');
        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Address Autocomplete', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Google Places address autocomplete on the WooCommerce checkout. Customers type the start of their address, Google suggests completions, and the standard WC fields (street, city, postcode, country) are filled in automatically — including the postcode, so table-rate shipping recalculates rates immediately without a manual "calculate shipping" click.', 'ai-eshop-optimizer') . '</p>';

        echo '<form id="aieo-dmm-aac-form" class="aieo-dmm-form aieo-dmm-card">';
        echo '<table class="form-table">';
        echo '<tr><th>' . esc_html__('Enable autocomplete', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label><input type="checkbox" name="enabled" value="1" ' . checked($settings['enabled'] === 'yes', true, false) . '> ' . esc_html__('Show the address-search field on checkout', 'ai-eshop-optimizer') . '</label>';
        echo '</td></tr>';

        echo '<tr><th>' . esc_html__('Google API key', 'ai-eshop-optimizer') . '</th><td>';
        echo '<input type="text" name="google_api_key" value="' . esc_attr((string) $settings['google_api_key']) . '" class="regular-text" autocomplete="off">';
        echo '<p class="description">' . esc_html__('Required. Create at console.cloud.google.com → APIs & Services → Credentials. Enable "Places API" and "Maps JavaScript API" on the same key.', 'ai-eshop-optimizer') . '</p>';
        echo '</td></tr>';

        echo '<tr><th>' . esc_html__('Language', 'ai-eshop-optimizer') . '</th><td>';
        echo '<input type="text" name="language" value="' . esc_attr((string) $settings['language']) . '" style="width:60px;" maxlength="5">';
        echo ' <span class="description">' . esc_html__('ISO code (el, en, …).', 'ai-eshop-optimizer') . '</span>';
        echo '</td></tr>';

        echo '<tr><th>' . esc_html__('Country', 'ai-eshop-optimizer') . '</th><td>';
        echo '<input type="text" name="country" value="' . esc_attr((string) $settings['country']) . '" style="width:60px;" maxlength="2">';
        echo ' <span class="description">' . esc_html__('Restrict suggestions to this 2-letter country code (GR, CY, …).', 'ai-eshop-optimizer') . '</span>';
        echo '</td></tr>';

        echo '<tr><th>' . esc_html__('Field label', 'ai-eshop-optimizer') . '</th><td>';
        echo '<input type="text" name="field_label" value="' . esc_attr((string) $settings['field_label']) . '" class="regular-text">';
        echo '</td></tr>';

        echo '<tr><th>' . esc_html__('Field placeholder', 'ai-eshop-optimizer') . '</th><td>';
        echo '<input type="text" name="field_placeholder" value="' . esc_attr((string) $settings['field_placeholder']) . '" class="regular-text">';
        echo '</td></tr>';

        echo '<tr><th>' . esc_html__('Hide for repeat visitors', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label><input type="checkbox" name="hide_for_repeat_visitors" value="1" ' . checked($settings['hide_for_repeat_visitors'] === 'yes', true, false) . '> ' . esc_html__('Skip the field for logged-in users who already have a complete saved address', 'ai-eshop-optimizer') . '</label>';
        echo '</td></tr>';

        echo '<tr><th>' . esc_html__('“Use my location” button', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label><input type="checkbox" name="geolocation_enabled" value="1" ' . checked($settings['geolocation_enabled'] === 'yes', true, false) . '> ' . esc_html__('Show a one-tap geolocation button next to the address field on the block checkout', 'ai-eshop-optimizer') . '</label>';
        echo '<p class="description">' . esc_html__('Uses the browser’s Geolocation API to read the customer’s coordinates, then asks Google to reverse-geocode them into a street/city/postcode/state. Requires the same Google API key as autocomplete (Geocoding API must be enabled on it). Works independently of the autocomplete toggle.', 'ai-eshop-optimizer') . '</p>';
        echo '</td></tr>';
        echo '</table>';

        echo '<p><button type="button" class="button button-primary" id="aieo-dmm-aac-save">' . esc_html__('Save settings', 'ai-eshop-optimizer') . '</button>';
        echo ' <span id="aieo-dmm-aac-status" style="margin-left:10px;color:#646970;font-size:13px;"></span></p>';
        echo '</form>';

        echo '<script>(function(){
            var form = document.getElementById("aieo-dmm-aac-form");
            var btn  = document.getElementById("aieo-dmm-aac-save");
            var status = document.getElementById("aieo-dmm-aac-status");
            if (!btn) return;
            btn.addEventListener("click", function(){
                var fd = new FormData(form);
                fd.set("action", "aieo_dmm_address_autocomplete_save");
                fd.set("nonce", "' . esc_js($nonce) . '");
                status.style.color = "#646970";
                status.textContent = "' . esc_js(__('Saving…', 'ai-eshop-optimizer')) . '";
                fetch("' . esc_js($ajax) . '", {method:"POST", credentials:"same-origin", body:fd})
                    .then(function(r){return r.json();})
                    .then(function(j){
                        if (j && j.success) { status.style.color = "#15803d"; status.textContent = j.data.message; }
                        else { status.style.color = "#b91c1c"; status.textContent = (j && j.data && j.data.message) || "' . esc_js(__('Save failed.', 'ai-eshop-optimizer')) . '"; }
                    });
            });
        })();</script>';

        echo '</div>';
    }
}
