<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Read-only system audit helpers for developer QA and release readiness.
 */
class AIFLT_System_Audit {

    public static function table_exists(string $table): bool {
        global $wpdb;
        return $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) === $table;
    }

    public static function get_tracking_audit(): array {
        global $wpdb;
        $funnel = $wpdb->prefix . 'aiflt_funnel_data';
        $behavior = $wpdb->prefix . 'aiflt_behavior_data';
        $funnel_exists = self::table_exists($funnel);
        $behavior_exists = self::table_exists($behavior);

        $rows = $funnel_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM {$funnel}") : 0;
        $behavior_rows = $behavior_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM {$behavior}") : 0;
        $recent = $funnel_exists ? (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$funnel} WHERE timestamp >= %s", gmdate('Y-m-d H:i:s', strtotime('-7 days')))) : 0;
        $steps = [];
        if ($funnel_exists) {
            $steps = $wpdb->get_results("SELECT page_name, COUNT(*) total FROM {$funnel} GROUP BY page_name ORDER BY total DESC", ARRAY_A) ?: [];
        }

        return [
            'tracking_enabled' => get_option('aiflt_enable_tracking', '1') === '1',
            'woocommerce_active' => class_exists('WooCommerce'),
            'funnel_table' => $funnel_exists,
            'behavior_table' => $behavior_exists,
            'funnel_rows' => $rows,
            'behavior_rows' => $behavior_rows,
            'recent_7_day_events' => $recent,
            'steps' => $steps,
        ];
    }

    public static function get_purchase_conversion_audit(): array {
        global $wpdb;
        $funnel = $wpdb->prefix . 'aiflt_funnel_data';
        $funnel_exists = self::table_exists($funnel);
        $sales_events = $funnel_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM {$funnel} WHERE page_name = 'checkout_attempt'") : 0;
        $order_events = $funnel_exists ? (int) $wpdb->get_var("SELECT COUNT(DISTINCT order_id) FROM {$funnel} WHERE order_id IS NOT NULL AND order_id > 0") : 0;

        $wc_counts = [];
        if (function_exists('wc_get_orders')) {
            foreach (['pending', 'processing', 'completed', 'failed', 'cancelled', 'refunded'] as $status) {
                $orders = wc_get_orders(['status' => $status, 'limit' => 1, 'return' => 'ids']);
                // Avoid expensive full counts on very large stores; this is a readiness indicator.
                $wc_counts[$status] = is_array($orders) ? count($orders) : 0;
            }
        }

        return [
            'sales_events' => $sales_events,
            'order_id_events' => $order_events,
            'woocommerce_order_status_sample' => $wc_counts,
            'recommendation' => __('Verify manually that failed, cancelled, and refunded orders are not counted as completed conversions.', 'ai-flash-tune'),
        ];
    }

    public static function get_cart_recovery_audit(): array {
        global $wpdb;
        $tokens = $wpdb->prefix . 'aiftcr_recovery_tokens';
        $email_log = $wpdb->prefix . 'aiftcr_email_log';
        $tokens_exists = self::table_exists($tokens);
        $email_exists = self::table_exists($email_log);
        return [
            'token_table' => $tokens_exists,
            'email_log_table' => $email_exists,
            'tokens' => $tokens_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM {$tokens}") : 0,
            'clicked_tokens' => $tokens_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM {$tokens} WHERE clicked_at IS NOT NULL") : 0,
            'recovered_orders' => $tokens_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM {$tokens} WHERE recovered_order_id IS NOT NULL AND recovered_order_id > 0") : 0,
            'emails_logged' => $email_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM {$email_log}") : 0,
        ];
    }

    public static function get_ai_audit(): array {
        $actions = class_exists('AIFLT_AI_Action_Registry') ? AIFLT_AI_Action_Registry::all() : [];
        $missing = [];
        foreach ($actions as $key => $action) {
            if (empty($action['zywrap_wrapper_code'])) {
                $missing[] = $key;
            }
        }
        return [
            'provider_status' => class_exists('AIFLT_AI_Service') ? AIFLT_AI_Service::get_status_label() : __('AI service not loaded.', 'ai-flash-tune'),
            'registered_actions' => count($actions),
            'missing_wrapper_codes' => $missing,
            'usage_stats' => class_exists('AIFLT_AI_Usage_Log') ? AIFLT_AI_Usage_Log::stats(30) : [],
        ];
    }

    public static function readiness_items(): array {
        $tracking = self::get_tracking_audit();
        $cart = self::get_cart_recovery_audit();
        $ai = self::get_ai_audit();
        return [
            ['label' => __('WooCommerce active', 'ai-flash-tune'), 'ok' => !empty($tracking['woocommerce_active'])],
            ['label' => __('Tracking enabled', 'ai-flash-tune'), 'ok' => !empty($tracking['tracking_enabled'])],
            ['label' => __('Funnel table available', 'ai-flash-tune'), 'ok' => !empty($tracking['funnel_table'])],
            ['label' => __('Behavior table available', 'ai-flash-tune'), 'ok' => !empty($tracking['behavior_table'])],
            ['label' => __('AI action registry loaded', 'ai-flash-tune'), 'ok' => !empty($ai['registered_actions'])],
            ['label' => __('All registry actions have wrapper codes', 'ai-flash-tune'), 'ok' => empty($ai['missing_wrapper_codes'])],
            ['label' => __('Cart recovery token table available', 'ai-flash-tune'), 'ok' => !empty($cart['token_table']) || !class_exists('AIFTCR_Logic')],
        ];
    }
}
