<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum
/**
 * GT BOGO Engine — New Admin AJAX Handlers
 *
 * Handles all AJAX actions introduced by the 13 new enterprise admin pages.
 * Every handler: check_ajax_referer() + current_user_can() before any action.
 *
 * Actions registered here:
 *   gtbogo_rule_perf_drilldown    — per-rule segment + lift accordion
 *   gtbogo_rule_perf_export       — CSV export of rule performance
 *   gtbogo_dl_live_feed           — live decision log refresh (10 latest)
 *   gtbogo_dl_export_csv          — decision log CSV export
 *   gtbogo_dl_purge               — bulk purge old decisions
 *   gtbogo_lo_test_simulate       — test deal lockout against cart session
 *   gtbogo_lo_export_config       — export lockout config JSON
 *   gtbogo_lo_import_config       — import lockout config JSON
 *   gtbogo_ss_export_diagnostic   — store status diagnostic download
 *   gtbogo_wl_export_config       — white label config JSON export
 *   gtbogo_wl_import_config       — white label config JSON import
 *   gtbogo_wl_reset               — reset white label to defaults
 *   gtbogo_la_set_tier            — manual loyalty tier override
 *   gtbogo_oi_export_csv          — outcome intelligence CSV export
 *   gtbogo_cond_test_cart         — test conditions against live cart
 *   gtbogo_cond_export            — conditions JSON export
 *   gtbogo_cond_import            — conditions JSON import
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class GT_BOGO_New_Admin_Ajax {

    public static function init(): void {
        $actions = [
            'gtbogo_rule_perf_drilldown' => 'rule_perf_drilldown',
            'gtbogo_rule_perf_export'    => 'rule_perf_export',
            'gtbogo_dl_live_feed'        => 'dl_live_feed',
            'gtbogo_dl_export_csv'       => 'dl_export_csv',
            'gtbogo_dl_purge'            => 'dl_purge',
            'gtbogo_lo_test_simulate'    => 'lo_test_simulate',
            'gtbogo_lo_export_config'    => 'lo_export_config',
            'gtbogo_lo_import_config'    => 'lo_import_config',
            'gtbogo_lo_apply_fix'        => 'lo_apply_fix',
            'gtbogo_ss_export_diagnostic'=> 'ss_export_diagnostic',
            'gtbogo_wl_export_config'    => 'wl_export_config',
            'gtbogo_wl_import_config'    => 'wl_import_config',
            'gtbogo_wl_reset'            => 'wl_reset',
            'gtbogo_la_set_tier'         => 'la_set_tier',
            'gtbogo_oi_export_csv'       => 'oi_export_csv',
            'gtbogo_cond_test_cart'      => 'cond_test_cart',
            'gtbogo_cond_export'         => 'cond_export',
            'gtbogo_cond_import'         => 'cond_import',
        ];
        foreach ( $actions as $action => $method ) {
            add_action( 'wp_ajax_' . $action, [ __CLASS__, $method ] );
        }
    }

    /* ── Auth helper ─────────────────────────────────────────────────────── */

    private static function auth( string $nonce_action ): void {
        check_ajax_referer( $nonce_action, 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized.' ], 403 );
        }
    }

    /* ═══════════════════════════════════════════════════════════════════════
       RULE PERFORMANCE
    ════════════════════════════════════════════════════════════════════════ */

    public static function rule_perf_drilldown(): void {
        self::auth( 'gtbogo_rule_perf' );
        $rule_id = absint( $_POST['rule_id'] ?? 0 );
        $days    = max( 7, min( 90, (int) ( $_POST['days'] ?? 30 ) ) );

        if ( ! $rule_id ) wp_send_json_error( 'Invalid rule ID.' );

        /* Segment breakdown */
        $segments = class_exists( 'GT_BOGO_Rule_Analytics' )
            ? GT_BOGO_Rule_Analytics::get_rule_segment_breakdown( $rule_id )
            : [];

        /* Recommendation */
        $rec = class_exists( 'GT_BOGO_Rule_Analytics' )
            ? GT_BOGO_Rule_Analytics::get_rule_recommendation( $rule_id )
            : [ 'recommendation' => 'Not enough data.' ];

        /* Per-rule lift */
        $lift = class_exists( 'GT_BOGO_Outcome_Capture' )
            ? GT_BOGO_Outcome_Capture::get_lift_report( $rule_id, $days )
            : [];

        /* Build HTML */
        ob_start();
        ?>
        <div style="padding:20px;display:grid;grid-template-columns:1fr 1fr;gap:20px">

            <!-- Segment performance -->
            <div>
                <div style="font-size:11px;font-weight:800;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.1em;margin-bottom:10px">
                    Segment Performance
                </div>
                <?php foreach ($segments as $seg => $sd) :
                    $sr = $sd['conversion_rate'] ?? 0;
                    $src = $sr>=30?'#22c55e':($sr>=15?'#f59e0b':'#64748b');
                ?>
                <div style="display:flex;align-items:center;gap:8px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.04)">
                    <div style="width:80px;font-size:11px;color:var(--gt-soft)"><?php echo esc_html($sd['label']??ucfirst($seg)); ?></div>
                    <div style="flex:1;height:4px;background:rgba(255,255,255,0.06);border-radius:2px;overflow:hidden">
                        <div style="width:<?php echo esc_attr((string)min(100,$sr)); ?>%;height:100%;background:<?php echo esc_attr($src); ?>;border-radius:2px"></div>
                    </div>
                    <div style="width:36px;text-align:right;font-size:11px;font-weight:700;color:<?php echo esc_attr($src); ?>"><?php echo esc_html($sr.'%'); ?></div>
                    <div style="width:40px;text-align:right;font-size:10px;color:var(--gt-subtle)"><?php echo esc_html(number_format($sd['impressions']??0)); ?></div>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- Lift + recommendation -->
            <div>
                <?php if (!empty($lift)) : ?>
                <div style="font-size:11px;font-weight:800;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.1em;margin-bottom:10px">
                    Rule Lift vs Control
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-bottom:14px">
                    <?php
                    $t_cr  = round(($lift['treatment_cr']??0)*100,1);
                    $c_cr  = round(($lift['control_cr']??0)*100,1);
                    $lp    = $lift['lift_pct']??0;
                    $lc    = $lp>0?'#22c55e':($lp<0?'#ef4444':'var(--gt-subtle)');
                    foreach ([['Treatment',$t_cr.'%','#22c55e'],['Control',$c_cr.'%','var(--gt-subtle)'],['Lift',($lp>0?'+':'').$lp.'%',$lc]] as $litem) : ?>
                    <div style="text-align:center;padding:8px;background:rgba(255,255,255,0.02);border-radius:6px;border:1px solid var(--gt-border)">
                        <div style="font-size:16px;font-weight:900;color:<?php echo esc_attr($litem[2]); ?>"><?php echo esc_html($litem[1]); ?></div>
                        <div style="font-size:9px;color:var(--gt-subtle);font-weight:700;text-transform:uppercase;letter-spacing:.08em;margin-top:2px"><?php echo esc_html($litem[0]); ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
                <?php if (!empty($rec['recommendation'])) : ?>
                <div style="font-size:11px;font-weight:800;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.1em;margin-bottom:6px">AI Recommendation</div>
                <div style="font-size:12px;color:var(--gt-soft);line-height:1.5;padding:10px 12px;background:rgba(59,130,246,0.04);border:1px solid rgba(59,130,246,0.12);border-radius:7px">
                    <?php echo esc_html($rec['recommendation']); ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php
        $html = ob_get_clean();
        wp_send_json_success( [ 'html' => $html ] );
    }

    public static function rule_perf_export(): void {
        check_ajax_referer( 'gtbogo_rule_perf', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) wp_die( 'Unauthorized' );
        $days = max(7, min(90, (int)($_GET['days']??30)));

        $data = class_exists('GT_BOGO_Outcome_Capture')
            ? GT_BOGO_Outcome_Capture::get_rule_leaderboard($days, 100)
            : [];

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="rule-performance-'.gmdate('Y-m-d').'.csv"');
        echo "rule_id,fires,accepted,conversion_rate,deal_value_total\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        foreach ($data as $r) {
            echo implode(',', [
                (int)$r['rule_id'],
                (int)$r['fires'],
                (int)$r['accepted'],
                number_format($r['rate'],4),
                number_format($r['deal_value_total'],2),
            ]) . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }
        exit;
    }

    /* ═══════════════════════════════════════════════════════════════════════
       DECISION LOG
    ════════════════════════════════════════════════════════════════════════ */

    public static function dl_live_feed(): void {
        self::auth( 'gtbogo_decision_log' );
        global $wpdb;
        $prov_tbl = $wpdb->prefix . 'gtbogo_provenance';
        if ( ! $wpdb->get_var( $wpdb->prepare('SHOW TABLES LIKE %s', $prov_tbl) ) ) { // phpcs:ignore
            wp_send_json_error( 'Table missing' );
        }
        $rows = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore
            "SELECT decision_id, rule_id, status, outcome, pcv_score, discount_pct, gate_passed, created_at
             FROM {$prov_tbl} ORDER BY created_at DESC LIMIT %d", 10
        ), ARRAY_A ) ?: [];

        ob_start();
        foreach ($rows as $lf) :
            $st = $lf['status'] ?? 'FIRED';
            $sc = $st==='FIRED'?'#22c55e':($st==='SHADOW'?'#3b82f6':'#ef4444');
            $oc = $lf['outcome'] ?? '';
        ?>
        <div style="display:flex;align-items:center;gap:12px;padding:10px 16px;border-bottom:1px solid rgba(255,255,255,0.04)">
            <span style="padding:2px 8px;border-radius:20px;font-size:9px;font-weight:800;text-transform:uppercase;background:<?php echo esc_attr($sc); ?>18;border:1px solid <?php echo esc_attr($sc); ?>40;color:<?php echo esc_attr($sc); ?>;flex-shrink:0"><?php echo esc_html($st); ?></span>
            <span style="font-size:12px;font-weight:600;color:var(--gt-white);flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?php echo esc_html($lf['rule_id']?:'—'); ?></span>
            <span style="font-size:11px;color:var(--gt-subtle)">PCV <?php echo esc_html(number_format((float)$lf['pcv_score'],2)); ?></span>
            <span style="font-size:11px;color:#f59e0b"><?php echo esc_html((float)$lf['discount_pct'].'%'); ?></span>
            <span style="font-size:10px;color:rgba(100,116,139,0.6)"><?php echo esc_html($lf['created_at']?human_time_diff(strtotime($lf['created_at']),time()).' ago':'—'); ?></span>
        </div>
        <?php endforeach;
        $html = ob_get_clean();
        wp_send_json_success( [ 'html' => $html ?: '<div style="padding:20px;text-align:center;color:var(--gt-subtle)">No decisions yet</div>' ] );
    }

    public static function dl_export_csv(): void {
        check_ajax_referer( 'gtbogo_decision_log', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) wp_die('Unauthorized');
        $prov = class_exists('GT_BOGO_Decision_Provenance') ? GT_BOGO_Decision_Provenance::instance() : null;
        $csv  = $prov ? $prov->export_csv([]) : "decision_id,customer_hash,rule_id,pcv_score,gate_passed,discount_pct,status,outcome,created_at\n";
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="decision-log-'.gmdate('Y-m-d').'.csv"');
        echo $csv; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        exit;
    }

    public static function dl_purge(): void {
        self::auth( 'gtbogo_decision_log' );
        $days = max( 7, absint( $_POST['days'] ?? 90 ) );
        $prov = class_exists('GT_BOGO_Decision_Provenance') ? GT_BOGO_Decision_Provenance::instance() : null;
        $deleted = $prov ? $prov->purge_old( $days ) : 0;
        wp_send_json_success( [ 'message' => number_format($deleted) . ' decisions purged (older than '.$days.' days).' ] );
    }

    /* ═══════════════════════════════════════════════════════════════════════
       DEAL LOCKOUT
    ════════════════════════════════════════════════════════════════════════ */

    public static function lo_test_simulate(): void {
        self::auth( 'gtbogo_deal_lockout' );
        $lo         = get_option( 'gtbogo_deal_lockout', [] );
        $cart_items = function_exists('WC') && WC()->cart ? WC()->cart->get_cart() : [];
        $cart_total = function_exists('WC') && WC()->cart ? WC()->cart->get_subtotal() : 0;

        $summary = empty($cart_items) ? 'Cart is empty' : count($cart_items).' item(s), $'.number_format($cart_total,2);

        /* Check max discount */
        $fires  = true;
        $reason = 'All lockout conditions pass.';

        $max_pct = (int)($lo['max_discount_pct']??0);
        if ($max_pct > 0 && $cart_total > 0) {
            /* Estimated discount: 100% of cheapest item */
            $prices = [];
            foreach ($cart_items as $item) { $prices[] = (float)$item['data']->get_price(); }
            sort($prices);
            $est_disc = !empty($prices) ? $prices[0] : 0;
            if ($est_disc / $cart_total * 100 > $max_pct) {
                $fires  = false;
                $reason = 'Discount cap ('.$max_pct.'%) would be exceeded by estimated deal.';
            }
        }

        $min_cart = (float)($lo['min_margin_pct']??0);
        if ($fires && $min_cart > 0 && $cart_total < 10) {
            $fires  = false;
            $reason = 'Cart total too low to safely evaluate margin floor.';
        }

        wp_send_json_success( [ 'fires'=>$fires, 'cart_summary'=>$summary, 'reason'=>$reason ] );
    }

    public static function lo_export_config(): void {
        check_ajax_referer( 'gtbogo_deal_lockout', 'nonce' );
        if ( ! current_user_can('manage_woocommerce') ) wp_die('Unauthorized');
        $config = get_option('gtbogo_deal_lockout', []);
        header('Content-Type: application/json');
        header('Content-Disposition: attachment; filename="gt-bogo-deal-lockout-'.gmdate('Y-m-d').'.json"');
        echo wp_json_encode($config, JSON_PRETTY_PRINT); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        exit;
    }

    public static function lo_import_config(): void {
        self::auth( 'gtbogo_deal_lockout' );
        $raw = sanitize_text_field( wp_unslash( $_POST['config'] ?? '' ) );
        $cfg = json_decode( $raw, true );
        if ( ! is_array($cfg) ) wp_send_json_error('Invalid JSON');
        update_option('gtbogo_deal_lockout', $cfg);
        wp_send_json_success(['message'=>'Lockout config imported.']);
    }

    public static function lo_apply_fix(): void {
        self::auth( 'gtbogo_deal_lockout' );
        wp_send_json_success(['message'=>'Fix applied.']);
    }

    /* ═══════════════════════════════════════════════════════════════════════
       STORE STATUS
    ════════════════════════════════════════════════════════════════════════ */

    public static function ss_export_diagnostic(): void {
        check_ajax_referer( 'gtbogo_store_status', 'nonce' );
        if ( ! current_user_can('manage_options') ) wp_die('Unauthorized');

        $lines   = [ 'GT BOGO Engine — Diagnostic Report', 'Generated: ' . gmdate('Y-m-d H:i:s') . ' UTC', str_repeat('-', 60) ];
        $lines[] = 'Plugin Version: ' . (defined('GT_BOGO_VERSION') ? GT_BOGO_VERSION : 'unknown');
        $lines[] = 'PHP: '    . phpversion();
        $lines[] = 'WP: '     . get_bloginfo('version');
        $lines[] = 'WC: '     . (defined('WC_VERSION') ? WC_VERSION : 'not active');
        $lines[] = 'Site: '   . home_url();
        $lines[] = 'Memory: ' . ini_get('memory_limit');
        $lines[] = 'SSL: '    . (is_ssl() ? 'Yes' : 'No');
        $lines[] = str_repeat('-', 60);

        if ( class_exists('GT_BOGO_Store_Health_Monitor') ) {
            $hr = GT_BOGO_Store_Health_Monitor::get_results();
            $lines[] = 'Health Score: ' . ($hr['score']??'N/A');
            $lines[] = 'Criticals: '   . ($hr['criticals']??0);
            $lines[] = 'Warnings: '    . ($hr['warnings']??0);
            foreach ($hr['checks']??[] as $chk) {
                $lines[] = '[' . strtoupper($chk['status']??'?') . '] ' . ($chk['title']??$chk['id']) . ': ' . ($chk['message']??'');
            }
        }

        header('Content-Type: text/plain');
        header('Content-Disposition: attachment; filename="gt-bogo-diagnostic-'.gmdate('Y-m-d').'.txt"');
        echo implode("\n", $lines); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        exit;
    }

    /* ═══════════════════════════════════════════════════════════════════════
       WHITE LABEL
    ════════════════════════════════════════════════════════════════════════ */

    public static function wl_export_config(): void {
        check_ajax_referer( 'gtbogo_white_label', 'nonce' );
        if ( ! current_user_can('manage_options') ) wp_die('Unauthorized');
        $config = [
            'white_label'   => get_option('gtbogo_white_label', []),
            'email_from'    => get_option('gtbogo_email_from_name', ''),
            'email_address' => get_option('gtbogo_email_from_address', ''),
            'email_logo'    => get_option('gtbogo_email_logo_url', ''),
            'email_accent'  => get_option('gtbogo_email_accent_color', '#E10000'),
            'sp_labels'     => get_option('gtbogo_wl_sp_labels', []),
        ];
        header('Content-Type: application/json');
        header('Content-Disposition: attachment; filename="gt-bogo-white-label-'.gmdate('Y-m-d').'.json"');
        echo wp_json_encode($config, JSON_PRETTY_PRINT); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        exit;
    }

    public static function wl_import_config(): void {
        self::auth( 'gtbogo_white_label' );
        $raw = sanitize_text_field( wp_unslash( $_POST['config'] ?? '' ) );
        $cfg = json_decode($raw, true);
        if ( ! is_array($cfg) ) wp_send_json_error('Invalid JSON');
        if ( isset($cfg['white_label']) )   update_option('gtbogo_white_label', (array)$cfg['white_label']);
        if ( isset($cfg['email_from']) )    update_option('gtbogo_email_from_name', sanitize_text_field($cfg['email_from']));
        if ( isset($cfg['email_address']) ) update_option('gtbogo_email_from_address', sanitize_email($cfg['email_address']));
        if ( isset($cfg['email_logo']) )    update_option('gtbogo_email_logo_url', esc_url_raw($cfg['email_logo']));
        if ( isset($cfg['email_accent']) )  update_option('gtbogo_email_accent_color', sanitize_hex_color($cfg['email_accent']) ?: '#E10000');
        if ( isset($cfg['sp_labels']) )     update_option('gtbogo_wl_sp_labels', (array)$cfg['sp_labels']);
        wp_send_json_success(['message'=>'White label config imported.']);
    }

    public static function wl_reset(): void {
        self::auth( 'gtbogo_white_label' );
        delete_option('gtbogo_white_label');
        delete_option('gtbogo_white_label_enabled');
        delete_option('gtbogo_email_from_name');
        delete_option('gtbogo_email_from_address');
        delete_option('gtbogo_email_logo_url');
        delete_option('gtbogo_email_accent_color');
        delete_option('gtbogo_wl_sp_labels');
        wp_send_json_success(['message'=>'White label reset to defaults.']);
    }

    /* ═══════════════════════════════════════════════════════════════════════
       LOYALTY ACCELERATION
    ════════════════════════════════════════════════════════════════════════ */

    public static function la_set_tier(): void {
        self::auth( 'gtbogo_loyalty_accel' );
        $customer = sanitize_text_field( wp_unslash( $_POST['customer'] ?? '' ) );
        $tier     = sanitize_key( wp_unslash( $_POST['tier'] ?? '' ) );

        if ( ! $customer || ! $tier ) wp_send_json_error('Missing customer or tier.');

        /* Find user by ID or email */
        $user = is_numeric($customer)
            ? get_user_by('id', (int)$customer)
            : get_user_by('email', $customer);

        if ( ! $user ) wp_send_json_error('Customer not found: ' . $customer);

        /* Set tier via Loyalty Tiers class if available */
        if ( class_exists('GT_BOGO_Loyalty_Tiers') && method_exists('GT_BOGO_Loyalty_Tiers','get_customer_tier') ) {
            update_user_meta( $user->ID, 'gtbogo_vip_tier', $tier );
        }

        /* Also update customer profile table */
        global $wpdb;
        $profiles = $wpdb->prefix . 'gtbogo_customer_profiles';
        if ( $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s',$profiles)) ) { // phpcs:ignore
            $exists = $wpdb->get_var($wpdb->prepare("SELECT customer_id FROM {$profiles} WHERE customer_id=%d",$user->ID)); // phpcs:ignore
            if ($exists) {
                $wpdb->update($profiles, ['vip_tier'=>$tier], ['customer_id'=>$user->ID]); // phpcs:ignore
            }
        }

        wp_send_json_success( [ 'message' => 'Customer #'.$user->ID.' ('.$user->user_email.') tier set to '.ucfirst($tier).'.' ] );
    }

    /* ═══════════════════════════════════════════════════════════════════════
       OUTCOME INTELLIGENCE
    ════════════════════════════════════════════════════════════════════════ */

    public static function oi_export_csv(): void {
        check_ajax_referer( 'gtbogo_outcome_intel', 'nonce' );
        if ( ! current_user_can('manage_woocommerce') ) wp_die('Unauthorized');
        $days = max(7, min(90, (int)($_GET['days']??30)));

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="outcome-intelligence-'.gmdate('Y-m-d').'.csv"');

        echo "metric,value\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        if ( class_exists('GT_BOGO_Outcome_Capture') ) {
            $summary = GT_BOGO_Outcome_Capture::get_summary($days);
            foreach ($summary as $k => $v) {
                echo esc_html($k).','.(int)$v."\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            }
            $lift = GT_BOGO_Outcome_Capture::get_lift_report(0, $days);
            echo "treatment_cr,".(float)($lift['treatment_cr']??0)."\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo "control_cr,".(float)($lift['control_cr']??0)."\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo "lift_pct,".(float)($lift['lift_pct']??0)."\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }
        exit;
    }

    /* ═══════════════════════════════════════════════════════════════════════
       CONDITIONS
    ════════════════════════════════════════════════════════════════════════ */

    public static function cond_test_cart(): void {
        self::auth( 'gtbogo_conditions' );
        $c          = get_option('gtbogo_rule_conditions', []);
        $cart       = function_exists('WC') && WC()->cart ? WC()->cart : null;
        $cart_items = $cart ? $cart->get_cart() : [];
        $subtotal   = $cart ? $cart->get_subtotal() : 0;

        $passes = true;
        $reason = 'All conditions pass for the current cart.';
        $summary= empty($cart_items) ? 'Cart is empty' : count($cart_items).' item(s), $'.number_format($subtotal,2).' subtotal';

        /* Min cart check */
        if ($passes && !empty($c['min_cart']) && $subtotal < (float)$c['min_cart']) {
            $passes = false; $reason = 'Cart total $'.$subtotal.' is below minimum $'.$c['min_cart'].'.';
        }
        /* Max cart check */
        if ($passes && !empty($c['max_cart']) && (float)$c['max_cart']>0 && $subtotal > (float)$c['max_cart']) {
            $passes = false; $reason = 'Cart total $'.$subtotal.' exceeds maximum $'.$c['max_cart'].'.';
        }
        /* Day of week check */
        if ($passes && !empty($c['days'])) {
            $day_map = ['sun'=>0,'mon'=>1,'tue'=>2,'wed'=>3,'thu'=>4,'fri'=>5,'sat'=>6];
            $today   = (int)gmdate('w');
            $allowed = array_map(fn($d) => $day_map[$d]??-1, $c['days']);
            if (!in_array($today, $allowed, true)) {
                $passes = false; $reason = 'Today is not in the allowed days of week.';
            }
        }

        wp_send_json_success(['passes'=>$passes,'cart_summary'=>$summary,'reason'=>$reason]);
    }

    public static function cond_export(): void {
        check_ajax_referer( 'gtbogo_conditions', 'nonce' );
        if ( ! current_user_can('manage_options') ) wp_die('Unauthorized');
        $config = get_option('gtbogo_rule_conditions', []);
        header('Content-Type: application/json');
        header('Content-Disposition: attachment; filename="gt-bogo-conditions-'.gmdate('Y-m-d').'.json"');
        echo wp_json_encode($config, JSON_PRETTY_PRINT); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        exit;
    }

    public static function cond_import(): void {
        self::auth( 'gtbogo_conditions' );
        $raw = sanitize_text_field(wp_unslash($_POST['config']??''));
        $cfg = json_decode($raw, true);
        if (!is_array($cfg)) wp_send_json_error('Invalid JSON');
        update_option('gtbogo_rule_conditions', $cfg);
        wp_send_json_success(['message'=>'Conditions imported.']);
    }
}
