<?php
/**
 * Fired during plugin activation.
 *
 * This class defines all code necessary to run during the plugin's activation.
 *
 * @since      1.0.0
 * @package    Ai_Try_N_Buy
 * @subpackage Ai_Try_N_Buy/includes
 * @author     Edu Brazeal <contact@edubrazeal.com>
 */
class Aitnb_Activator {

	/**
	 * The main activation method.
	 *
	 * This method is triggered when the plugin is activated. It creates the
	 * custom database table for analytics and sets default plugin options.
	 *
	 * @since    1.0.0
	 */
	public static function activate() {
		$table_created = self::create_analytics_table();
		$options_set = self::set_default_options();
		
		if ( ! $table_created || ! $options_set ) {
			self::verify_activation();
		} else {
			update_option(
				'aitnb_activation_status',
				array(
					'status'    => 'success',
					'timestamp' => current_time( 'mysql' ),
					'version'   => AITNB_VERSION,
				)
			);
		}

		if ( class_exists( 'Aitnb_Style_Assistant_Cron' ) ) {
			Aitnb_Style_Assistant_Cron::reschedule_event();
		}
	}

	/**
	 * Creates the custom database table for analytics.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @return   bool     True if table creation was successful, false otherwise.
	 */
	private static function create_analytics_table() {
		global $wpdb;

		$table_name      = $wpdb->prefix . 'aitnb_analytics';
		$charset_collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE $table_name (
			id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			product_id bigint(20) UNSIGNED NOT NULL,
			user_id bigint(20) UNSIGNED DEFAULT 0,
			session_id varchar(191) NOT NULL,
			event_type varchar(50) NOT NULL,
			event_timestamp datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY  (id),
			KEY product_id (product_id),
			KEY event_type (event_type),
			KEY event_timestamp (event_timestamp),
			KEY session_product (session_id, product_id, event_type)
		) $charset_collate;";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		
		dbDelta( $sql );

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$table_exists = $wpdb->get_var(
			$wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name )
		) === $table_name;

		if ( ! $table_exists ) {
			return false;
		}

		if ( strpos( $table_name, $wpdb->prefix . 'aitnb_analytics' ) !== 0 ) {
			return false;
		}

		$expected_table_name = $wpdb->prefix . 'aitnb_analytics';
		if ( $table_name !== $expected_table_name ) {
			return false;
		}

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$columns = $wpdb->get_results(
			"SHOW COLUMNS FROM `{$table_name}`",
			ARRAY_A
		);

		$required_columns = array( 'id', 'product_id', 'user_id', 'session_id', 'event_type', 'event_timestamp' );
		$existing_columns = array();

		if ( is_array( $columns ) ) {
			foreach ( $columns as $column ) {
				if ( isset( $column['Field'] ) ) {
					$existing_columns[] = $column['Field'];
				}
			}
		}

		foreach ( $required_columns as $required_column ) {
			if ( ! in_array( $required_column, $existing_columns, true ) ) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Sets the default plugin options in the database.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @return   bool     True if options were set successfully, false otherwise.
	 */
	private static function set_default_options() {
		$existing_options = get_option( 'aitnb_settings' );
		
		if ( false !== $existing_options ) {
			return true;
		}

		$default_options = array(
			'google_api_key'           => '',
			'gemini_api_key'           => '',
			'gemini_fit_model'         => 'gemini-2.5-flash-latest',
			'gemini_style_model'       => 'gemini-2.5-pro-latest',
			'delete_data_on_uninstall' => false,
			'api_data_consent'         => false,
			'style_assistant_frequency' => 'daily',
			'product_page_hook'        => 'woocommerce_after_single_product_summary',
		);

		$result = add_option( 'aitnb_settings', $default_options );

		if ( false === $result ) {
			return false;
		}

		return true;
	}

	/**
	 * Verifies that activation completed successfully.
	 *
	 * @since    1.0.0
	 * @access   private
	 */
	private static function verify_activation() {
		global $wpdb;
		
		$table_name = $wpdb->prefix . 'aitnb_analytics';
		$issues = array();

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) ) === $table_name;
		
		if ( ! $table_exists ) {
			$issues[] = __( 'Analytics table was not created', 'virtual-ai-fit-and-style-assistant' );
		} else {
			if ( strpos( $table_name, $wpdb->prefix . 'aitnb_analytics' ) !== 0 ) {
				$issues[] = __( 'Invalid table name detected', 'virtual-ai-fit-and-style-assistant' );
			} else {
				$expected_table_name = $wpdb->prefix . 'aitnb_analytics';
				if ( $table_name !== $expected_table_name ) {
					$issues[] = __( 'Table name validation failed', 'virtual-ai-fit-and-style-assistant' );
				} else {
					// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
					$columns = $wpdb->get_results(
						"SHOW COLUMNS FROM `{$table_name}`",
						ARRAY_A
					);

					$required_columns = array( 'id', 'product_id', 'user_id', 'session_id', 'event_type', 'event_timestamp' );
					$existing_columns = array();

					if ( is_array( $columns ) ) {
						foreach ( $columns as $column ) {
							if ( isset( $column['Field'] ) ) {
								$existing_columns[] = $column['Field'];
							}
					}
				}

				foreach ( $required_columns as $required_column ) {
					if ( ! in_array( $required_column, $existing_columns, true ) ) {
						/* translators: %s: column name */
						$issues[] = sprintf(
							__( 'Analytics table is missing required column: %s', 'virtual-ai-fit-and-style-assistant' ),
							$required_column
						);
					}
				}
			}
		}
	}		$settings = get_option( 'aitnb_settings' );
		if ( false === $settings ) {
			$issues[] = __( 'Plugin settings were not created', 'virtual-ai-fit-and-style-assistant' );
		} elseif ( ! is_array( $settings ) ) {
			$issues[] = __( 'Plugin settings are corrupted', 'virtual-ai-fit-and-style-assistant' );
		} else {
			$required_settings = array( 'google_api_key', 'gemini_api_key', 'gemini_fit_model', 'gemini_style_model', 'api_data_consent' );
			foreach ( $required_settings as $required_setting ) {
				if ( ! array_key_exists( $required_setting, $settings ) ) {
					/* translators: %s: setting key name */
					$issues[] = sprintf(
						__( 'Plugin settings are missing required key: %s', 'virtual-ai-fit-and-style-assistant' ),
						$required_setting
					);
				}
			}
		}

		if ( empty( $issues ) ) {
			update_option(
				'aitnb_activation_status',
				array(
					'status'    => 'success',
					'timestamp' => current_time( 'mysql' ),
					'version'   => AITNB_VERSION,
				)
			);
		} else {
			update_option(
				'aitnb_activation_status',
				array(
					'status'    => 'error',
					'issues'    => $issues,
					'timestamp' => current_time( 'mysql' ),
					'version'   => AITNB_VERSION,
				)
			);

			set_transient( 'aitnb_activation_notice', $issues, 300 );

			foreach ( $issues as $issue ) {
			}
		}
	}

	/**
	 * Checks if the plugin was activated successfully.
	 * Can be called from admin pages to verify installation status.
	 *
	 * @since    1.0.0
	 * @return   array|false    Activation status array or false if not set.
	 */
	public static function get_activation_status() {
		return get_option( 'aitnb_activation_status', false );
	}

	/**
	 * Displays an admin notice if there were activation issues.
	 * Hook this to 'admin_notices' action.
	 *
	 * @since    1.0.0
	 */
	public static function show_activation_notice() {
		if ( ! current_user_can( 'activate_plugins' ) ) {
			return;
		}

		$notice_issues = get_transient( 'aitnb_activation_notice' );
		
		if ( $notice_issues && is_array( $notice_issues ) ) {
			require_once plugin_dir_path( __FILE__ ) . '../admin/views/activation-notice-view.php';
			delete_transient( 'aitnb_activation_notice' );
		}
	}
}