<?php
/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://www.webtoffee.com/
 * @since      3.0.0
 *
 * @package    WebToffee\CookieConsent\Lite\Admin
 */

namespace WebToffee\CookieConsent\Lite\Admin;

use WebToffee\CookieConsent\Lite\Includes\Notice;
/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    WebToffee
 * @subpackage CookieConsent/admin
 * @author     WebToffee <info@webtoffee.com>
 */
class Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    3.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    3.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Admin modules of the plugin
	 *
	 * @var array
	 */
	private static $modules;

	/**
	 * Currently active modules
	 *
	 * @var array
	 */
	private static $active_modules;

	/**
	 * Existing modules
	 *
	 * @var array
	 */
	public static $existing_modules;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    3.0.0
	 * @param      string $plugin_name       The name of this plugin.
	 * @param      string $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {
		$this->plugin_name = $plugin_name;
		$this->version     = $version;
		self::$modules     = $this->get_default_modules();
		$this->load();
		$this->add_notices();
		$this->add_review_notice();
		$this->load_modules();
		add_action( 'admin_menu', array( $this, 'admin_menu' ) );
		add_action( 'admin_init', array( $this, 'load_plugin' ) );
		add_filter( 'admin_body_class', array( $this, 'admin_body_classes' ) );
		// Hide the unrelated admin notices.
		add_action( 'admin_print_scripts', array( $this, 'hide_admin_notices' ) );
		add_filter( 'plugin_action_links_' . CLI_PLUGIN_BASENAME, array( $this, 'plugin_action_links' ) );
	}

	/**
	 * Load activator on each load.
	 *
	 * @return void
	 */
	public function load() {
		\WebToffee\CookieConsent\Lite\Includes\Activator::init();
	}

	/**
	 * Load admin notices
	 *
	 * @return void
	 */
	public function add_notices() {
		$notice = Notice::get_instance();
		$notice->add( 'connect_notice' );
		$notice->add(
			'disconnect_notice',
			array(
				'dismissible' => false,
				'type'        => 'info',
			)
		);
	}

	/**
	 * Add review notice
	 *
	 * @return void
	 */
	public function add_review_notice() {
		$expiry    = 15 * DAY_IN_SECONDS;
		$settings  = new \WebToffee\CookieConsent\Lite\Admin\Modules\Settings\Includes\Settings();
		$installed = $settings->get_installed_date();
		if ( $installed && ( $installed + $expiry > time() ) ) {
			return;
		}
		$notice = Notice::get_instance();
		$notice->add(
			'review_notice',
			array(
				'expiration' => $expiry,
			)
		);
	}
	/**
	 * Get the default modules array
	 *
	 * @return array
	 */
	public function get_default_modules() {
		$modules = array(
			'settings',
			'languages',
			'banners',
			'cookies',
			'policies',
			'cache',
			'upgrade',
			'scanner',
			'consentlogs',
			'license',
			'advanced',
			'gcm',
			'mcm',
		);
		return $modules;
	}

	/**
	 * Get the active admin modules
	 *
	 * @return void
	 */
	public function get_active_modules() {
	}
	/**
	 * Load all the modules
	 *
	 * @return void
	 */
	public function load_modules() {
		foreach ( self::$modules as $module ) {
			$parts      = explode( '_', $module );
			$class      = implode( '_', $parts );
			$class_name = 'WebToffee\CookieConsent\Lite\\Admin\\Modules\\' . ucfirst( $module ) . '\\' . ucfirst( $class );

			if ( class_exists( $class_name ) ) {
				$module_obj = new $class_name( $module );
				if ( $module_obj instanceof $class_name ) {
					if ( $module_obj->is_active() ) {
						self::$active_modules[ $module ] = true;
					}
				}
			}
		}
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    3.0.0
	 */
	public function enqueue_styles() {
		if ( false === wcc_is_admin_page() ) {
			return;
		}
		//wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'dist/css/app.css', array(), $this->version );
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    3.0.0
	 */
	public function enqueue_scripts() {
		if ( false === wcc_is_admin_page() ) {
			return;
		}

		if ( ! wcc_is_cloud_request() ) {
			$banner_arr = \WebToffee\CookieConsent\Lite\Admin\Modules\Banners\Includes\Controller::get_instance()->get_active_banners();
			if ( ! empty( $banner_arr ) ) {
				foreach ( $banner_arr as $key => $banner ) {
					if ( $banner ) {
						$properties = $banner->get_settings();
						$settings   = isset( $properties['settings'] ) ? $properties['settings'] : array();
						$version_id = isset( $settings['versionID'] ) ? $settings['versionID'] : 'default';
						$shortcodes = new \WebToffee\CookieConsent\Lite\Frontend\Modules\Shortcodes\Shortcodes( $banner, $version_id );
					}
				}
			}
		}
		$notice = Notice::get_instance();

		$global_script  = $this->plugin_name . '-app';
		$admin_url      = wcc_parse_url( admin_url( 'admin.php' ) );
		$plugin_dir_url = defined( 'WCC_PLUGIN_URL' ) ? WCC_PLUGIN_URL : trailingslashit( site_url() );

		if ( function_exists( 'wp_enqueue_editor' ) ) {
			wp_enqueue_editor();
		}

		wp_enqueue_script( $this->plugin_name . '-vendors', plugin_dir_url( __FILE__ ) . 'dist/js/chunk-vendors.js', array(), $this->version, true );
		wp_enqueue_script( $this->plugin_name . '-app', plugin_dir_url( __FILE__ ) . 'dist/js/app.js', array(), $this->version, true );

		wp_localize_script(
			$global_script,
			'wccGlobals',
			apply_filters(
				'wcc_admin_scripts_global',
				array(
					'webApp'       => array(
						'url' => '',
					),
					'path'         => array(
						'base'  => plugin_dir_path( __FILE__ ),
						'admin' => $admin_url['path'],
					),
					'api'          => array(
						'base'  => rest_url( 'wcc/v1/' ),
						'nonce' => wp_create_nonce( 'wp_rest' ),
					),
					'site'         => array(
						'url'  => get_site_url(),
						'name' => esc_attr( get_option( 'blogname' ) ),
					),
					'app'          => array(
						'url' => $plugin_dir_url . 'admin/dist/',
					),
					'modules'      => self::$active_modules,
					'nonce'        => wp_create_nonce( 'wp_rest' ),
					'assetsURL'    => WCC_PLUGIN_URL . 'frontend/images/',
					'multilingual' => wcc_i18n_is_multilingual() && count( wcc_selected_languages() ) > 0 ? true : false,
				),
				$global_script
			)
		);
		wp_localize_script(
			$global_script,
			'wccTranslations',
			array( 'translations' => $this->get_jed_locale_data( 'webtoffee-cookie-consent' ) )
		);
		wp_localize_script(
			$global_script,
			'wccConfig',
			apply_filters(
				'wcc_admin_scripts_config',
				array(),
				$global_script
			)
		);
		wp_localize_script(
			$global_script,
			'wccScanner',
			apply_filters( 'wcc_admin_scripts_scanner_config', array(), $global_script )
		);
		wp_localize_script(
			$global_script,
			'wccLanguages',
			apply_filters( 'wcc_admin_scripts_languages', array(), $global_script )
		);
		wp_localize_script(
			$global_script,
			'wccBannerConfig',
			apply_filters(
				'wcc_admin_scripts_banner_config',
				array(
					'_shortCodes' => $this->prepare_shortcodes(),
				),
				$global_script
			)
		);
		wp_localize_script(
			$global_script,
			'wccAppMenus',
			$this->get_registered_menus( true )
		);
		wp_localize_script(
			$global_script,
			'wccAppNotices',
			$notice->get()
		);
	}

	/**
	 * Prepare shortcodes for banner preview.
	 *
	 * @return array
	 */
	public function prepare_shortcodes() {
		$data   = array();
		$data[] = array(
			'key'     => 'wcc_readmore',
			'content' => do_shortcode( '[wcc_readmore]' ),
			'tag'     => 'readmore-button',
		);
		$data[] = array(
			'key'        => 'wcc_show_desc',
			'content'    => do_shortcode( '[wcc_show_desc]' ),
			'tag'        => 'show-desc-button',
			'attributes' => array(),
		);
		$data[] = array(
			'key'        => 'wcc_hide_desc',
			'content'    => do_shortcode( '[wcc_hide_desc]' ),
			'tag'        => 'hide-desc-button',
			'attributes' => array(),
		);
		return $data;
	}
	/**
	 * Register main menu and sub menus
	 *
	 * @return void
	 */
	public function admin_menu() {
		$capability = 'manage_options';
		$slug       = 'cookie-consent';

		// Load the SVG image file
		$logo_path = WCC_PLUGIN_URL . 'admin/dist/img/icon.svg';
		$hook      = add_menu_page(
			__( 'Cookie Consent', 'webtoffee-cookie-consent' ),
			__( 'Cookie Consent', 'webtoffee-cookie-consent' ),
			$capability,
			$slug,
			array( $this, 'menu_page_template' ),
			$logo_path,
			40
		);
	}

	/**
	 * Get regisered menus from each module.
	 *
	 * @param boolean $minify Whether to minify or not.
	 * @return array
	 */
	public function get_registered_menus( $minify = false ) {
		$menus = apply_filters( 'wcc_registered_admin_menus', array() );
		if ( true === $minify ) {
			foreach ( $menus as $key => $menu ) {
				unset( $menu['callback'] );
				$menus[ $key ] = $menu;
			}
		}
		return $menus;
	}
	/**
	 * Main menu template
	 *
	 * @return void
	 */
	public function menu_page_template() {
		echo '<div id="wcc-app"></div>';
	}

	/**
	 * Add custom class to admin body tag.
	 *
	 * @param string $classes List of classes.
	 * @return string
	 */
	public function admin_body_classes( $classes ) {
		if ( true === wcc_is_admin_page() ) {
			$classes .= ' wcc-app-admin';
		}
		return $classes;
	}

	/**
	 * Returns Jed-formatted localization data. Added for backwards-compatibility.
	 *
	 * @since 4.0.0
	 *
	 * @param  string $domain Translation domain.
	 * @return array          The information of the locale.
	 */
	public function get_jed_locale_data( $domain ) {
		$translations = get_translations_for_domain( $domain );
		$locale       = array(
			'' => array(
				'domain' => $domain,
				'lang'   => is_admin() && function_exists( 'get_user_locale' ) ? get_user_locale() : get_locale(),
			),
		);

		if ( ! empty( $translations->headers['Plural-Forms'] ) ) {
			$locale['']['plural_forms'] = $translations->headers['Plural-Forms'];
		}

		foreach ( $translations->entries as $msgid => $entry ) {
			$locale[ $msgid ] = $entry->translations;
		}

		// If any of the translated strings incorrectly contains HTML line breaks, we need to return or else the admin is no longer accessible.
		$json = wp_json_encode( $locale );
		if ( preg_match( '/<br[\s\/\\\\]*>/', $json ) ) {
			return array();
		}

		return $locale;
	}

	/**
	 * Hide all the unrelated notices from plugin page.
	 *
	 * @since 3.0.0
	 * @return void
	 */
	public function hide_admin_notices() {
		// Bail if we're not on the plugin screen.
		if ( empty( $_REQUEST['page'] ) || ! preg_match( '/cookie-consent/', esc_html( wp_unslash( $_REQUEST['page'] ) ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			return;
		}
		global $wp_filter;

		$notices_type = array(
			'user_admin_notices',
			'admin_notices',
			'all_admin_notices',
		);

		foreach ( $notices_type as $type ) {
			if ( empty( $wp_filter[ $type ]->callbacks ) || ! is_array( $wp_filter[ $type ]->callbacks ) ) {
				continue;
			}

			foreach ( $wp_filter[ $type ]->callbacks as $priority => $hooks ) {
				foreach ( $hooks as $name => $arr ) {
					if ( is_object( $arr['function'] ) && $arr['function'] instanceof \Closure ) {
						unset( $wp_filter[ $type ]->callbacks[ $priority ][ $name ] );
						continue;
					}
					$class = ! empty( $arr['function'][0] ) && is_object( $arr['function'][0] ) ? strtolower( get_class( $arr['function'][0] ) ) : '';

					if ( ! empty( $class ) && preg_match( '/^(?:wcc)/', $class ) ) {
						continue;
					}
					if ( ! empty( $name ) && ! preg_match( '/^(?:wcc)/', $name ) ) {
						unset( $wp_filter[ $type ]->callbacks[ $priority ][ $name ] );
					}
				}
			}
		}
	}

	/**
	 * Load plugin for the first time.
	 *
	 * @return void
	 */
	public function load_plugin() {
		if ( is_admin() && 'true' === get_option( 'wcc_first_time_activated_plugin' ) ) {
			do_action( 'wcc_after_first_time_install' );
			delete_option( 'wcc_first_time_activated_plugin' );
		}
	}

	/**
	 * Modify plugin action links on plugin listing page.
	 *
	 * @param array $links Existing links.
	 * @return array
	 */
	public function plugin_action_links( $links ) {
		$links[] = '<a href="https://www.webtoffee.com/support/" target="_blank">' . esc_html__( 'Support', 'webtoffee-cookie-consent' ) . '</a>';
		$links[] = '<a href="' . get_admin_url( null, 'admin.php?page=cookie-consent' ) . '">' . esc_html__( 'Settings', 'webtoffee-cookie-consent' ) . '</a>';
		return array_reverse( $links );
	}
}
