<?php
/**
 * Fired during plugin activation
 *
 * @link       https://www.webtoffee.com/
 * @since      3.0.0
 *
 * @package    WebToffee
 * @subpackage CookieConsent/includes
 */

namespace WebToffee\CookieConsent\Lite\Includes;

use WebToffee\CookieConsent\Lite\Admin\Modules\Banners\Includes\Banner;
use WebToffee\CookieConsent\Lite\Admin\Modules\Banners\Includes\Controller;

/**
 * Fired during plugin activation.
 *
 * This class defines all code necessary to run during the plugin's activation.
 *
 * @since      3.0.0
 * @package    WebToffee
 * @subpackage CookieConsent/includes
 * @author     WebToffee <info@webtoffee.com>
 */
class Activator {

	/**
	 * Instance of the current class
	 *
	 * @var object
	 */
	private static $instance;
	/**
	 * Update DB callbacks.
	 *
	 * @var array
	 */
	private static $db_updates = array(
		'3.2.0' => array(
			'update_db_320',
		),
		'3.4.4' => array(
			'update_db_344',
		),
		'3.5.1' => array(
			'update_db_351',
		),
	);
	/**
	 * Return the current instance of the class
	 *
	 * @return object
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Activate the plugin
	 *
	 * @since 3.0.0
	 * @return void
	 */
	public static function init() {
		add_action( 'init', array( __CLASS__, 'check_version' ), 5 );
	}
	/**
	 * Check the plugin version and run the updater is required.
	 *
	 * This check is done on all requests and runs if the versions do not match.
	 */
	public static function check_version() {

		if ( ! defined( 'IFRAME_REQUEST' ) && version_compare( get_option( 'wcc_version', '3.0.0' ), CLI_VERSION, '<' ) ) {
			self::install();
		}
	}
	/**
	 * Install all the plugin
	 *
	 * @return void
	 */
	public static function install() {
		self::check_for_upgrade();
		if ( true === wcc_first_time_install() ) {
			add_option( 'wcc_first_time_activated_plugin', 'true' );
		}
		self::maybe_update_db();
		update_option( 'wcc_version', CLI_VERSION );
		do_action( 'wcc_after_activate', CLI_VERSION );
		self::update_db_version();
	}

	/**
	 * Set a temporary flag during the first time installation.
	 *
	 * @return void
	 */
	public static function check_for_upgrade() {
		if ( false === get_option( 'wcc_settings', false ) ) {
			if ( false === get_site_transient( '_wcc_first_time_install' ) ) {
				set_site_transient( '_wcc_first_time_install', true, 30 );
			}
		}
	}

	/**
	 * Update DB version to track changes to data structure.
	 *
	 * @param string $version Current version.
	 * @return void
	 */
	public static function update_db_version( $version = null ) {
		update_option( 'wcc_cookie_consent_lite_db_version', is_null( $version ) ? CLI_VERSION : $version );
	}

	/**
	 * Check if any database changes is required on the latest release
	 *
	 * @return boolean
	 */
	private static function needs_db_update() {
		$current_version = get_option( 'wcc_cookie_consent_lite_db_version', '3.0.0' ); // @since 3.0.0 introduced DB migrations
		$updates         = self::$db_updates;
		$update_versions = array_keys( $updates );
		usort( $update_versions, 'version_compare' );
		return ! is_null( $current_version ) && version_compare( $current_version, end( $update_versions ), '<' );
	}

	/**
	 * Update DB if required
	 *
	 * @return void
	 */
	public static function maybe_update_db() {
		if ( self::needs_db_update() ) {
			self::update();
		}
	}

	/**
	 * Run a update check during each release update.
	 *
	 * @return void
	 */
	private static function update() {
		$current_version = get_option( 'wcc_cookie_consent_lite_db_version', '3.0.0' );
		foreach ( self::$db_updates as $version => $callbacks ) {
			if ( version_compare( $current_version, $version, '<' ) ) {
				foreach ( $callbacks as $callback ) {
					self::$callback();
				}
			}
		}
	}
	/**
	 * Update latest IAB description in the banner content
	 *
	 * @return void
	 */
	public static function update_db_320() {
		$items = Controller::get_instance()->get_items();
		foreach ( $items as $item ) {
			$banner = new Banner( $item->banner_id );
			$banner->save();
		}
	}
	/**
	 * Update latest placeholder text in the banner content
	 * Update only videoPlaceholder for ccpa and gdpr sections
	 *
	 * @return void
	 */
	public static function update_db_344() {
		$items = Controller::get_instance()->get_items();

		foreach ( $items as $item ) {
			$banner = new Banner( $item->banner_id );

			// Get current banner contents.
			$current_contents = $banner->get_contents();
			// Get available languages using the global helper function.
			$available_languages = is_array( wcc_selected_languages() ) && ! empty( wcc_selected_languages() ) ? wcc_selected_languages() : array( 'en' );

			$contents_updated = false;

			foreach ( $available_languages as $language ) {

				// Clear cache to get latest content from JSON files.
				wp_cache_delete( 'wcc_contents_' . $language, 'wcc_banner_contents' );

				$translations = $banner->get_translations( $language );

				if ( ! empty( $translations ) && is_array( $translations ) ) {
					if ( isset( $translations['videoPlaceholder'] ) ) {
						// Update videoPlaceholder directly under the language.
						$current_contents[ $language ]['videoPlaceholder'] = $translations['videoPlaceholder'];
						$contents_updated                                  = true;
					}
				}
			}

			// Only update if contents were actually modified.
			if ( $contents_updated ) {
				// Ensure all required fields are set for the banner.
				$banner->set_multi_item_data(
					array(
						'name'     => $banner->get_name(),
						'slug'     => $banner->get_slug(),
						'status'   => $banner->get_status(),
						'settings' => $banner->get_settings(),
						'default'  => $banner->get_default(),
						'contents' => $current_contents,
					)
				);
				// Use the controller's update_item method to save the banner.
				Controller::get_instance()->update_item( $banner );

			}
		}
	}
	/**
	 * Update latest placeholder text in the banner content
	 * Update only videoPlaceholder for ccpa and gdpr sections
	 *
	 * @return void
	 */
	public static function update_db_351() {
		$items = Controller::get_instance()->get_items();

		foreach ( $items as $item ) {
			$banner = new Banner( $item->banner_id );

			// Get current banner contents.
			$current_contents = $banner->get_contents();
			// Get available languages using the global helper function.
			$available_languages = is_array( wcc_selected_languages() ) && ! empty( wcc_selected_languages() ) ? wcc_selected_languages() : array( 'en' );

			$contents_updated = false;

			foreach ( $available_languages as $language ) {

				// Clear cache to get latest content from JSON files.
				wp_cache_delete( 'wcc_contents_' . $language, 'wcc_banner_contents' );

				$translations = $banner->get_translations( $language );

				if ( ! empty( $translations ) && is_array( $translations ) ) {
					if ( isset( $translations['optoutPopup']['elements']['gpcOption']['elements']['description'] ) ) {
						// Update gpcOption description directly under the language.
						$current_contents[ $language ]['optoutPopup']['elements']['gpcOption']['elements']['description'] = $translations['optoutPopup']['elements']['gpcOption']['elements']['description'];
						$contents_updated                                  = true;
					}
				}
			}

			// Only update if contents were actually modified.
			if ( $contents_updated ) {
				// Ensure all required fields are set for the banner.
				$banner->set_multi_item_data(
					array(
						'name'     => $banner->get_name(),
						'slug'     => $banner->get_slug(),
						'status'   => $banner->get_status(),
						'settings' => $banner->get_settings(),
						'default'  => $banner->get_default(),
						'contents' => $current_contents,
					)
				);
				// Use the controller's update_item method to save the banner.
				Controller::get_instance()->update_item( $banner );

			}
			// Save the banner.
			$banner->save();

		}
	}
}
