<?php

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

class AIEO_DMM_Payment_Country_Block {

    
    const OPTION_KEY = 'aieo_dmm_payment_blocked_countries';

    public static function bootstrap() {
        static $done = false;
        if ($done) { return; }
        $done = true;

        
        add_action('aieo_dmm_free_shipping_after_cod_card', array(__CLASS__, 'render_card'));
        add_action('wp_ajax_aieo_dmm_payment_country_save', array(__CLASS__, 'ajax_save'));

        
        
        if (!empty(self::get_map())) {
            add_filter('woocommerce_available_payment_gateways', array(__CLASS__, 'gate'), 1003);
            add_action('wp_enqueue_scripts', array(__CLASS__, 'enqueue_block_support'));
        }
    }

    
    
    

    
    public static function get_map() {
        $v = get_option(self::OPTION_KEY, array());
        if (!is_array($v)) { return array(); }
        $out = array();
        foreach ($v as $gid => $codes) {
            $gid = sanitize_key((string) $gid);
            if ($gid === '' || !is_array($codes)) { continue; }
            $codes = array_values(array_filter(array_unique(array_map('strtoupper', array_map('strval', $codes)))));
            if (!empty($codes)) { $out[$gid] = $codes; }
        }
        return $out;
    }

    
    public static function gateways() {
        $out = array();
        if (!function_exists('WC') || !WC() || !WC()->payment_gateways) { return $out; }
        $cod = self::cod_slug();
        foreach (WC()->payment_gateways->payment_gateways() as $id => $gw) {
            $id = (string) $id;
            if ($id === '' || $id === $cod) { continue; }
            $enabled = isset($gw->enabled) ? $gw->enabled : 'no';
            if ($enabled !== 'yes') { continue; } 
            $title = method_exists($gw, 'get_title') ? (string) $gw->get_title() : '';
            if ($title === '') { $title = isset($gw->method_title) ? (string) $gw->method_title : $id; }
            $out[$id] = $title;
        }
        return $out;
    }

    
    
    

    
    public static function render_card() {
        $gateways  = self::gateways();
        $map       = self::get_map();
        $countries = self::shipping_countries();
        $nonce     = wp_create_nonce(AIEO_DMM::NONCE_ACTION);
        $ajax      = admin_url('admin-ajax.php');
        ?>
        <div class="aieo-dmm-card" style="margin-top:24px;">
            <h2><?php esc_html_e('Disable payments by country', 'ai-eshop-optimizer'); ?></h2>
            <p class="description">
                <?php esc_html_e('Hide a payment method when the customer\'s BILLING country is one you pick (e.g. Direct Bank Transfer disabled in Cyprus). Each method is independent; leave a method empty to allow it everywhere. The method must be enabled in WooCommerce → Payments — this only controls visibility. (Cash on Delivery is configured in its own card above.)', 'ai-eshop-optimizer'); ?>
            </p>
            <?php if (empty($gateways)) : ?>
                <p class="description">
                    <?php esc_html_e('No enabled payment methods found (other than Cash on Delivery). Enable a gateway in WooCommerce → Settings → Payments first.', 'ai-eshop-optimizer'); ?>
                </p>
            <?php elseif (empty($countries)) : ?>
                <p class="description">
                    <?php esc_html_e('No shipping countries are configured in WooCommerce → Settings → Shipping yet.', 'ai-eshop-optimizer'); ?>
                </p>
            <?php else : ?>
                <form id="aieo-dmm-pc-form" class="aieo-dmm-form"><table class="form-table">
                    <?php foreach ($gateways as $gid => $title) :
                        $sel = isset($map[$gid]) ? $map[$gid] : array(); ?>
                        <tr>
                            <th>
                                <?php echo esc_html($title); ?>
                                <br><span style="font-weight:400;color:#646970;font-size:11px;"><?php echo esc_html($gid); ?></span>
                            </th>
                            <td>
                                <select multiple class="aieo-dmm-country-select"
                                        name="payment_blocked[<?php echo esc_attr($gid); ?>][]"
                                        style="width:100%;max-width:480px;"
                                        data-placeholder="<?php esc_attr_e('Allowed everywhere — pick countries to disable it in', 'ai-eshop-optimizer'); ?>">
                                    <?php foreach ($countries as $code => $name) :
                                        $cc = strtoupper($code); ?>
                                        <option value="<?php echo esc_attr($cc); ?>" <?php selected(in_array($cc, $sel, true)); ?>>
                                            <?php echo esc_html($name . ' (' . $cc . ')'); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </table>
                <p>
                    <button type="button" class="button button-primary" id="aieo-dmm-pc-save"><?php esc_html_e('Save payment country rules', 'ai-eshop-optimizer'); ?></button>
                    <span id="aieo-dmm-pc-status" style="margin-left:10px;color:#646970;font-size:13px;"></span>
                </p>
                </form>
                <script>
                (function(){
                    if (window.AieoDmm && typeof window.AieoDmm.initSelect2 === 'function') {
                        window.AieoDmm.initSelect2(document.getElementById('aieo-dmm-pc-form'));
                    }
                    var f=document.getElementById('aieo-dmm-pc-form');
                    var b=document.getElementById('aieo-dmm-pc-save');
                    var s=document.getElementById('aieo-dmm-pc-status');
                    if(!b||!f)return;
                    b.addEventListener('click',function(){
                        var fd=new FormData(f);
                        fd.set('action','aieo_dmm_payment_country_save');
                        fd.set('nonce','<?php echo esc_js($nonce); ?>');
                        s.style.color='#646970';s.textContent='<?php echo esc_js(__('Saving…', 'ai-eshop-optimizer')); ?>';
                        fetch('<?php echo 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&&j.data.message)||'<?php echo esc_js(__('Saved.', 'ai-eshop-optimizer')); ?>';}
                            else{s.style.color='#b91c1c';s.textContent=(j&&j.data&&j.data.message)||'<?php echo esc_js(__('Save failed.', 'ai-eshop-optimizer')); ?>';}
                        }).catch(function(){s.style.color='#b91c1c';s.textContent='<?php echo esc_js(__('Save failed.', 'ai-eshop-optimizer')); ?>';});
                    });
                })();
                </script>
            <?php endif; ?>
        </div>
        <?php
    }

    public static function ajax_save() {
        AIEO_DMM::verify_ajax_request();

        $allowed_countries = self::allowed_country_codes();
        $cod               = self::cod_slug();
        $map = array();

        if (isset($_POST['payment_blocked']) && is_array($_POST['payment_blocked'])) {
            
            
            
            
            
            
            
            
            
            
            
            
            
            $raw = wp_unslash($_POST['payment_blocked']); 
            foreach ($raw as $gid => $codes) {
                $gid = sanitize_key((string) $gid);
                if ($gid === '' || $gid === $cod || !is_array($codes)) { continue; }
                $codes = array_map('sanitize_text_field', $codes);
                $codes = array_map('strtoupper', $codes);
                $codes = array_values(array_intersect(array_unique($codes), $allowed_countries));
                if (!empty($codes)) { $map[$gid] = $codes; }
            }
        }

        update_option(self::OPTION_KEY, $map, false);
        wp_send_json_success(array('message' => __('Payment country rules saved.', 'ai-eshop-optimizer')));
    }

    
    
    

    public static function gate($gateways) {
        if (!is_array($gateways)) {
            return $gateways;
        }
        if (is_admin() && !wp_doing_ajax()) {
            return $gateways;
        }

        $map = self::get_map();
        if (empty($map)) {
            return $gateways;
        }

        $country = self::billing_country();
        if ($country === '') {
            return $gateways;
        }

        foreach ($map as $gid => $codes) {
            if (isset($gateways[$gid]) && in_array($country, $codes, true)) {
                unset($gateways[$gid]);
            }
        }
        return $gateways;
    }

    
    
    

    public static function enqueue_block_support() {
        $map = self::get_map();
        if (empty($map)) {
            return;
        }
        if (!(function_exists('is_checkout') && is_checkout()) && !(function_exists('is_cart') && is_cart())) {
            return;
        }
        $handle = 'wc-blocks-registry';
        if (!wp_script_is($handle, 'registered') && !wp_script_is($handle, 'enqueued')) {
            return;
        }
        wp_enqueue_script($handle);

        $cfg = wp_json_encode(array('map' => $map));
        if (!is_string($cfg)) {
            return;
        }

        $js = <<<JS
( function () {
    var cfg = {$cfg};
    var wc = window.wc;
    if ( ! cfg || ! cfg.map || ! wc || ! wc.wcBlocksRegistry ||
         typeof wc.wcBlocksRegistry.registerPaymentMethodExtensionCallbacks !== 'function' ) {
        return;
    }
    var map = cfg.map;
    var billingCountry = function ( arg ) {
        var addr = ( arg && ( arg.billingAddress || arg.billingData ) ) || {};
        return String( addr.country || '' ).toUpperCase();
    };
    var callbacks = {};
    Object.keys( map ).forEach( function ( gid ) {
        var codes = ( map[ gid ] || [] ).map( function ( c ) { return String( c ).toUpperCase(); } );
        callbacks[ gid ] = function ( arg ) {
            try {
                var c = billingCountry( arg );
                if ( c && codes.indexOf( c ) !== -1 ) {
                    return false;
                }
                return true;
            } catch ( e ) {
                return true;
            }
        };
    } );
    wc.wcBlocksRegistry.registerPaymentMethodExtensionCallbacks( 'aieo-payment-country-block', callbacks );
} )();
JS;
        wp_add_inline_script($handle, $js);
    }

    
    
    
    

    private static function billing_country() {
        
        if (isset($_POST['billing_country'])) {
            $c = strtoupper(sanitize_text_field((string) wp_unslash($_POST['billing_country'])));
            if ($c !== '') {
                return $c;
            }
        }
        if (isset($_POST['post_data'])) {
            parse_str((string) wp_unslash($_POST['post_data']), $pd);
            if (is_array($pd) && !empty($pd['billing_country'])) {
                return strtoupper(sanitize_text_field((string) $pd['billing_country']));
            }
        }
        
        if (function_exists('WC') && WC() && WC()->customer) {
            return strtoupper((string) WC()->customer->get_billing_country());
        }
        return '';
    }

    private static function shipping_countries() {
        if (!function_exists('WC') || !WC() || !WC()->countries) {
            return array();
        }
        $c = WC()->countries->get_shipping_countries();
        return is_array($c) ? $c : array();
    }

    private static function allowed_country_codes() {
        return array_map('strtoupper', array_keys(self::shipping_countries()));
    }

    private static function cod_slug() {
        $fs = get_option('aieo_dmm_free_shipping', array());
        if (is_array($fs) && !empty($fs['cod_gateway_slug'])) {
            $slug = sanitize_key($fs['cod_gateway_slug']);
            if ($slug !== '') {
                return $slug;
            }
        }
        return 'cod';
    }
}
