<?php

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

class AIEO_DMM_Checkout_Invoicing extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_dmm_checkout_invoicing';

    public function get_id()       { return 'checkout_invoicing'; }
    public function get_label()    { return __('Professional Invoice', 'ai-eshop-optimizer'); }
    public function get_priority() { return 30; }
    public function get_group()    { return 'checkout_handling'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_checkout_invoicing_save', array($this, 'ajax_save'));
        
        
        
        add_action('wp_ajax_om_checkout_aade_lookup',         array($this, 'ajax_aade_lookup'));
        add_action('wp_ajax_nopriv_om_checkout_aade_lookup',  array($this, 'ajax_aade_lookup'));

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

        
        
        if (!(defined('REST_REQUEST') && REST_REQUEST)) {
            add_filter('woocommerce_checkout_fields', array($this, 'inject_classic_fields'), 10);
            add_action('wp_enqueue_scripts',          array($this, 'enqueue_assets'));
        }
        add_action('woocommerce_checkout_update_order_meta', array($this, 'save_classic_to_order_meta'));

        
        add_action('woocommerce_admin_order_data_after_billing_address', array($this, 'render_admin_order_panel'));

        
        
        
        
        
        
        
        
        
        
        
        
        if (function_exists('woocommerce_register_additional_checkout_field')) {
            $this->register_block_fields();
        } else {
            add_action('woocommerce_blocks_loaded', array($this, 'register_block_fields'));
        }
        add_action('woocommerce_store_api_checkout_update_order_meta', array($this, 'sync_block_fields_to_legacy_meta'));
    }

    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['invoicing_enabled']) ? (string) $legacy['invoicing_enabled'] : 'no',
            'invoice_field_label'     => isset($legacy['invoice_field_label']) ? (string) $legacy['invoice_field_label'] : __('Χρειάζεστε τιμολόγιο;', 'ai-eshop-optimizer'),
            'invoice_yes_label'       => isset($legacy['invoice_yes_label']) ? (string) $legacy['invoice_yes_label'] : __('Ναι, θέλω τιμολόγιο', 'ai-eshop-optimizer'),
            'invoice_no_label'        => isset($legacy['invoice_no_label']) ? (string) $legacy['invoice_no_label'] : __('Όχι, θέλω απόδειξη', 'ai-eshop-optimizer'),
            'vat_field_label'         => isset($legacy['vat_field_label']) ? (string) $legacy['vat_field_label'] : __('ΑΦΜ', 'ai-eshop-optimizer'),
            'irs_field_label'         => isset($legacy['irs_field_label']) ? (string) $legacy['irs_field_label'] : __('ΔΟΥ', 'ai-eshop-optimizer'),
            'profession_field_label'  => isset($legacy['profession_field_label']) ? (string) $legacy['profession_field_label'] : __('Δραστηριότητα', 'ai-eshop-optimizer'),
            'move_company_field'      => isset($legacy['move_company_field']) ? (string) $legacy['move_company_field'] : 'no',
            
            'aade_enabled'            => isset($legacy['aade_enabled']) ? (string) $legacy['aade_enabled'] : 'no',
            'aade_vat'                => isset($legacy['aade_vat']) ? (string) $legacy['aade_vat'] : '',
            'aade_username'           => isset($legacy['aade_username']) ? (string) $legacy['aade_username'] : '',
            'aade_password'           => isset($legacy['aade_password']) ? (string) $legacy['aade_password'] : '',
        ), $stored);
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        $patch = array(
            'enabled'                 => !empty($_POST['enabled']) ? 'yes' : 'no',
            'invoice_field_label'     => isset($_POST['invoice_field_label']) ? sanitize_text_field(wp_unslash($_POST['invoice_field_label'])) : '',
            'invoice_yes_label'       => isset($_POST['invoice_yes_label']) ? sanitize_text_field(wp_unslash($_POST['invoice_yes_label'])) : '',
            'invoice_no_label'        => isset($_POST['invoice_no_label']) ? sanitize_text_field(wp_unslash($_POST['invoice_no_label'])) : '',
            'vat_field_label'         => isset($_POST['vat_field_label']) ? sanitize_text_field(wp_unslash($_POST['vat_field_label'])) : '',
            'irs_field_label'         => isset($_POST['irs_field_label']) ? sanitize_text_field(wp_unslash($_POST['irs_field_label'])) : '',
            'profession_field_label'  => isset($_POST['profession_field_label']) ? sanitize_text_field(wp_unslash($_POST['profession_field_label'])) : '',
            'move_company_field'      => !empty($_POST['move_company_field']) ? 'yes' : 'no',
            'aade_enabled'            => !empty($_POST['aade_enabled']) ? 'yes' : 'no',
            'aade_vat'                => isset($_POST['aade_vat']) ? sanitize_text_field(wp_unslash($_POST['aade_vat'])) : '',
            'aade_username'           => isset($_POST['aade_username']) ? sanitize_text_field(wp_unslash($_POST['aade_username'])) : '',
            'aade_password'           => isset($_POST['aade_password']) ? sanitize_text_field(wp_unslash($_POST['aade_password'])) : '',
        );
        update_option(self::OPTION_KEY, $patch, false);
        wp_send_json_success(array('message' => __('Invoicing settings saved.', 'ai-eshop-optimizer')));
    }

    
    public function ajax_aade_lookup() {
        $s = $this->get_settings();
        if ($s['aade_enabled'] !== 'yes') {
            wp_send_json_error(array('message' => __('AADE lookup not enabled.', 'ai-eshop-optimizer')));
        }
        
        
        check_ajax_referer('om_checkout_invoice', 'nonce');

        $vat = isset($_POST['vat']) ? sanitize_text_field(wp_unslash($_POST['vat'])) : '';
        $vat = preg_replace('/\D+/', '', (string) $vat); 
        if ($vat === '' || strlen($vat) !== 9) {
            wp_send_json_error(array('message' => __('Invalid VAT (must be 9 digits).', 'ai-eshop-optimizer')));
        }

        $username  = (string) $s['aade_username'];
        $password  = (string) $s['aade_password'];
        $called_by = (string) $s['aade_vat'];
        if ($username === '' || $password === '' || $called_by === '') {
            wp_send_json_error(array('message' => __('AADE credentials not configured.', 'ai-eshop-optimizer')));
        }

        $result = $this->call_aade_api($vat, $called_by, $username, $password);
        if (isset($result['error'])) {
            wp_send_json_error(array('message' => $result['error']));
        }
        wp_send_json_success($result);
    }

    
    private function call_aade_api($vat, $called_by, $username, $password) {
        if (!class_exists('SoapClient')) {
            return array('error' => __('PHP SOAP extension not available on this server.', 'ai-eshop-optimizer'));
        }
        $wsdl = 'https://www1.gsis.gr/webtax2/wsgsis/RgWsPublic/RgWsPublicPort?WSDL';
        try {
            $client = new SoapClient($wsdl, array(
                'trace'      => true,
                'exceptions' => true,
                'cache_wsdl' => WSDL_CACHE_NONE,
            ));
            $params = array(
                'INPUT_REC' => array(
                    'afm_called_by'  => $called_by,
                    'afm_called_for' => $vat,
                ),
                'OUTPUT_REC'    => array(),
                'pCallSeqId_out'=> 0,
                'pErrorRec_out' => array(),
            );
            $headers = new SoapHeader(
                'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd',
                'Security',
                new SoapVar(
                    '<wsse:UsernameToken><wsse:Username>' . esc_html($username) . '</wsse:Username><wsse:Password>' . esc_html($password) . '</wsse:Password></wsse:UsernameToken>',
                    XSD_ANYXML
                )
            );
            $client->__setSoapHeaders($headers);
            $result = $client->rgWsPublicAfmMethod($params);
            if (!isset($result->OUTPUT_REC)) {
                return array('error' => __('No data returned from AADE.', 'ai-eshop-optimizer'));
            }
            return array(
                'commer_title'            => isset($result->OUTPUT_REC->commer_title) ? (string) $result->OUTPUT_REC->commer_title : '',
                'onomasia'                => isset($result->OUTPUT_REC->onomasia) ? (string) $result->OUTPUT_REC->onomasia : '',
                'doy_descr'               => isset($result->OUTPUT_REC->doy_descr) ? (string) $result->OUTPUT_REC->doy_descr : '',
                'postal_address'          => isset($result->OUTPUT_REC->postal_address) ? (string) $result->OUTPUT_REC->postal_address : '',
                'postal_address_no'       => isset($result->OUTPUT_REC->postal_address_no) ? (string) $result->OUTPUT_REC->postal_address_no : '',
                'postal_area_description' => isset($result->OUTPUT_REC->postal_area_description) ? (string) $result->OUTPUT_REC->postal_area_description : '',
                'postal_zip_code'         => isset($result->OUTPUT_REC->postal_zip_code) ? (string) $result->OUTPUT_REC->postal_zip_code : '',
                'activities'              => isset($result->OUTPUT_REC->firm_act_tab->item)
                    ? array_map(function($a){ return isset($a->firm_act_descr) ? (string) $a->firm_act_descr : ''; }, (array) $result->OUTPUT_REC->firm_act_tab->item)
                    : array(),
            );
        } catch (\Throwable $e) {
            return array('error' => $e->getMessage());
        }
    }

    
    public function inject_classic_fields($fields) {
        $s = $this->get_settings();
        $options = array(
            'NO'  => (string) $s['invoice_no_label'],
            'YES' => (string) $s['invoice_yes_label'],
        );
        $fields['billing']['billing_timologio'] = array(
            'type'     => 'select',
            'label'    => (string) $s['invoice_field_label'],
            'options'  => $options,
            'default'  => 'NO',
            'class'    => array('form-row-wide'),
            'priority' => 115,
            'required' => true,
        );
        $fields['billing']['billing_vat'] = array(
            'type'     => 'text',
            'label'    => (string) $s['vat_field_label'],
            'class'    => array('form-row-wide', 'timologio-hide'),
            'priority' => 116,
            'required' => false,
        );
        $fields['billing']['billing_irs'] = array(
            'type'     => 'text',
            'label'    => (string) $s['irs_field_label'],
            'class'    => array('form-row-wide', 'timologio-hide'),
            'priority' => 117,
            'required' => false,
        );
        $fields['billing']['billing_store'] = array(
            'type'     => 'text',
            'label'    => (string) $s['profession_field_label'],
            'class'    => array('form-row-wide', 'timologio-hide'),
            'priority' => 118,
            'required' => false,
        );
        if ($s['move_company_field'] === 'yes' && isset($fields['billing']['billing_company'])) {
            $fields['billing']['billing_company']['class'][] = 'timologio-hide';
            $fields['billing']['billing_company']['priority'] = 116;
        }
        return $fields;
    }

    public function enqueue_assets() {
        if (!function_exists('is_checkout') || !is_checkout()) { return; }
        $version = defined('AIEO_VERSION') ? AIEO_VERSION : '1.0';
        wp_enqueue_style(
            'aieo-checkout-invoicing',
            plugins_url('assets/css/aieo-checkout-invoicing.css', AIEO_FILE),
            array(), $version
        );
        wp_enqueue_script(
            'aieo-checkout-invoicing',
            plugins_url('assets/js/aieo-checkout-invoicing.js', AIEO_FILE),
            array('jquery'), $version, true
        );
        $s = $this->get_settings();
        wp_localize_script('aieo-checkout-invoicing', 'omCheckoutInvoice', array(
            'ajaxUrl'     => admin_url('admin-ajax.php'),
            'nonce'       => wp_create_nonce('om_checkout_invoice'),
            'aadeEnabled' => $s['aade_enabled'] === 'yes' && (string) $s['aade_username'] !== '' && (string) $s['aade_password'] !== '' && (string) $s['aade_vat'] !== '',
        ));
    }

    
    public function save_classic_to_order_meta($order_id) {
        $order = wc_get_order($order_id);
        if (!$order) { return; }
        $fields = array('billing_timologio', 'billing_vat', 'billing_irs', 'billing_store');
        foreach ($fields as $f) {
            if (isset($_POST[$f])) {
                $order->update_meta_data('_' . $f, sanitize_text_field(wp_unslash($_POST[$f])));
            }
        }
        $order->save();
    }

    
    public function render_admin_order_panel($order) {
        if (!is_a($order, 'WC_Order')) { return; }
        $tim   = (string) $order->get_meta('_billing_timologio');
        if ($tim !== 'YES') { return; }
        $vat   = (string) $order->get_meta('_billing_vat');
        $irs   = (string) $order->get_meta('_billing_irs');
        $store = (string) $order->get_meta('_billing_store');
        echo '<div class="om-ai-invoice-info" style="margin-top:15px;padding:10px;background:#f9f9f9;border-left:4px solid #0073aa;">';
        echo '<h4 style="margin:0 0 10px;color:#0073aa;">' . esc_html__('Στοιχεία Τιμολογίου', 'ai-eshop-optimizer') . '</h4>';
        if ($vat   !== '') { echo '<p><strong>ΑΦΜ:</strong> '          . esc_html($vat)   . '</p>'; }
        if ($irs   !== '') { echo '<p><strong>ΔΟΥ:</strong> '          . esc_html($irs)   . '</p>'; }
        if ($store !== '') { echo '<p><strong>Δραστηριότητα:</strong> ' . esc_html($store) . '</p>'; }
        echo '</div>';
    }

    
    public function register_block_fields() {
        if (!function_exists('woocommerce_register_additional_checkout_field')) { return; }
        $s = $this->get_settings();

        
        
        
        
        try {
            woocommerce_register_additional_checkout_field(array(
                'id'       => 'aieo/wants_invoice',
                'label'    => (string) $s['invoice_field_label'],
                'location' => 'address',
                'type'     => 'checkbox',
                'required' => false,
            ));
            woocommerce_register_additional_checkout_field(array(
                'id'       => 'aieo/billing_vat',
                'label'    => (string) $s['vat_field_label'],
                'location' => 'address',
                'type'     => 'text',
                'required' => false,
            ));
            woocommerce_register_additional_checkout_field(array(
                'id'       => 'aieo/billing_irs',
                'label'    => (string) $s['irs_field_label'],
                'location' => 'address',
                'type'     => 'text',
                'required' => false,
            ));
            woocommerce_register_additional_checkout_field(array(
                'id'       => 'aieo/billing_store',
                'label'    => (string) $s['profession_field_label'],
                'location' => 'address',
                'type'     => 'text',
                'required' => false,
            ));
        } catch (\Throwable $e) {
            
            
        }
    }

    
    public function sync_block_fields_to_legacy_meta($order) {
        if (!is_a($order, 'WC_Order')) { return; }
        
        $wants  = (string) $order->get_meta('_wc_other/aieo/wants_invoice');
        if ($wants === '1' || $wants === 'true' || $wants === 'yes') {
            $order->update_meta_data('_billing_timologio', 'YES');
            $vat   = (string) $order->get_meta('_wc_other/aieo/billing_vat');
            $irs   = (string) $order->get_meta('_wc_other/aieo/billing_irs');
            $store = (string) $order->get_meta('_wc_other/aieo/billing_store');
            if ($vat   !== '') { $order->update_meta_data('_billing_vat',   $vat); }
            if ($irs   !== '') { $order->update_meta_data('_billing_irs',   $irs); }
            if ($store !== '') { $order->update_meta_data('_billing_store', $store); }
        } else {
            $order->update_meta_data('_billing_timologio', 'NO');
        }
        $order->save();
    }

    public function render_subtab() {
        $s = $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__('Professional Invoice (Τιμολόγιο)', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Greek-style invoice toggle on checkout. Customer picks "I want an invoice" → 3 extra fields appear (ΑΦΜ, ΔΟΥ, Δραστηριότητα). Saved to the same order meta keys (`_billing_timologio`, `_billing_vat`, `_billing_irs`, `_billing_store`) the legacy om-checkout-handling plugin used, so existing PDF invoice templates, AADE plugins, and order exports continue working unchanged.', 'ai-eshop-optimizer') . '</p>';

        echo '<form id="aieo-dmm-inv-form" class="aieo-dmm-form aieo-dmm-card">';
        echo '<table class="form-table">';

        echo '<tr><th>' . esc_html__('Enable invoicing fields', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label><input type="checkbox" name="enabled" value="1" ' . checked($s['enabled'] === 'yes', true, false) . '> ' . esc_html__('Show the invoice toggle + fields on checkout', 'ai-eshop-optimizer') . '</label>';
        echo '</td></tr>';

        $rows = array(
            'invoice_field_label'    => __('Toggle question label', 'ai-eshop-optimizer'),
            'invoice_yes_label'      => __('"Yes, invoice" option', 'ai-eshop-optimizer'),
            'invoice_no_label'       => __('"No, receipt" option', 'ai-eshop-optimizer'),
            'vat_field_label'        => __('ΑΦΜ field label', 'ai-eshop-optimizer'),
            'irs_field_label'        => __('ΔΟΥ field label', 'ai-eshop-optimizer'),
            'profession_field_label' => __('Activity field label', 'ai-eshop-optimizer'),
        );
        foreach ($rows as $k => $label) {
            echo '<tr><th>' . esc_html($label) . '</th><td>';
            echo '<input type="text" name="' . esc_attr($k) . '" value="' . esc_attr((string) $s[$k]) . '" class="regular-text">';
            echo '</td></tr>';
        }

        echo '<tr><th>' . esc_html__('Group company field with invoice fields', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label><input type="checkbox" name="move_company_field" value="1" ' . checked($s['move_company_field'] === 'yes', true, false) . '> ' . esc_html__('Move billing_company next to invoice fields and hide it together with them', 'ai-eshop-optimizer') . '</label>';
        echo '</td></tr>';

        
        echo '<tr><th colspan="2" style="padding-top:24px;border-top:1px solid #e5e7eb;"><h3 style="margin:0;">' . esc_html__('AADE VAT Lookup', 'ai-eshop-optimizer') . '</h3>';
        echo '<p class="description" style="font-weight:normal;margin-top:6px;">' . esc_html__('When enabled, the customer\'s entered ΑΦΜ is sent to the AADE SOAP service and the company name + ΔΟΥ + activity get auto-filled. Requires AADE credentials (apply at gsis.gr) and the PHP SOAP extension on the server.', 'ai-eshop-optimizer') . '</p></th></tr>';

        echo '<tr><th>' . esc_html__('Enable AADE lookup', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label><input type="checkbox" name="aade_enabled" value="1" ' . checked($s['aade_enabled'] === 'yes', true, false) . '> ' . esc_html__('Auto-fill invoice fields from AADE on ΑΦΜ blur', 'ai-eshop-optimizer') . '</label>';
        echo '</td></tr>';
        echo '<tr><th>' . esc_html__('Caller VAT (your shop\'s ΑΦΜ)', 'ai-eshop-optimizer') . '</th><td>';
        echo '<input type="text" name="aade_vat" value="' . esc_attr((string) $s['aade_vat']) . '" maxlength="9" pattern="\d{9}" style="width:140px;font-family:monospace;">';
        echo '<p class="description">' . esc_html__('The 9-digit ΑΦΜ AADE expects in the afm_called_by field — your shop\'s registered ΑΦΜ.', 'ai-eshop-optimizer') . '</p>';
        echo '</td></tr>';
        echo '<tr><th>' . esc_html__('AADE username', 'ai-eshop-optimizer') . '</th><td>';
        echo '<input type="text" name="aade_username" value="' . esc_attr((string) $s['aade_username']) . '" autocomplete="off" class="regular-text">';
        echo '</td></tr>';
        echo '<tr><th>' . esc_html__('AADE password', 'ai-eshop-optimizer') . '</th><td>';
        echo '<input type="password" name="aade_password" value="' . esc_attr((string) $s['aade_password']) . '" autocomplete="off" class="regular-text">';
        echo '<p class="description">' . esc_html__('Stored in wp_options. Consider a dedicated AADE service account separate from your personal login.', 'ai-eshop-optimizer') . '</p>';
        echo '</td></tr>';

        echo '</table>';

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

        echo '<div class="aieo-dmm-card" style="margin-top:18px;background:#f0f6fc;border-left:4px solid #2271b1;">';
        echo '<h3 style="margin:0 0 6px;">' . esc_html__('Block-checkout note', 'ai-eshop-optimizer') . '</h3>';
        echo '<p class="description" style="margin:0;">' . esc_html__('The Cart/Checkout blocks use a different field-registration API than classic checkout. This module registers the four invoice fields via woocommerce_register_additional_checkout_field() (WC ≥ 8.6) so they appear in the block checkout and auto-persist; values are then mapped to the same legacy `_billing_*` meta keys you already use, so your PDF invoice templates and AADE pipeline keep reading one canonical surface.', 'ai-eshop-optimizer') . '</p>';
        echo '</div>';

        echo '<script>(function(){
            var form = document.getElementById("aieo-dmm-inv-form");
            var btn  = document.getElementById("aieo-dmm-inv-save");
            var status = document.getElementById("aieo-dmm-inv-status");
            if (!btn) return;
            btn.addEventListener("click", function(){
                var fd = new FormData(form);
                fd.set("action", "aieo_dmm_checkout_invoicing_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>';
    }
}
