<?php

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

class AIEO_DMM_Payment_Gating {

    const OPTION_KEY = 'aieo_dmm_payment_gating';

    
    const PICKUP_ANY_TOKEN = '__local_pickup_any__';

    
    public static function local_pickup_method_ids() {
        if (class_exists('Automattic\\WooCommerce\\StoreApi\\Utilities\\LocalPickupUtils')) {
            $ids = \Automattic\WooCommerce\StoreApi\Utilities\LocalPickupUtils::get_local_pickup_method_ids();
            if (is_array($ids) && !empty($ids)) { return array_values(array_map('strval', $ids)); }
        }
        return array('local_pickup', 'pickup_location');
    }

    
    private static function chosen_matches_token($chosen, $token) {
        $chosen = (array) $chosen;
        if ($token === self::PICKUP_ANY_TOKEN) {
            $ids = self::local_pickup_method_ids();
            foreach ($chosen as $m) {
                $parts = explode(':', (string) $m, 2);
                if (in_array($parts[0], $ids, true)) { return true; }
            }
            return false;
        }
        foreach ($chosen as $m) {
            if (strpos((string) $m, $token) !== false) { return true; }
        }
        return false;
    }

    
    private static function chosen_matches_pickup($chosen, $s) {
        if ((isset($s['pickup_any']) ? $s['pickup_any'] : 'yes') !== 'no') {
            
            return self::chosen_matches_token($chosen, self::PICKUP_ANY_TOKEN);
        }
        
        $allowed = self::selected_pickup_rate_ids((array) (isset($s['pickup_locations']) ? $s['pickup_locations'] : array()));
        if (empty($allowed)) { return false; }
        foreach ((array) $chosen as $m) {
            $m = (string) $m;
            if (in_array($m, $allowed, true) || in_array(self::base_pickup_rate($m), $allowed, true)) {
                return true;
            }
        }
        return false;
    }

    
    public static function selected_pickup_rate_ids($names) {
        $names = array_filter(array_map('strval', (array) $names));
        if (empty($names)) { return array(); }
        $locs = get_option('pickup_location_pickup_locations', array());
        $out  = array();
        if (is_array($locs)) {
            foreach ($locs as $i => $l) {
                if (is_array($l) && !empty($l['name']) && in_array((string) $l['name'], $names, true)) {
                    $out[] = 'pickup_location:' . $i;
                }
            }
        }
        return $out;
    }

    
    private static function base_pickup_rate($rid) {
        $colon = strpos($rid, ':');
        if ($colon === false) { return $rid; }
        $method = substr($rid, 0, $colon);
        $rest   = substr($rid, $colon + 1);
        if (preg_match('/^(\d+)/', $rest, $mm)) { return $method . ':' . $mm[1]; }
        return $rid;
    }

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

        
        
        
        add_action('wp_ajax_aieo_dmm_payment_gating_save', array(__CLASS__, 'ajax_save'));

        
        $s = self::get_settings();
        if ($s['enabled'] !== 'yes') { return; }

        
        
        add_filter('woocommerce_available_payment_gateways', array(__CLASS__, 'gate_payment'), 1002);
        
        add_action('wp_enqueue_scripts', array(__CLASS__, 'enqueue_block_support'));
    }

    public static function get_settings() {
        $stored = get_option(self::OPTION_KEY, array());
        if (!is_array($stored)) { $stored = array(); }
        $s = array_merge(array(
            'enabled'                => 'no',
            'gated_gateway_id'       => 'cheque',
            'pickup_any'             => 'yes',                  
            'pickup_locations'       => array(),               
            'shipping_match_token'   => self::PICKUP_ANY_TOKEN, 
        ), $stored);
        if (!is_array($s['pickup_locations'])) { $s['pickup_locations'] = array(); }
        $s['pickup_any'] = ($s['pickup_any'] === 'no') ? 'no' : 'yes';
        return $s;
    }

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

        $pickup_any = !empty($_POST['pickup_any']) ? 'yes' : 'no';
        $locs = array();
        if ($pickup_any === 'no' && isset($_POST['pickup_locations']) && is_array($_POST['pickup_locations'])) {
            $valid = array();
            if (class_exists('AIEO_DMM_Local_Pickup')) {
                foreach (AIEO_DMM_Local_Pickup::blocks_locations() as $bl) {
                    if (!empty($bl['name'])) { $valid[] = (string) $bl['name']; }
                }
            }
            $raw  = array_map('sanitize_text_field', wp_unslash($_POST['pickup_locations']));
            $locs = array_values(array_intersect($raw, $valid));
        }

        $patch = array(
            'enabled'              => !empty($_POST['enabled']) ? 'yes' : 'no',
            'gated_gateway_id'     => isset($_POST['gated_gateway_id']) ? sanitize_key(wp_unslash($_POST['gated_gateway_id'])) : 'cheque',
            'pickup_any'           => $pickup_any,
            'pickup_locations'     => $locs,
            'shipping_match_token' => self::PICKUP_ANY_TOKEN,
        );
        update_option(self::OPTION_KEY, $patch, false);
        wp_send_json_success(array('message' => __('Cash-on-pickup settings saved.', 'ai-eshop-optimizer')));
    }

    public static function gate_payment($gateways) {
        if (!is_array($gateways)) { return $gateways; }
        
        if (is_admin() && !wp_doing_ajax()) { return $gateways; }
        if (!function_exists('WC') || !WC() || !WC()->session) { return $gateways; }

        $s = self::get_settings();
        $gateway_id = (string) $s['gated_gateway_id'];
        if ($gateway_id === '') { return $gateways; }

        $chosen = WC()->session->get('chosen_shipping_methods');
        if (!is_array($chosen) || empty($chosen)) {
            unset($gateways[$gateway_id]); 
            return $gateways;
        }

        $matches_pickup = self::chosen_matches_pickup($chosen, $s);

        if ($matches_pickup) {
            if (!isset($gateways[$gateway_id]) && WC()->payment_gateways) {
                $all = WC()->payment_gateways->payment_gateways();
                if (isset($all[$gateway_id])) {
                    $gateways[$gateway_id] = $all[$gateway_id];
                }
            }
        } else {
            unset($gateways[$gateway_id]);
        }
        return $gateways;
    }

    
    public static function enqueue_block_support() {
        $s = self::get_settings();
        if ($s['enabled'] !== 'yes') { return; }
        $slug = (string) $s['gated_gateway_id'];
        if ($slug === '') { 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);

        $any = ($s['pickup_any'] !== 'no');
        $cfg = wp_json_encode(array(
            'slug'           => $slug,
            'anyPickup'      => $any,
            'pickupIds'      => $any ? self::local_pickup_method_ids() : array(),
            'allowedRateIds' => $any ? array() : self::selected_pickup_rate_ids((array) $s['pickup_locations']),
        ));
        if (!is_string($cfg)) { return; }

        $js = <<<JS
( function () {
    var cfg = {$cfg};
    var wc = window.wc;
    if ( ! cfg || ! cfg.slug || ! wc || ! wc.wcBlocksRegistry ||
         typeof wc.wcBlocksRegistry.registerPaymentMethodExtensionCallbacks !== 'function' ) {
        return;
    }
    var anyPickup = !! cfg.anyPickup;
    var pickupIds = cfg.pickupIds || [];
    var allowed   = cfg.allowedRateIds || [];
    var baseRate = function ( rid ) {
        rid = String( rid );
        var c = rid.indexOf( ':' );
        if ( c === -1 ) { return rid; }
        var method = rid.slice( 0, c );
        var mm = rid.slice( c + 1 ).match( /^(\d+)/ );
        return mm ? method + ':' + mm[ 1 ] : rid;
    };
    var callbacks = {};
    callbacks[ cfg.slug ] = function ( arg ) {
        try {
            var sel = ( arg && arg.selectedShippingMethods ) || {};
            var ids = [];
            if ( Array.isArray( sel ) ) {
                ids = sel;
            } else if ( sel && typeof sel === 'object' ) {
                ids = Object.keys( sel ).map( function ( k ) { return sel[ k ]; } );
            }
            for ( var i = 0; i < ids.length; i++ ) {
                var rid = String( ids[ i ] );
                if ( anyPickup ) {
                    if ( pickupIds.indexOf( rid.split( ':' )[ 0 ] ) !== -1 ) { return true; }
                } else if ( allowed.indexOf( rid ) !== -1 || allowed.indexOf( baseRate( rid ) ) !== -1 ) {
                    return true;
                }
            }
            return false; // otherwise hide it
        } catch ( e ) {
            return true;
        }
    };
    wc.wcBlocksRegistry.registerPaymentMethodExtensionCallbacks( 'aieo-payment-gating', callbacks );
} )();
JS;
        wp_add_inline_script($handle, $js);
    }

    
    private static function gateways_list() {
        $out = array();
        if (!function_exists('WC') || !WC() || !WC()->payment_gateways) { return $out; }
        foreach (WC()->payment_gateways->payment_gateways() as $id => $gw) {
            $id = (string) $id;
            if ($id === '') { 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] = array(
                'title'   => $title,
                'enabled' => (isset($gw->enabled) ? $gw->enabled : 'no') === 'yes',
            );
        }
        return $out;
    }

    
    private static function shipping_methods_list() {
        
        
        
        $out = array(self::PICKUP_ANY_TOKEN => __('Any local pickup (legacy + Blocks)', 'ai-eshop-optimizer'));
        if (!class_exists('WC_Shipping_Zones')) { return $out; }
        $zones = WC_Shipping_Zones::get_zones();
        $rest  = WC_Shipping_Zones::get_zone(0);
        if ($rest) { $zones[] = array('shipping_methods' => $rest->get_shipping_methods(false)); }
        foreach ($zones as $z) {
            foreach ((isset($z['shipping_methods']) ? $z['shipping_methods'] : array()) as $m) {
                if (method_exists($m, 'is_enabled') && !$m->is_enabled()) { continue; }
                $mid = (string) $m->id;
                if ($mid === '' || isset($out[$mid])) { continue; }
                $title = (isset($m->method_title) && $m->method_title !== '') ? (string) $m->method_title : $mid;
                $out[$mid] = $title;
            }
        }
        return $out;
    }

    
    public static function render_card() {
        $s        = self::get_settings();
        $cur_gw   = (string) $s['gated_gateway_id'];
        $gateways = self::gateways_list();
        $loc_names = array();
        if (class_exists('AIEO_DMM_Local_Pickup')) {
            foreach (AIEO_DMM_Local_Pickup::blocks_locations() as $bl) {
                if (!empty($bl['name'])) { $loc_names[] = (string) $bl['name']; }
            }
        }
        $pickup_any = ($s['pickup_any'] !== 'no');
        $selected   = (array) $s['pickup_locations'];
        $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('Cash payment during pick-up', 'ai-eshop-optimizer'); ?></h2>
            <p class="description" style="max-width:760px;">
                <?php esc_html_e('Show a payment method ONLY when the customer chooses store pickup — for paying in cash at the store on collection (this is NOT Cash on Delivery). Typically the WooCommerce Cheque gateway, renamed. The gateway must be enabled in WooCommerce → Payments; the name the customer sees is that gateway\'s own title (rename it there, e.g. to "Cash payment during pick-up").', 'ai-eshop-optimizer'); ?>
            </p>
            <form id="aieo-dmm-pg-form" class="aieo-dmm-form"><table class="form-table">
                <tr>
                    <th><?php esc_html_e('Enable this rule', 'ai-eshop-optimizer'); ?></th>
                    <td><label><input type="checkbox" name="enabled" value="1" <?php checked($s['enabled'] === 'yes'); ?>> <?php esc_html_e('Hide the payment method below until its shipping method is chosen', 'ai-eshop-optimizer'); ?></label></td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Payment method to gate', 'ai-eshop-optimizer'); ?></th>
                    <td>
                        <select name="gated_gateway_id" style="min-width:320px;max-width:480px;">
                            <?php if ($cur_gw !== '' && !isset($gateways[$cur_gw])) : ?>
                                <option value="<?php echo esc_attr($cur_gw); ?>" selected><?php echo esc_html($cur_gw); ?></option>
                            <?php endif; ?>
                            <?php foreach ($gateways as $id => $info) :
                                $label = $info['title'] . ' (' . $id . ')';
                                if (!$info['enabled']) { $label .= ' — ' . __('disabled in WooCommerce', 'ai-eshop-optimizer'); }
                                ?>
                                <option value="<?php echo esc_attr($id); ?>" <?php selected($cur_gw, $id); ?>><?php echo esc_html($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <p class="description"><?php esc_html_e('This method stays hidden until store pickup is chosen. Default: Cheque. (Must be enabled in WooCommerce → Payments to ever show.)', 'ai-eshop-optimizer'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Show it for these pickup locations', 'ai-eshop-optimizer'); ?></th>
                    <td>
                        <label style="display:block;margin:0 0 8px;">
                            <input type="checkbox" name="pickup_any" id="aieo-pg-any" value="1" <?php checked($pickup_any); ?>>
                            <strong><?php esc_html_e('Any pickup location', 'ai-eshop-optimizer'); ?></strong>
                            — <?php esc_html_e('show for every store pickup (legacy + Blocks, both checkouts). Recommended.', 'ai-eshop-optimizer'); ?>
                        </label>
                        <fieldset id="aieo-pg-locs" style="margin:0 0 0 22px;padding:0;border:0;<?php echo $pickup_any ? 'opacity:.5;' : ''; ?>">
                            <?php if (empty($loc_names)) : ?>
                                <p class="description"><?php esc_html_e('No pickup locations defined yet — add them above (Local Pickup tab).', 'ai-eshop-optimizer'); ?></p>
                            <?php else : foreach ($loc_names as $ln) : ?>
                                <label style="display:block;margin:0 0 5px;line-height:1.4;">
                                    <input type="checkbox" name="pickup_locations[]" value="<?php echo esc_attr($ln); ?>" <?php checked(in_array($ln, $selected, true)); ?>>
                                    <?php echo esc_html($ln); ?>
                                </label>
                            <?php endforeach; endif; ?>
                        </fieldset>
                        <p class="description"><?php esc_html_e('Untick "Any pickup location" to restrict the payment method to specific stores (block checkout). Default: any.', 'ai-eshop-optimizer'); ?></p>
                    </td>
                </tr>
            </table>
            <p>
                <button type="button" class="button button-primary" id="aieo-dmm-pg-save"><?php esc_html_e('Save', 'ai-eshop-optimizer'); ?></button>
                <span id="aieo-dmm-pg-status" style="margin-left:10px;color:#646970;font-size:13px;"></span>
            </p>
            </form>
            <script>
            (function(){
                var f=document.getElementById('aieo-dmm-pg-form');
                var b=document.getElementById('aieo-dmm-pg-save');
                var s=document.getElementById('aieo-dmm-pg-status');
                if(!b||!f)return;
                var anyEl=document.getElementById('aieo-pg-any');
                var locsEl=document.getElementById('aieo-pg-locs');
                function syncLocs(){ if(locsEl){ locsEl.style.opacity=(anyEl&&anyEl.checked)?'0.5':'1'; } }
                if(anyEl){ anyEl.addEventListener('change', syncLocs); }
                b.addEventListener('click',function(){
                    var fd=new FormData(f);
                    fd.set('action','aieo_dmm_payment_gating_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>
        </div>
        <?php
    }
}
