<?php

/**
 * Plugin Activator
 * Tự động cài đặt các API key mặc định khi plugin được kích hoạt
 */

class Ai_auto_tool_Activator {
	
	/**
	 * Activate plugin
	 * Tự động cài đặt các API key mặc định từ file default-api-keys.php
	 */
	public static function activate() {
		// Load default API keys file
		$plugin_dir = plugin_dir_path( __FILE__ ) . '../../';
		$default_keys_file = $plugin_dir . 'inc/default-api-keys.php';
		
		if ( file_exists( $default_keys_file ) ) {
			require_once $default_keys_file;
			
			// Get default keys
			if ( function_exists( 'aiautotool_get_default_api_keys' ) ) {
				$default_keys = aiautotool_get_default_api_keys();
				
				// Only proceed if we have default keys
				if ( ! empty( $default_keys ) && is_array( $default_keys ) ) {
					// Load API Keys Manager class
					$api_keys_file = $plugin_dir . 'inc/ai-providers/aiautotool_ai_provider_api_keys.php';
					if ( file_exists( $api_keys_file ) ) {
						// Define ABSPATH if not already defined (for direct access)
						if ( ! defined( 'ABSPATH' ) ) {
							define( 'ABSPATH', dirname( dirname( dirname( dirname( dirname( __FILE__ ) ) ) ) ) . '/' );
						}
						
						require_once $api_keys_file;
						
						// Install default keys for each provider
						if ( class_exists( 'AIAutotool_AI_Provider_API_Keys' ) ) {
							$api_manager = AIAutotool_AI_Provider_API_Keys::get_instance();
							
							foreach ( $default_keys as $provider => $keys ) {
								if ( ! empty( $keys ) && is_array( $keys ) ) {
									// Check if provider already has keys
									$existing_keys = $api_manager->get_all_keys( $provider );
									
									// Only install if no keys exist
									if ( empty( $existing_keys ) ) {
										foreach ( $keys as $key_data ) {
											if ( isset( $key_data['key'] ) && ! empty( trim( $key_data['key'] ) ) ) {
												$key_name = isset( $key_data['name'] ) && ! empty( $key_data['name'] ) ? $key_data['name'] : 'Default Key';
												$result = $api_manager->add_key( $provider, $key_data['key'], $key_name );
												
												// Log success/failure in debug mode
												if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
													if ( isset( $result['success'] ) && $result['success'] ) {
													} else {
														$message = isset( $result['message'] ) ? $result['message'] : 'Unknown error';
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}

}
