<?php
/**
 * Plugin Uninstall Handler
 *
 * Cleans up all plugin data when uninstalled
 *
 * @package    Kitsune_AI_Platform
 */

// If uninstall not called from WordPress, exit
if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

/**
 * Delete all plugin options
 */
function kitsune_ai_platform_delete_options() {
    delete_option('kitsune_ai_platform_settings');
    delete_option('kitsune_ai_platform_db_version');
    delete_option('kitsune_ai_platform_api_keys');
    delete_option('kitsune_ai_platform_default_models');
    delete_option('kitsune_ai_platform_integrations');
    delete_option('kitsune_ai_platform_webhooks');
    delete_option('kitsune_ai_platform_chatbot_templates');
    delete_option('kitsune_ai_platform_access_control');
    delete_option('kitsune_ai_platform_notification_settings');
    delete_option('kitsune_ai_platform_onboarding_complete');
    delete_option('kitsune_ai_platform_form_settings');
    delete_option('kitsune_ai_platform_kb_settings');
    delete_option('kitsune_ai_platform_kb_vector_dbs');
    delete_option('kitsune_ai_platform_kb_last_reset');

    // Delete provider configs
    $providers = array('openai', 'anthropic', 'google', 'mistral', 'cohere');
    foreach ($providers as $provider) {
        delete_option('kitsune_ai_platform_provider_' . $provider);
    }

    // Delete transients
    global $wpdb;
    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM %i WHERE option_name LIKE %s OR option_name LIKE %s",
            $wpdb->options,
            '_transient_kitsune_ai_platform_%',
            '_transient_timeout_kitsune_ai_platform_%'
        )
    );
}

/**
 * Delete all Custom Post Type data
 * 
 * Deletes posts for CPTs: ai_chatbot, ai_content, ai_form, ai_kb_source,
 * ai_chatbot_template, ai_workflow, ai_scheduled_task
 */
function kitsune_ai_platform_delete_cpt_data() {
    $post_types = array(
        'kitsune_ai_chatbot',
        'kitsune_ai_chat_tpl',
        'kitsune_ai_workflow',
        'kitsune_ai_sched_task',
        'kitsune_ai_content',
        'kitsune_ai_form',
        'kitsune_ai_kb_source',
    );

    foreach ($post_types as $post_type) {
        $posts = get_posts(array(
            'post_type'      => $post_type,
            'posts_per_page' => -1,
            'post_status'    => 'any',
            'fields'         => 'ids',
        ));

        foreach ($posts as $post_id) {
            wp_delete_post($post_id, true);
        }
    }

    // Clean up orphaned post meta with our prefix
    global $wpdb;
    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM %i WHERE meta_key LIKE %s",
            $wpdb->postmeta,
            '_ai_platform_%'
        )
    );
}

/**
 * Delete all plugin tables (only for high-volume / log data)
 */
function kitsune_ai_platform_delete_tables() {
    global $wpdb;

    $tables = array(
        $wpdb->prefix . 'kitsune_ai_platform_form_submissions',
        $wpdb->prefix . 'kitsune_ai_platform_stats',
        $wpdb->prefix . 'kitsune_ai_platform_conversations',
        $wpdb->prefix . 'kitsune_ai_platform_embeddings',
        $wpdb->prefix . 'kitsune_ai_platform_workflow_logs',
        $wpdb->prefix . 'kitsune_ai_platform_api_logs',
        $wpdb->prefix . 'kitsune_ai_platform_audit_log',
    );

    foreach ($tables as $table) {
        $table_name = esc_sql($table);
        $wpdb->query($wpdb->prepare("DROP TABLE IF EXISTS %i", $table));
    }
}

/**
 * Delete all plugin files and directories
 */
function kitsune_ai_platform_delete_files() {
    $upload_dir = wp_upload_dir();
    $ai_platform_dir = $upload_dir['basedir'] . '/ai-platform';

    if (file_exists($ai_platform_dir)) {
        kitsune_ai_platform_delete_directory($ai_platform_dir);
    }
}

/**
 * Recursively delete directory
 */
function kitsune_ai_platform_delete_directory($dir) {
    global $wp_filesystem;

    if (empty($wp_filesystem)) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
        WP_Filesystem();
    }

    if (!$wp_filesystem || !$wp_filesystem->is_dir($dir)) {
        return;
    }

    $wp_filesystem->rmdir($dir, true);
}

/**
 * Clear scheduled cron jobs
 */
function kitsune_ai_platform_clear_cron_jobs() {
    $scheduled_hooks = array(
        'kitsune_ai_platform_daily_stats',
        'kitsune_ai_platform_weekly_summary',
        'kitsune_ai_platform_cleanup_logs',
    );

    foreach ($scheduled_hooks as $hook) {
        wp_clear_scheduled_hook($hook);
    }
}

// Check if user wants to delete data (configurable in settings)
$settings = get_option('kitsune_ai_platform_settings', array());
$delete_on_uninstall = $settings['delete_on_uninstall'] ?? true;

if ($delete_on_uninstall) {
    // Perform cleanup
    kitsune_ai_platform_delete_options();
    kitsune_ai_platform_delete_cpt_data();
    kitsune_ai_platform_delete_tables();
    kitsune_ai_platform_delete_files();
    kitsune_ai_platform_clear_cron_jobs();
}
