<?php
/**
 * Bootstrap class for UGC Commerce plugin.
 *
 * @package Ugcify
 */

namespace Ugcify;

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

/**
 * Main Bootstrap class.
 */
class Bootstrap {
	/**
	 * Current database schema version.
	 */
	private const DB_SCHEMA_VERSION = '3';

	/**
	 * Plugin instance.
	 *
	 * @var Plugin|null
	 */
	private static $instance = null;

	/**
	 * Plugin activation hook.
	 *
	 * @return void
	 */
	public static function activate() {
		// Activation logic here.
		// Create database tables.
		self::create_tables();
		update_option( 'ugcify_db_schema_version', self::DB_SCHEMA_VERSION );

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

		// Schedule the 12-hour license revalidation cron.
		License\LicenseCron::schedule();

		// Flush rewrite rules.
		flush_rewrite_rules();

		// Set a transient flag to trigger redirect to setup wizard on next admin page load.
		// Only set if this is not a bulk activation (WP passes 'activate-multi' during bulk).
		if ( ! wp_doing_ajax() && ! isset( $_GET['activate-multi'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Bulk plugin activation param; not user input.
			set_transient( 'ugcify_activation_redirect', true, 30 );
		}
	}

	/**
	 * Plugin deactivation hook.
	 *
	 * @return void
	 */
	public static function deactivate() {
		// Deactivation logic here.
		$social_cron_file = UGCIFY_PATH . 'includes/Automation/SocialCron.php';
		if ( file_exists( $social_cron_file ) ) {
			require_once $social_cron_file;
			Automation\SocialCron::clear_schedule();
		}

		// Remove the license revalidation cron.
		License\LicenseCron::clear_schedule();
		wp_clear_scheduled_hook( 'ugcify_cleanup_share_tokens' );

		// Flush rewrite rules.
		flush_rewrite_rules();
	}

	/**
	 * Initialize the plugin.
	 *
	 * @return Plugin
	 */
	public static function init() {
		self::register_creator_foundation();

		if ( null === self::$instance ) {
			self::$instance = new Plugin();
		}

		// Hook the activation redirect handler into admin_init.
		add_action( 'admin_init', array( __CLASS__, 'maybe_redirect_to_setup_wizard' ) );

		// Run DB migrations when plugin version changes (covers code updates without deactivation).
		add_action( 'admin_init', array( __CLASS__, 'maybe_run_migrations' ) );
		// Auto-create any missing tables on plugin load (idempotent via dbDelta).
		add_action( 'admin_init', array( __CLASS__, 'maybe_create_analytics_table' ) );
		// Flush rewrite rules if needed for WooCommerce endpoints.
		add_action( 'admin_init', array( __CLASS__, 'maybe_flush_rewrite_rules' ) );

		// Register the cron action callback on every load (required for WP-Cron to fire).
		License\LicenseCron::register_hook();
		// Ensure cron is scheduled (covers existing installs that were not deactivated/reactivated).
		License\LicenseCron::schedule();

		return self::$instance;
	}

	/**
	 * Register creator defaults and capabilities.
	 *
	 * Safe to call repeatedly on activation and plugin boot.
	 *
	 * @return void
	 */
	private static function register_creator_foundation() {
		$settings_file     = UGCIFY_PATH . 'includes/Influencer/Settings.php';
		$capabilities_file = UGCIFY_PATH . 'includes/Influencer/Capabilities.php';

		if ( ! file_exists( $settings_file ) || ! file_exists( $capabilities_file ) ) {
			return;
		}

		require_once $settings_file;
		require_once $capabilities_file;

		Influencer\Settings::ensure_default_option();
		Influencer\Capabilities::register_role_and_caps();
	}

	/**
	 * Redirect to the setup wizard after first activation.
	 *
	 * Checks for a transient flag set during activation. The redirect only fires once
	 * and is skipped during AJAX requests, WP-CLI, or network admin contexts.
	 *
	 * @return void
	 */
	public static function maybe_redirect_to_setup_wizard() {
		// Check if the activation redirect transient exists.
		if ( ! get_transient( 'ugcify_activation_redirect' ) ) {
			return;
		}

		// Delete the transient so the redirect only happens once.
		delete_transient( 'ugcify_activation_redirect' );

		// Bail if activating from network admin, running AJAX, or WP-CLI.
		if ( is_network_admin() || wp_doing_ajax() || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
			return;
		}

		// Redirect to the setup wizard page.
		wp_safe_redirect( admin_url( 'admin.php?page=ugcify#/setup-wizard' ) );
		exit;
	}

	/**
	 * Run database migrations when the plugin version has changed.
	 *
	 * This ensures new columns/tables are created even when the plugin files
	 * are updated without a deactivate/reactivate cycle.
	 *
	 * @return void
	 */
	public static function maybe_run_migrations() {
		// Schema version tracks DB structure changes independently of plugin version.
		// Bump this when adding new migrations.
		$current_schema = get_option( 'ugcify_db_schema_version', '0' );

		if ( version_compare( $current_schema, self::DB_SCHEMA_VERSION, '>=' ) ) {
			return;
		}

		self::create_tables();
		update_option( 'ugcify_db_schema_version', self::DB_SCHEMA_VERSION );
  }
  
  /*
	 * Create the analytics table if it does not exist yet.
	 * Runs on admin_init so existing installs get the table without reactivation.
	 *
	 * @return void
	 */
	public static function maybe_create_analytics_table() {
		global $wpdb;

		$table = $wpdb->prefix . 'ugcify_analytics';

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

		if ( $exists === $table ) {
			return;
		}

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		require_once UGCIFY_PATH . 'includes/Database/Migrations/CreateAnalyticsTable.php';

		$migration = new Database\Migrations\CreateAnalyticsTable( $wpdb );
		dbDelta( $migration->run() );
	}

	/**
	 * Flush rewrite rules if the influencer feature was added after initial activation.
	 *
	 * This ensures WooCommerce My Account endpoints work correctly.
	 *
	 * @return void
	 */
	public static function maybe_flush_rewrite_rules() {
		// Check if we've already flushed rules for the influencer feature.
		$flushed = get_option( 'ugcify_influencer_rewrite_flushed', false );

		if ( $flushed ) {
			return;
		}

		// Mark as flushed before actually flushing to prevent repeated flushes.
		update_option( 'ugcify_influencer_rewrite_flushed', true );

		// Flush rewrite rules to register WooCommerce My Account endpoints.
		flush_rewrite_rules();
	}

	/**
	 * Create database tables.
	 *
	 * @return void
	 */
	private static function create_tables() {
		global $wpdb;

		require_once UGCIFY_PATH . 'includes/Database/Migrations/MigrationRunner.php';
		require_once UGCIFY_PATH . 'includes/Database/Migrations/CreateReviewsTable.php';
		require_once UGCIFY_PATH . 'includes/Database/Migrations/CreateReviewMetaTable.php';
		require_once UGCIFY_PATH . 'includes/Database/Migrations/CreateReviewSyncMapTable.php';
		require_once UGCIFY_PATH . 'includes/Database/Migrations/CreateProductTagsTable.php';
		require_once UGCIFY_PATH . 'includes/Database/Migrations/CreatePointsTable.php';
		require_once UGCIFY_PATH . 'includes/Database/Migrations/CreateAutomationLogsTable.php';
		require_once UGCIFY_PATH . 'includes/Database/Migrations/AddActionToPointsTable.php';
		require_once UGCIFY_PATH . 'includes/Database/Migrations/AlterPointsTableAddTransactionFields.php';
		require_once UGCIFY_PATH . 'includes/Database/Migrations/CreateAnalyticsTable.php';
		require_once UGCIFY_PATH . 'includes/Database/Migrations/CreateInfluencerInvitationsTable.php';

		$runner = new Database\Migrations\MigrationRunner( $wpdb );
		$runner->run();
	}

	/**
	 * Set default plugin options.
	 *
	 * @return void
	 */
	private static function set_default_options() {
		$defaults = array(
			'ugcify_version'        => UGCIFY_VERSION,
			'ugcify_auto_approve'   => false,
			'ugcify_require_login'  => false,
			'ugcify_points_enabled' => true,
		);

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

		// Set default review form settings.
		if ( false === get_option( 'ugcify_review_form_settings' ) ) {
			add_option(
				'ugcify_review_form_settings',
				array(
					'formType'       => 'step-by-step',
					'formVisibility' => 'logged-in',
				)
			);
		}

		// Set default storage settings.
		if ( false === get_option( 'ugcify_storage_settings' ) ) {
			add_option(
				'ugcify_storage_settings',
				array(
					'enabled'              => false,
					'bucket'               => '',
					'region'               => 'us-east-1',
					'access_key_encrypted' => '',
					'secret_key_encrypted' => '',
					'custom_endpoint'      => '',
					'path_prefix'          => 'ugcify-reviews/',
				)
			);
		}

		// Set default review template settings.
		if ( false === get_option( 'ugcify_review_template_settings' ) ) {
			add_option(
				'ugcify_review_template_settings',
				array(
					'version'          => 1,
					'activeTemplateId' => '',
					'templates'        => array(
						'minimal_grid' => array(
							'enabled' => false,
						),
					),
				)
			);
		}

		$review_form_tab_options = array(
			'ugcify_review_form_rating_settings',
			'ugcify_review_form_media_settings',
			'ugcify_review_form_about_settings',
			'ugcify_review_form_review_settings',
			'ugcify_review_form_thank_you_settings',
		);

		foreach ( $review_form_tab_options as $option_name ) {
			if ( false === get_option( $option_name ) ) {
				add_option( $option_name, array() );
			}
		}

		// Set default email settings on first activation.
		if ( false === get_option( 'ugcify_email_global_settings' ) ) {
			add_option(
				'ugcify_email_global_settings',
				array(
					'from_name'     => get_bloginfo( 'name' ),
					'from_email'    => get_option( 'admin_email' ),
					'reply_to'      => get_option( 'admin_email' ),
					'body_color'    => '#f7f7f7',
					'heading_color' => '#1e1e1e',
					'text_color'    => '#555555',
					'button_color'  => '#201CFE',
					'link_color'    => '#201CFE',
					'header_logo'   => '',
					'footer_text'   => '',
				)
			);
		}

		if ( false === get_option( 'ugcify_social_settings' ) ) {
			add_option(
				'ugcify_social_settings',
				array(
					'instagram' => array(
						'custom_app_id_hash'      => '',
						'custom_app_secret_hash'  => '',
						'custom_app_id_encrypted' => '',
						'custom_app_secret_encrypted' => '',
						'app_id'                  => '',
						'app_secret'              => '',
						'access_token'            => '',
						'access_token_encrypted'  => '',
						'ig_user_id'              => '',
						'connected_handle'        => '',
						'token_created_at'        => '',
						'token_expires_at'        => '',
						'token_last_refreshed_at' => '',
						'last_refresh_error_at'   => '',
						'last_refresh_error'      => '',
						'refresh_notice_sent'     => false,
					),
					'hashtags'        => array(),
					'hashtag_mapping' => array(),
					'auto_publish'    => false,
					'storage'         => 'external',
					'cron_frequency'  => 'weekly',
					'default_product' => 0,
				)
			);
		}

		if ( false === get_option( 'ugcify_ab_tests' ) ) {
			add_option(
				'ugcify_ab_tests',
				array(
					'version' => 1,
					'items'   => array(),
				)
			);
		}

		self::register_creator_foundation();
	}
}
