<?php

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

class AIEO_DMM_Checkout_Modal extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_dmm_checkout_modal';

    public function get_id()       { return 'checkout_modal'; }
    public function get_label()    { return __('Checkout Modal (a11y notices)', 'ai-eshop-optimizer'); }
    public function get_priority() { return 90; }
    public function get_group()    { return 'checkout_handling'; }

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

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

        
        add_action('wp', array($this, 'suppress_inline_notices'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_assets'));
        add_action('wp_footer', array($this, 'output_modal_shell_and_bootstrap'), 99);
    }

    public function get_settings() {
        $stored = get_option(self::OPTION_KEY, array());
        if (!is_array($stored)) { $stored = array(); }
        return array_merge(array(
            'enabled'     => 'yes',
            'modal_title' => __('Σφάλματα στο ταμείο', 'ai-eshop-optimizer'),
        ), $stored);
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        update_option(self::OPTION_KEY, array(
            'enabled'     => !empty($_POST['enabled']) ? 'yes' : 'no',
            'modal_title' => isset($_POST['modal_title']) ? sanitize_text_field(wp_unslash($_POST['modal_title'])) : __('Σφάλματα στο ταμείο', 'ai-eshop-optimizer'),
        ), false);
        wp_send_json_success(array('message' => __('Checkout modal settings saved.', 'ai-eshop-optimizer')));
    }

    public function suppress_inline_notices() {
        if (!function_exists('is_checkout') || !is_checkout()) { return; }
        remove_action('woocommerce_before_checkout_form', 'woocommerce_output_all_notices', 10);
    }

    public function enqueue_assets() {
        if (!function_exists('is_checkout') || !is_checkout()) { return; }
        $version  = defined('AIEO_VERSION') ? AIEO_VERSION : '1.0';
        
        
        $base_dir = plugin_dir_path(AIEO_FILE);
        $css_mt   = @filemtime($base_dir . 'assets/css/aieo-checkout-modal.css');
        $js_mt    = @filemtime($base_dir . 'assets/js/aieo-checkout-modal.js');
        $css_ver  = $css_mt ? $version . '.' . $css_mt : $version;
        $js_ver   = $js_mt  ? $version . '.' . $js_mt  : $version;
        wp_enqueue_style(
            'aieo-checkout-modal',
            plugins_url('assets/css/aieo-checkout-modal.css', AIEO_FILE),
            array(), $css_ver
        );
        $deps = array('jquery');
        if (wp_script_is('wc-checkout', 'registered')) { $deps[] = 'wc-checkout'; }
        wp_enqueue_script(
            'aieo-checkout-modal',
            plugins_url('assets/js/aieo-checkout-modal.js', AIEO_FILE),
            $deps, $js_ver, true
        );
        $s = $this->get_settings();
        wp_add_inline_script(
            'aieo-checkout-modal',
            'window.omWcModalTitle = ' . wp_json_encode((string) $s['modal_title']) . ';',
            'before'
        );
    }

    
    public function output_modal_shell_and_bootstrap() {
        if (!function_exists('is_checkout') || !is_checkout()) { return; }
        $title = (string) $this->get_settings()['modal_title'];
        echo '<div class="om-wc-modal-overlay" aria-hidden="true" style="display:none"></div>';
        echo '<div class="om-wc-modal" role="dialog" aria-modal="true" aria-labelledby="om-wc-modal-title" tabindex="-1" style="display:none">'
            . '<div class="om-wc-modal-header"><h3 id="om-wc-modal-title" class="om-wc-modal-title">' . esc_html($title) . '</h3>'
            . '<button type="button" class="om-wc-modal-close" aria-label="Close">&times;</button></div>'
            . '<div class="om-wc-modal-body"></div></div>';

        if (function_exists('wc_print_notices')) {
            ob_start();
            wc_print_notices();
            $html = trim((string) ob_get_clean());
            if ($html !== '') {
                printf(
                    '<script>window.__OM_WC_NOTICES_HTML = %s;</script>',
                    wp_json_encode($html)
                );
            }
        }
    }

    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__('Checkout Notice Modal', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Hoists WooCommerce checkout error / info / success notices into an accessibility-first modal dialog (focus-trapped, ESC-closable). Catches both classic and block checkout error flows. Suppresses the default inline notice render so customers don\'t see the same message twice.', 'ai-eshop-optimizer') . '</p>';
        echo '<form id="aieo-dmm-cm-form" class="aieo-dmm-form aieo-dmm-card"><table class="form-table">';
        echo '<tr><th>' . esc_html__('Enable', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label><input type="checkbox" name="enabled" value="1" ' . checked($s['enabled'] === 'yes', true, false) . '></label></td></tr>';
        echo '<tr><th>' . esc_html__('Modal title', 'ai-eshop-optimizer') . '</th><td>';
        echo '<input type="text" name="modal_title" value="' . esc_attr((string) $s['modal_title']) . '" class="regular-text">';
        echo '</td></tr></table>';
        echo '<p><button type="button" class="button button-primary" id="aieo-dmm-cm-save">' . esc_html__('Save', 'ai-eshop-optimizer') . '</button>';
        echo ' <span id="aieo-dmm-cm-status" style="margin-left:10px;color:#646970;font-size:13px;"></span></p></form>';
        echo '<script>(function(){var f=document.getElementById("aieo-dmm-cm-form");var b=document.getElementById("aieo-dmm-cm-save");var s=document.getElementById("aieo-dmm-cm-status");if(!b)return;b.addEventListener("click",function(){var fd=new FormData(f);fd.set("action","aieo_dmm_checkout_modal_save");fd.set("nonce","' . esc_js($nonce) . '");s.style.color="#646970";s.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){s.style.color="#15803d";s.textContent=j.data.message;}else{s.style.color="#b91c1c";s.textContent=(j&&j.data&&j.data.message)||"' . esc_js(__('Save failed.', 'ai-eshop-optimizer')) . '";}});});})();</script>';
        echo '</div>';
    }
}
