<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @since 1.0.0
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
namespace Wisewand\Core;

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Wisewand\Database\Database_Manager;
use Wisewand\Database\Database_Schema;
use Wisewand\Database\Database_Upgrader;
use Wisewand\Database\Database_Version;

// phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- error_log() is only used within WP_DEBUG conditionals for debugging; direct database calls and schema changes required for plugin activation, database table creation, and schema migrations

class Activator {

	public static function activate() {
		try {
			// Set plugin version first
			update_option( 'wisewand_plugin_version', WISEWAND_PLUGIN_VERSION );

			// Log non-InnoDB defaults so support can correlate any edge case;
			// CREATE TABLE statements force ENGINE=InnoDB regardless.
			self::check_storage_engine_compatibility();

			// Create database tables if needed
			self::create_database_tables();

			// Set default options
			self::set_default_options();

			// Create initial HMAC secret
			self::generate_initial_secret();

			// Set activation redirect flag
			set_transient( 'wisewand_activation_redirect', true, 30 );

			// Schedule cleanup cron if not exists (but don't fail if it doesn't work)
			if ( function_exists( 'wp_next_scheduled' ) && ! wp_next_scheduled( 'wisewand_cleanup_logs' ) ) {
				wp_schedule_event( time(), 'daily', 'wisewand_cleanup_logs' );
			}

			// Schedule editorial calendar CRON (automation engine)
			if ( function_exists( 'wp_next_scheduled' ) && ! wp_next_scheduled( 'wisewand_editorial_calendar_cron' ) ) {
				$frequency = get_option( 'wisewand_cron_frequency', 'twice_daily' );
				wp_schedule_event( time(), $frequency, 'wisewand_editorial_calendar_cron' );
			}

			// Flush rewrite rules to ensure REST API endpoints work
			if ( function_exists( 'flush_rewrite_rules' ) ) {
				flush_rewrite_rules();
			}
		} catch ( Exception $e ) {
			// Log error but don't prevent activation
			if ( WP_DEBUG ) {
				error_log( 'Wisewand Activation Warning: ' . $e->getMessage() );
			}
		}
	}

	/**
	 * Log a warning when the server's default storage engine is not InnoDB.
	 *
	 * The plugin forces ENGINE=InnoDB on every CREATE TABLE so this is purely
	 * informational — it helps support understand environments where shared
	 * hosts default to MyISAM/Aria (OVH mutualisé, o2switch, LWS, PlanetHoster).
	 *
	 * @since 2.9.13
	 */
	private static function check_storage_engine_compatibility() {
		if ( ! ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) {
			return;
		}

		global $wpdb;
		$engine = $wpdb->get_var( 'SELECT @@default_storage_engine' );
		if ( $engine && 'innodb' !== strtolower( $engine ) ) {
			error_log( 'Wisewand: Server default_storage_engine is ' . $engine . ' — tables will be forced to InnoDB via the ENGINE= clause.' );
		}
	}

	/**
	 * Create database tables
	 *
	 * Uses the new Database_Manager system (v1.0.2+).
	 * All migrations have been merged into clean base schema.
	 *
	 * @since 1.0.2
	 */
	private static function create_database_tables() {
		// Initialize database system
		$success = Database_Manager::initialize();

		if ( ! $success ) {
			global $wpdb;

			$error_message = $wpdb->last_error ?: __( 'Unknown database error', 'wisewand-ai-content-writer-seo-content-generator' );

			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( 'Wisewand: Database initialization failed: ' . $error_message );
			}

			wp_die(
				'<h1>' . esc_html__( 'Wisewand Database Error', 'wisewand-ai-content-writer-seo-content-generator' ) . '</h1>' .
				'<p>' . esc_html__( 'Wisewand could not create required database tables.', 'wisewand-ai-content-writer-seo-content-generator' ) . '</p>' .
				'<p><strong>' . esc_html__( 'Error:', 'wisewand-ai-content-writer-seo-content-generator' ) . '</strong> ' . esc_html( $error_message ) . '</p>' .
				'<hr>' .
				'<p>' . esc_html__( 'Possible causes:', 'wisewand-ai-content-writer-seo-content-generator' ) . '</p>' .
				'<ul>' .
					'<li><strong>' . esc_html__( 'Storage engine:', 'wisewand-ai-content-writer-seo-content-generator' ) . '</strong> ' .
					esc_html__( 'Server default storage engine is MyISAM/Aria instead of InnoDB. Common on shared hosting (OVH mutualisé, o2switch, LWS, PlanetHoster). Ask your host to set default_storage_engine=InnoDB.', 'wisewand-ai-content-writer-seo-content-generator' ) . '</li>' .
					'<li><strong>' . esc_html__( 'Insufficient permissions:', 'wisewand-ai-content-writer-seo-content-generator' ) . '</strong> ' .
					esc_html__( 'Database user needs CREATE TABLE permission', 'wisewand-ai-content-writer-seo-content-generator' ) . '</li>' .
					'<li><strong>' . esc_html__( 'Database connection:', 'wisewand-ai-content-writer-seo-content-generator' ) . '</strong> ' .
					esc_html__( 'Check WordPress database credentials in wp-config.php', 'wisewand-ai-content-writer-seo-content-generator' ) . '</li>' .
					'<li><strong>' . esc_html__( 'MySQL version:', 'wisewand-ai-content-writer-seo-content-generator' ) . '</strong> ' .
					esc_html__( 'Requires MySQL 5.7+ or MariaDB 10.2+', 'wisewand-ai-content-writer-seo-content-generator' ) . '</li>' .
				'</ul>' .
				'<p><a href="' . esc_url( admin_url( 'plugins.php' ) ) . '" class="button button-primary">' .
				esc_html__( 'Return to Plugins', 'wisewand-ai-content-writer-seo-content-generator' ) . '</a></p>',
				esc_html__( 'Database Initialization Failed', 'wisewand-ai-content-writer-seo-content-generator' )
			);
		}

		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( 'Wisewand: Database initialization completed successfully' );
		}
	}

	private static function set_default_options() {
		$defaults = array(
			// Security settings
			'wisewand_hmac_secret'                    => '',
			'wisewand_timestamp_skew'                 => 300,
			'wisewand_ip_whitelist'                   => '',
			'wisewand_rate_limit_enabled'             => true,
			'wisewand_rate_limit_requests'            => 60,
			'wisewand_rate_limit_window'              => 600,
			'wisewand_enable_app_passwords'           => false,

			// Content settings
			'wisewand_allowed_post_types'             => array( 'post', 'page' ),
			'wisewand_default_post_status'            => 'draft',
			'wisewand_fallback_author'                => 1,
			'wisewand_auto_create_categories'         => true,
			'wisewand_auto_create_tags'               => true,
			'wisewand_allow_slug_override'            => true,

			// Media settings
			'wisewand_media_max_size'                 => 5242880,
			'wisewand_media_timeout'                  => 10,
			'wisewand_allowed_mime_types'             => array(
				// Images
				'image/jpeg',
				'image/png',
				'image/webp',
				'image/gif',

				// Audio - Standard MIME types
				'audio/mpeg',      // MP3
				'audio/wav',       // WAV
				'audio/ogg',       // OGG
				'audio/mp4',       // M4A, MP4 audio
				'audio/aac',       // AAC
				'audio/flac',      // FLAC

				// Audio - Server/Browser variants (some servers send these)
				'audio/mp3',       // Alternative for MP3
				'audio/x-wav',     // Alternative for WAV
				'audio/x-mpeg',    // Alternative for MPEG
				'audio/m4a',       // Alternative for M4A
			),
			'wisewand_download_inline_images'         => true, // Enable by default for better user experience
			'wisewand_default_inline_images_count'    => 1, // Default: 1 inline image (0.5 credits)
			'wisewand_allowed_domains'                => '',
			'wisewand_add_audio_player'               => true,
			'wisewand_audio_player_position'          => 'top', // top, bottom, none
			'wisewand_remove_h1_tags'                 => true,
			// Note: Smart SSRF protection with auto-detection is now the default
			// No configuration needed - it automatically adapts to context

			// SEO settings
			'wisewand_seo_mode'                       => 'auto',
			'wisewand_seo_meta_mapping'               => array(),

			// WPML settings
			'wisewand_wpml_enabled'                   => false,
			'wisewand_wpml_lang_mapping'              => array(),
			'wisewand_wpml_default_lang'              => '',

			// Logging settings
			'wisewand_logging_enabled'                => true,
			'wisewand_debug_mode'                     => false,
			'wisewand_log_max_entries'                => 200,
			'wisewand_log_retention_days'             => 30,

			// Pull mode settings
			'wisewand_pull_api_key'                   => '',
			'wisewand_pull_base_url'                  => 'https://api.wisewand.ai/v1',
			'wisewand_pull_timeout'                   => 3600,

			// API settings
			'wisewand_api_key'                        => '',
			'wisewand_api_base_url'                   => 'https://api.wisewand.ai',
			'wisewand_api_timeout'                    => 30,

			// DataForSEO settings
			'wisewand_dataforseo_login'               => '',
			'wisewand_dataforseo_password'            => '',

			// ACF settings
			'wisewand_acf_enabled'                    => false,
			'wisewand_acf_mode'                       => 'field_key',
			'wisewand_acf_mapping'                    => array(),

			// Custom fields
			'wisewand_custom_fields_whitelist'        => array(),

			// Editorial Calendar settings
			'wisewand_calendar_enabled'               => true,
			'wisewand_calendar_default_project'       => '',
			'wisewand_calendar_default_persona'       => '',
			'wisewand_calendar_default_language'      => 'en',
			'wisewand_calendar_default_article_type'  => 'blog',
			'wisewand_calendar_default_length'        => 'auto',
			'wisewand_calendar_default_author'        => 1,
			'wisewand_calendar_default_category'      => '',
			'wisewand_calendar_auto_publish'          => false,
			'wisewand_calendar_default_image_primary_color' => '#ffffff',
			'wisewand_calendar_default_image_secondary_color' => '#ffffff',
			'wisewand_calendar_use_audio'             => true,

			// Publication Scheduling Settings
			'wisewand_calendar_time_range'            => 'random', // Default: Random (9 AM - 8 PM)
			'wisewand_allowed_publication_days'       => array( '1', '2', '3', '4', '5' ), // Mon-Fri (1=Monday, 7=Sunday)

			// Cannibalization & Content Update Settings (Change 3: Safe defaults)
			'wisewand_cannibalization_default_action' => 'create', // Safe: always create new content by default
			'wisewand_default_content_merge_strategy' => 'append', // Safe: append instead of destructive replace

			// CRON settings
			'wisewand_cron_enabled'                   => true,
			'wisewand_cron_frequency'                 => 'twice_daily',
			'wisewand_cron_randomize_time'            => true,
			'wisewand_cron_time_window_start'         => '09:00',
			'wisewand_cron_time_window_end'           => '20:00',
			'wisewand_cron_lead_time_days'            => 1,
			'wisewand_cron_max_retries'               => 2,  // Only 2 retries - after that, contact Wisewand support
		);

		foreach ( $defaults as $option => $value ) {
			if ( get_option( $option ) === false ) {
				add_option( $option, $value );
			}
		}
	}

	private static function generate_initial_secret() {
		$existing_secret = get_option( 'wisewand_hmac_secret' );
		if ( empty( $existing_secret ) ) {
			// Generate a secure random secret
			$secret     = '';
			$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
			$length     = 64;

			for ( $i = 0; $i < $length; $i++ ) {
				$secret .= $characters[ wp_rand( 0, strlen( $characters ) - 1 ) ];
			}

			update_option( 'wisewand_hmac_secret', $secret );
		}
	}

	/**
	 * Verify required database tables exist
	 *
	 * @since 1.0.2
	 * @return bool|string True if all tables exist, error message if not
	 */
	private static function verify_tables_exist() {
		return Database_Manager::verify_tables_exist();
	}
}
