<?php

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

class AIEO_DMM_Risk_Gating {

    const OPT_NOTICE = 'aieo_dmm_risk_show_checkout_notice';
    const OPT_BLOCK_COD = 'aieo_dmm_risk_block_cod_for_high';

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

        if ((bool) get_option(self::OPT_NOTICE, false)) {
            add_action('woocommerce_before_checkout_form', array(__CLASS__, 'maybe_render_checkout_notice'), 5);
        }
        if ((bool) get_option(self::OPT_BLOCK_COD, false)) {
            add_filter('woocommerce_available_payment_gateways', array(__CLASS__, 'maybe_block_cod_for_high_risk'));
        }
    }

    
    public static function maybe_render_checkout_notice() {
        $uid = get_current_user_id();
        if (!$uid) { return; }
        if (!class_exists('AIEO_DMM_User_Behavior_Metrics')) { return; }
        $band = AIEO_DMM_User_Behavior_Metrics::risk_band($uid);
        if ($band < 1) { return; }

        $msg = $band === 2
            ? __('We&#8217;ve noticed several recent cancellations on this account. Please double-check the order before submitting — it helps us keep prices low for everyone.', 'ai-eshop-optimizer')
            : __('Quick reminder: please review your order details carefully before checkout.', 'ai-eshop-optimizer');
        $msg = (string) apply_filters('aieo_dmm_risk_checkout_notice_text', $msg, $band, $uid);

        $color = $band === 2 ? '#b91c1c' : '#ca8a04';
        echo '<div class="aieo-dmm-risk-notice" style="border-left:4px solid ' . esc_attr($color) . ';background:' . esc_attr($color) . '11;padding:12px 14px;margin:0 0 18px;border-radius:4px;font-size:14px;">';
        echo wp_kses_post($msg);
        echo '</div>';
    }

    
    public static function maybe_block_cod_for_high_risk($gateways) {
        if (!is_array($gateways)) { return $gateways; }
        $uid = get_current_user_id();
        if (!$uid) { return $gateways; }
        if (!class_exists('AIEO_DMM_User_Behavior_Metrics')) { return $gateways; }
        if (AIEO_DMM_User_Behavior_Metrics::risk_band($uid) < 2) { return $gateways; }

        
        $cod_ids = (array) apply_filters('aieo_dmm_risk_cod_gateway_ids', array('cod', 'wc_cod', 'cash_on_delivery'));
        foreach ($cod_ids as $id) {
            if (isset($gateways[$id])) { unset($gateways[$id]); }
        }
        return $gateways;
    }
}
