<?php
/**
 * Shois Chat Button — Activator
 *
 * Handles plugin activation, deactivation, and upgrade routines.
 *
 * @package ShoisChatButton
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class SHCB_Activator
 *
 * Manages activation, deactivation, and schema migration.
 */
class SHCB_Activator {

	/**
	 * Default global settings.
	 *
	 * @return array
	 */
	public static function get_default_settings() {
		return array(
			'active'              => true,
			'default_template_id' => 0,
			'brand_color'         => '#25D366',
			'schema_version'      => SHCB_SCHEMA_VERSION,
			'performance'         => array(
				'load_scope'      => 'all',
				'css_delivery'    => 'inline',
				'lazy_load'       => false,
				'hide_for_admins' => false,
			),
			'integrations'        => array(
				'woocommerce' => false,
				'ga4'         => false,
				'fb_pixel'    => false,
				'gtm'         => false,
			),
			'availability'        => array(
				'timezone'         => 'UTC',
				'offline_behavior' => 'show_message',
				'time_format'      => 'relative',
				'global_schedule'  => array(
					'enabled' => false,
					'hours'   => array(
						'mon' => array( array( 'start' => '09:00', 'end' => '17:00' ) ),
						'tue' => array( array( 'start' => '09:00', 'end' => '17:00' ) ),
						'wed' => array( array( 'start' => '09:00', 'end' => '17:00' ) ),
						'thu' => array( array( 'start' => '09:00', 'end' => '17:00' ) ),
						'fri' => array( array( 'start' => '09:00', 'end' => '17:00' ) ),
						'sat' => array(),
						'sun' => array(),
					),
				),
				'blackout_dates'   => array(),
			),
			'template_config'     => array(
				'template_slug'          => 'classic-green',
				'primary_color'          => '#00ff6e',
				'header_bg_color'        => '#00ff6e',
				'header_text_color'      => '#ffffff',
				'text_color'             => '#333333',
				'bg_color'               => '#ffffff',
				'agent_bg_color'         => '#f8faf9',
				'agent_text_color'       => '#1e293b',
				'radius_popup'           => 16,
				'radius_btn'             => 50,
				'btn_size'               => 60,
				'popup_width'            => 360,
				'header_title'           => 'Chat with us! 👋',
				'header_subtitle'        => 'We reply within minutes',
				'welcome_message'        => 'Hi! How can we help you today?',
				'offline_message'        => "We're currently offline.",
				'position'               => 'bottom-right',
				'offset_x'               => 24,
				'offset_y'               => 24,
				'close_on_outside_click' => true,
				'footer_text'            => 'Powered by Shois Chat Button',
			),
		);
	}

	/**
	 * Run on plugin activation.
	 *
	 * @return void
	 */
	public static function activate() {

		// Create default global settings if not present.
		if ( false === get_option( 'shcb_global_settings' ) ) {
			add_option( 'shcb_global_settings', self::get_default_settings(), '', 'no' );
		}

		// Create empty agents array if not present.
		if ( false === get_option( 'shcb_agents' ) ) {
			add_option( 'shcb_agents', array(), '', 'no' );
		}

		// Create empty display rules array if not present.
		if ( false === get_option( 'shcb_display_rules' ) ) {
			add_option( 'shcb_display_rules', array(), '', 'no' );
		}

		// Store schema version for future migrations.
		update_option( 'shcb_schema_version', SHCB_SCHEMA_VERSION );

		// Register CPT so rewrite rules include it.
		SHCB_Template_CPT::register_post_type();

		// Flush rewrite rules.
		flush_rewrite_rules();

		// Set activation redirect flag.
		set_transient( 'shcb_activation_redirect', true, 30 );
	}

	/**
	 * Run on plugin deactivation.
	 *
	 * @return void
	 */
	public static function deactivate() {
		flush_rewrite_rules();
	}

	/**
	 * Check and run schema migrations if needed.
	 *
	 * Called on plugins_loaded via the main plugin class.
	 *
	 * @return void
	 */
	public static function maybe_upgrade() {
		$current_version = absint( get_option( 'shcb_schema_version', 0 ) );

		if ( $current_version >= SHCB_SCHEMA_VERSION ) {
			return;
		}

		// Future migration steps go here.
		// if ( $current_version < 2 ) { self::migrate_to_v2(); }

		update_option( 'shcb_schema_version', SHCB_SCHEMA_VERSION );
	}

	/**
	 * Run on plugin uninstall.
	 * Removes all plugin data from the database.
	 * Hooked to Freemius 'after_uninstall' action.
	 *
	 * @return void
	 */
	public static function uninstall() {
		/**
		 * Remove all plugin options.
		 */
		delete_option( 'shcb_global_settings' );
		delete_option( 'shcb_agents' );
		delete_option( 'shcb_display_rules' );
		delete_option( 'shcb_schema_version' );
		delete_option( 'shcb_setup_complete' );

		/**
		 * Remove monthly analytics options.
		 */
		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$shcb_analytics_options = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
				$wpdb->esc_like( 'shcb_analytics_' ) . '%'
			)
		);

		if ( ! empty( $shcb_analytics_options ) ) {
			foreach ( $shcb_analytics_options as $shcb_option_name ) {
				delete_option( $shcb_option_name );
			}
		}

		/**
		 * Remove all shcb_template posts and their meta.
		 */
		$shcb_posts = get_posts(
			array(
				'post_type'      => 'shcb_template',
				'posts_per_page' => -1,
				'post_status'    => 'any',
				'fields'         => 'ids',
			)
		);

		if ( ! empty( $shcb_posts ) ) {
			foreach ( $shcb_posts as $post_id ) {
				wp_delete_post( $post_id, true );
			}
		}

		/**
		 * Remove all transients with shcb_ prefix.
		 */
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$shcb_transients = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
				$wpdb->esc_like( '_transient_shcb_' ) . '%',
				$wpdb->esc_like( '_transient_timeout_shcb_' ) . '%'
			)
		);

		if ( ! empty( $shcb_transients ) ) {
			foreach ( $shcb_transients as $shcb_transient_name ) {
				delete_option( $shcb_transient_name );
			}
		}

		/**
		 * Flush rewrite rules after CPT removal.
		 */
		flush_rewrite_rules();
	}
}
