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

/**
 * Plugin Activation Handler
 *
 * Creates database tables, sets default options, and schedules events
 * 
 * Note: The following entities use Custom Post Types instead of custom tables:
 * - Chatbots (ai_chatbot CPT)
 * - AI Content (ai_content CPT)
 * - AI Forms (ai_form CPT)
 * - KB Sources (ai_kb_source CPT)
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes
 */

class Kitsune_AI_Platform_Activator {

    /**
     * Activate the plugin
     *
     * Sets default plugin options and schedules recurring events
     */
    public static function activate() {
        self::create_tables();
        self::set_default_options();
        self::schedule_events();
        self::create_directories();
        self::restore_scheduled_tasks();

        // Flush rewrite rules
        flush_rewrite_rules();
    }

    /**
     * Create custom database tables
     * 
     * Only creates tables for high-volume data that cannot efficiently use CPT:
     * - Form submissions
     * - Stats/Analytics
     * - Conversations
     * - Embeddings
     * - Logs
     */
    private static function create_tables() {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();

        // Form submissions table (high volume - kept as custom table)
        $table_submissions = $wpdb->prefix . 'kitsune_ai_platform_form_submissions';
        $sql_submissions = "CREATE TABLE IF NOT EXISTS {$table_submissions} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            form_id bigint(20) NOT NULL,
            data longtext NOT NULL,
            ai_result longtext,
            status varchar(20) DEFAULT 'new',
            user_ip varchar(45),
            user_agent text,
            user_id bigint(20) DEFAULT NULL,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY form_id (form_id),
            KEY status (status),
            KEY user_id (user_id)
        ) {$charset_collate};";

        // Analytics/stats table (time-series aggregation)
        $table_stats = $wpdb->prefix . 'kitsune_ai_platform_stats';
        $sql_stats = "CREATE TABLE IF NOT EXISTS {$table_stats} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            stat_type varchar(50) NOT NULL,
            stat_key varchar(100) NOT NULL,
            stat_value longtext,
            date date NOT NULL,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY stat_type (stat_type),
            KEY date (date),
            KEY stat_key (stat_key)
        ) {$charset_collate};";

        // Conversations table (high volume chat logs)
        $table_conversations = $wpdb->prefix . 'kitsune_ai_platform_conversations';
        $sql_conversations = "CREATE TABLE IF NOT EXISTS {$table_conversations} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            chatbot_id bigint(20) NOT NULL,
            user_identifier varchar(255),
            messages longtext NOT NULL,
            sentiment varchar(20),
            satisfaction_rating int DEFAULT NULL,
            duration int DEFAULT 0,
            tokens_used int DEFAULT 0,
            cost decimal(10,4) DEFAULT 0.0000,
            lead_captured tinyint(1) DEFAULT 0,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY chatbot_id (chatbot_id),
            KEY user_identifier (user_identifier),
            KEY sentiment (sentiment),
            KEY created_at (created_at)
        ) {$charset_collate};";

        // Embeddings table (vector storage - specialized queries)
        $table_embeddings = $wpdb->prefix . 'kitsune_ai_platform_embeddings';
        $sql_embeddings = "CREATE TABLE IF NOT EXISTS {$table_embeddings} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            source_id bigint(20) NOT NULL,
            content_id bigint(20),
            chunk_text longtext NOT NULL,
            vector_id varchar(255),
            vector_db varchar(50),
            model varchar(50),
            tokens_used int DEFAULT 0,
            status varchar(20) DEFAULT 'pending',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY source_id (source_id),
            KEY content_id (content_id),
            KEY vector_id (vector_id),
            KEY status (status)
        ) {$charset_collate};";

        // Workflow logs table (execution history with trace support)
        $table_workflow_logs = $wpdb->prefix . 'kitsune_ai_platform_workflow_logs';
        $sql_workflow_logs = "CREATE TABLE IF NOT EXISTS {$table_workflow_logs} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            trace_id varchar(36) DEFAULT NULL,
            workflow_id bigint(20) NOT NULL DEFAULT 0,
            log_type varchar(50) NOT NULL DEFAULT 'execution',
            level varchar(20) NOT NULL DEFAULT 'info',
            status varchar(20) NOT NULL DEFAULT 'info',
            message text,
            execution_data longtext,
            context longtext,
            error_message text,
            duration int DEFAULT 0,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY trace_id (trace_id),
            KEY workflow_id (workflow_id),
            KEY log_type (log_type),
            KEY level (level),
            KEY status (status),
            KEY created_at (created_at)
        ) {$charset_collate};";

        // API usage logs table (usage tracking)
        $table_api_logs = $wpdb->prefix . 'kitsune_ai_platform_api_logs';
        $sql_api_logs = "CREATE TABLE IF NOT EXISTS {$table_api_logs} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            provider varchar(50) NOT NULL,
            model varchar(50) NOT NULL,
            feature varchar(50),
            tokens_input int DEFAULT 0,
            tokens_output int DEFAULT 0,
            cost decimal(10,4) DEFAULT 0.0000,
            duration int DEFAULT 0,
            status varchar(20) NOT NULL,
            user_id bigint(20),
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY provider (provider),
            KEY model (model),
            KEY feature (feature),
            KEY created_at (created_at)
        ) {$charset_collate};";

        // Note: ai_platform_logs table removed - workflow logs now use ai_platform_workflow_logs with trace support

        // Audit log table (security logging)
        $table_audit = $wpdb->prefix . 'kitsune_ai_platform_audit_log';
        $sql_audit = "CREATE TABLE IF NOT EXISTS {$table_audit} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            env_type varchar(50) NOT NULL,
            action varchar(50) NOT NULL,
            user_id bigint(20) DEFAULT NULL,
            ip_address varchar(45),
            timestamp datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY env_type (env_type),
            KEY user_id (user_id)
        ) {$charset_collate};";

        // Execute table creation
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql_submissions);
        dbDelta($sql_stats);
        dbDelta($sql_conversations);
        dbDelta($sql_embeddings);
        dbDelta($sql_workflow_logs);
        dbDelta($sql_api_logs);
        dbDelta($sql_audit);

        // Update database version
        update_option('kitsune_ai_platform_db_version', '1.3.0');
    }

    /**
     * Set default plugin options
     */
    private static function set_default_options() {
        $default_settings = array(
            'version'           => KITSUNE_AI_PLATFORM_VERSION,
            'openai_api_key'    => '',
            'claude_api_key'    => '',
            'gemini_api_key'    => '',
            'mistral_api_key'   => '',
            'default_model'     => KITSUNE_AI_PLATFORM_DEFAULT_MODEL,
            'budget_limit'      => 500,
            'budget_period'     => 'monthly',
            'enable_analytics'  => true,
            'cache_enabled'     => true,
            'cache_duration'    => 3600,
            'debug_mode'        => false,
            'gdpr_enabled'      => true,
            'data_retention'    => 90,
            'admin_email'       => get_option('admin_email'),
            'notifications'     => array(
                'api_errors'        => true,
                'budget_alerts'     => true,
                'workflow_failures' => true,
                'weekly_summary'    => false,
            ),
        );

        // Only add if not exists
        if (!get_option('kitsune_ai_platform_settings')) {
            add_option('kitsune_ai_platform_settings', $default_settings);
        }

    }

    /**
     * Schedule recurring events
     */
    private static function schedule_events() {
        // Schedule daily stats aggregation
        if (!wp_next_scheduled('kitsune_ai_platform_daily_stats')) {
            wp_schedule_event(time(), 'daily', 'kitsune_ai_platform_daily_stats');
        }

        // Schedule weekly summary email
        if (!wp_next_scheduled('kitsune_ai_platform_weekly_summary')) {
            wp_schedule_event(time(), 'weekly', 'kitsune_ai_platform_weekly_summary');
        }

        // Schedule cleanup of old logs
        if (!wp_next_scheduled('kitsune_ai_platform_cleanup_logs')) {
            wp_schedule_event(time(), 'daily', 'kitsune_ai_platform_cleanup_logs');
        }
    }

    /**
     * Reschedule WP-Cron events for all active scheduled tasks.
     * Runs on every activation so cron events survive plugin updates / reactivations.
     */
    private static function restore_scheduled_tasks() {
        // CPT may not be registered yet during early activation, so register it inline.
        if (!post_type_exists('kitsune_ai_sched_task')) {
            register_post_type('kitsune_ai_sched_task', array(
                'public'   => false,
                'supports' => array('title', 'custom-fields'),
            ));
        }

        // Autoloader won't be active yet during activation; require the model directly.
        if (!class_exists('Kitsune_AI_Platform_Scheduled_Task_Model')) {
            require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-scheduled-task-model.php';
        }

        Kitsune_AI_Platform_Scheduled_Task_Model::reschedule_all_active_tasks();
    }

    /**
     * Create necessary directories
     */
    private static function create_directories() {
        $upload_dir = wp_upload_dir();
        $ai_platform_dir = $upload_dir['basedir'] . '/ai-platform';

        // Create main directory
        if (!file_exists($ai_platform_dir)) {
            wp_mkdir_p($ai_platform_dir);
        }

        // Create subdirectories
        $subdirs = array('cache', 'exports', 'temp', 'uploads');
        foreach ($subdirs as $subdir) {
            $path = $ai_platform_dir . '/' . $subdir;
            if (!file_exists($path)) {
                wp_mkdir_p($path);
            }

            // Add .htaccess for security
            $htaccess_file = $path . '/.htaccess';
            if (!file_exists($htaccess_file)) {
                file_put_contents($htaccess_file, 'deny from all');
            }
        }
    }
}
