<?php
/**
 * Uninstall script for AI Product Content & Image Generator
 * 
 * This file is executed when the plugin is uninstalled.
 * It removes all plugin data, options, and database tables.
 * 
 * @package AIProductContentImageGenerator
 * @since 1.0.0
 */

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

// Check if user has permission to uninstall plugins
if (!current_user_can('activate_plugins')) {
    return;
}

// Define plugin constants for uninstall
define('APCIG_PLUGIN_DIR', plugin_dir_path(__FILE__));

// Load autoloader if available
if (file_exists(APCIG_PLUGIN_DIR . 'vendor/autoload.php')) {
    require_once APCIG_PLUGIN_DIR . 'vendor/autoload.php';
}

// Remove plugin options
$apcig_options_to_delete = [
    'apcig_version',
    'apcig_default_provider',
    'apcig_default_tone', 
    'apcig_default_language',
    'apcig_max_tokens',
    'apcig_temperature',
    'apcig_enable_seo_optimization',
    'apcig_enable_content_validation',
    'apcig_enable_duplicate_detection',
    'apcig_auto_apply_content',
    'apcig_backup_original_content',
    'apcig_data_retention_days',
    'apcig_openai_api_key',
    'apcig_claude_api_key',
    'apcig_gemini_api_key',
    'apcig_openrouter_api_key',
    'apcig_settings'
];

foreach ($apcig_options_to_delete as $apcig_option) {
    delete_option($apcig_option);
}

// Remove user meta data
delete_metadata('user', 0, 'apcig_user_preferences', '', true);
delete_metadata('user', 0, 'apcig_generation_history', '', true);

// Drop database tables
global $wpdb;

$apcig_tables_to_drop = [
    $wpdb->prefix . 'apcig_generations',
    $wpdb->prefix . 'apcig_batch_jobs', 
    $wpdb->prefix . 'apcig_api_usage'
];

foreach ($apcig_tables_to_drop as $apcig_table) {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
    $wpdb->query("DROP TABLE IF EXISTS " . esc_sql($apcig_table));
}

// Clear scheduled events
wp_clear_scheduled_hook('apcig_cleanup_old_records');
wp_clear_scheduled_hook('apcig_process_batch');

// Remove any uploaded files in plugin directory
$apcig_upload_dir = wp_upload_dir();
$apcig_plugin_upload_dir = $apcig_upload_dir['basedir'] . '/apcig-generated-images';

if (is_dir($apcig_plugin_upload_dir)) {
    // Remove all files in the directory
    $apcig_files = glob($apcig_plugin_upload_dir . '/*');
    foreach ($apcig_files as $apcig_file) {
        if (is_file($apcig_file)) {
            wp_delete_file($apcig_file);
        }
    }
    // Remove the directory using WP_Filesystem
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    WP_Filesystem();
    global $wp_filesystem;
    $wp_filesystem->rmdir($apcig_plugin_upload_dir);
}

// Clear any cached data
wp_cache_flush();

// Remove transients
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query(
    "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_apcig_%' OR option_name LIKE '_transient_timeout_apcig_%'"
);

// Log uninstall (optional, for debugging)
if (defined('WP_DEBUG') && WP_DEBUG) {
    // Use WordPress logging instead of error_log
    if (function_exists('wp_debug_log')) {
        wp_debug_log('AI Product Content & Image Generator: Plugin uninstalled and all data removed.');
    }
}