<?php

namespace FixAltText;

// Prevent Direct Access

( defined( 'ABSPATH' ) ) || die;

use FixAltText\HelpersLibrary\REQUEST;
use FixAltText\HelpersLibrary\Admin as Library_Admin;

/**
 * Class Admin - Handles all the admin functionality
 *
 * @package FixAltText
 * @since   1.0.0
 */
final class Admin extends Library_Admin {

	/**
	 * Set Hooks and display errors
	 *
	 * @package FixAltText
	 * @since   1.0.0
	 *
	 * @return void
	 */
	public static function init(): void {

		parent::init();

		if ( ! wp_doing_ajax() ) {

			if ( FIXALTTEXT_SLUG === REQUEST::key( 'page' ) ) {

				if ( ! defined( 'FIXALTTEXT_HELPERSLIBRARY_ADMIN_HIDE_NOTICES' ) ) {
					// Hide all other plugin notices on this page
					define( 'FIXALTTEXT_HELPERSLIBRARY_ADMIN_HIDE_NOTICES', true );
				}

				if ( ! defined( 'FIXALTTEXT_HELPERSLIBRARY_ADMIN_BODY_CLASS' ) ) {
					// Force styling to plugin pages
					define( 'FIXALTTEXT_HELPERSLIBRARY_ADMIN_BODY_CLASS', true );
				}

			}

			add_action( 'network_admin_menu', [
				self::class,
				'admin_menu',
			], 9999 );

			add_action( 'admin_menu', [
				self::class,
				'admin_menu',
			], 9999 );

			add_action( 'admin_enqueue_scripts', [
				self::class,
				'scripts',
			], 9 );

			// Add links to plugins page
			add_filter( 'plugin_action_links', [
				self::class,
				'plugin_action_links',
			], 10, 2 );

			add_filter( 'network_admin_plugin_action_links', [
				self::class,
				'plugin_action_links',
			], 10, 2 );

		}

		// Hook into Helper's Library to display notices inside of display_page()
		add_action( 'helpers_library_admin_notices', [
			self::class,
			'check_notices',
		], 0 );

		// Hook into Helper's Library get_current_tab()
		add_filter( 'helpers_library_admin_current_tab', [
			self::class,
			'get_current_tab',
		], 10, 0 );

		add_action( 'fixalttext_display_header', [
			self::class,
			'display_scan_needed_notice',
		], 10, 0 );

	}

	/**
	 * Displays the notice to tell user that a scan is needed
	 *
	 * @return void
	 */
	public static function display_scan_needed_notice(): void {
		if ( ! Scan::has_full_scan_ran() && ! Scan::is_full_scan_running() ) {
			// Scan is needed or the last scan is not finished
			Scan::display_results_not_available( true );
		}
	}

	/**
	 * Tells you which tab you are on adn sets the default tab
	 *
	 * @package FixAltText
	 * @since   1.0.0
	 *
	 * @return string
	 */
	public static function get_current_tab(): string {

		$tab = REQUEST::key( 'tab' );

		// Compensate for missing dashboard in network
		if ( is_network_admin() ) {
			if ( '' === $tab ) {
				$tab = 'settings';
			}
		} else {

			// Default to dashboard
			if ( '' === $tab ) {
				$tab = 'dashboard';
			}
		}

		return $tab;
	}

	/**
	 * Displays notices if needed
	 *
	 * @package FixAltText
	 * @since   1.0.0
	 *
	 * @return void
	 */
	public static function check_notices(): void {

		$scan = Scan::get_current( true );
		if ( $scan->get( 'needed' ) ) {
			// Scan is needed

			$settings = Settings::get_current_settings();

			if ( $settings->can_user_access_settings() ) {
				// User can run a scan themselves
				if ( $scan->get( 'start_date' ) ) {
					// Not our first rodeo
					$message = __( 'Settings have changed.', FIXALTTEXT_SLUG );
					$link_url = FIXALTTEXT_ADMIN_URL . '#scan';
					$link_anchor_text = __( 'Please run a new scan', FIXALTTEXT_SLUG );
				} else {
					$message = __( 'First, review settings and then, run an initial scan.', FIXALTTEXT_SLUG );
				}

			} else {
				// User doesn't have access to run a scan

				if ( $scan->get( 'start_date' ) ) {
					// Not our first rodeo
					$message = __( 'Settings have changed. Please request the administrator to run a new scan.', FIXALTTEXT_SLUG );
				} else {
					// Needs an initial scan
					$message = __( 'Please request the administrator to run an initial full scan.', FIXALTTEXT_SLUG );
				}
			}

			if ( $message ) {
				// Set defaults
				$link_url = $link_url ?? '';
				$link_anchor_text = $link_anchor_text ?? '';

				Admin::add_notice( [
					'message' => $message,
					'link_url' => $link_url,
					'link_anchor_text' => $link_anchor_text,
					'alert_level' => 'warning',
				] );
			}

		}
	}

	/**
	 * Adds links to this plugin on the plugin's management page
	 *
	 * @package FixAltText
	 * @since   1.0.0
	 *
	 * @param array  $links Array of links for the plugins, adapted when the current plugin is found.
	 * @param string $file  The filename for the current plugin, which the filter loops through.
	 *
	 * @return array
	 */
	public static function plugin_action_links( $links, $file ): array {

		// Show Settings Link
		if ( FIXALTTEXT_PLUGIN === $file ) {

			if ( is_network_admin() ) {
				$label = __( 'Network Settings', FIXALTTEXT_SLUG );
				$settings_url = FIXALTTEXT_SETTINGS_NETWORK_URL;
			} else {
				$label = __( 'Settings', FIXALTTEXT_SLUG );
				$settings_url = FIXALTTEXT_SETTINGS_URL;
			}
			// Settings Link
			$settings_link = '<a href="' . esc_url( $settings_url ) . '">' . esc_html( $label ) . '</a>';
			array_unshift( $links, $settings_link );

			if ( ! is_network_admin() ) {
				// Dashboard Link

				$dashboard_link = '<a href="' . esc_url( FIXALTTEXT_ADMIN_URL . '&tab=dashboard' ) . '">' . esc_html__( 'Dashboard', FIXALTTEXT_SLUG ) . '</a>';
				array_unshift( $links, $dashboard_link );
			}

			// Style Links
			$rate_link = '
<br /><a href="https://wordpress.org/support/plugin/fix-alt-text/reviews/#new-post">' . esc_html__( 'Rate:', FIXALTTEXT_SLUG ) . ' <span class="rate-us" data-stars="5"><span class="dashicons dashicons-star-filled star-1" title="' . esc_html__( 'Poor', FIXALTTEXT_SLUG ) . '"></span><span class="dashicons dashicons-star-filled star-2" title="' . esc_html__( 'Works', FIXALTTEXT_SLUG ) . '"></span><span class="dashicons dashicons-star-filled star-3" title="' . esc_html__( 'Good', FIXALTTEXT_SLUG ) . '"></span><span class="dashicons dashicons-star-filled star-4" title="' . esc_html__( 'Great', FIXALTTEXT_SLUG ) . '"></span><span class="dashicons dashicons-star-filled star-5" title="' . esc_html__( 'Fantastic!', FIXALTTEXT_SLUG ) . '"></span></span></a>
<style>
	.plugins .plugin-title [class*=dashicons-star-]{
		float: none;
		width: auto;
		height: auto;
		padding: 0;
		background: none;
	}
	.plugins .plugin-title .rate-us [class*=dashicons-star-]:before {
        font-size: 20px;
        color: #ffb900;
        background: none;
        padding: 0;
        box-shadow: none;
	}
	.plugins .plugin-title .rate-us:hover span:before {
		content: "\f154";
	}
	
	.plugins .plugin-title .rate-us:hover .star-1:before,
	.plugins .plugin-title .rate-us[data-stars="2"]:hover span.star-2:before,
	.plugins .plugin-title .rate-us[data-stars="3"]:hover span.star-2:before,
	.plugins .plugin-title .rate-us[data-stars="3"]:hover span.star-3:before,
	.plugins .plugin-title .rate-us[data-stars="4"]:hover span.star-2:before,
	.plugins .plugin-title .rate-us[data-stars="4"]:hover span.star-3:before,
	.plugins .plugin-title .rate-us[data-stars="4"]:hover span.star-4:before,
	.plugins .plugin-title .rate-us[data-stars="5"]:hover span:before {
		content: "\f155";
	}
</style>
<script>
jQuery(".plugins .plugin-title .rate-us span").on("mouseover", function(){
    let stars = jQuery(this).index() + 1;
   jQuery(this).closest(".rate-us").attr("data-stars", stars);
});
</script>';
			$links[] = $rate_link;
		}

		return $links;

	}

	/**
	 * Load Scripts
	 *
	 * @package FixAltText
	 * @since   1.0.0
	 *
	 * @return void
	 */
	public static function scripts(): void {

		global $pagenow;

		Debug::log( __( 'Loading Scripts', FIXALTTEXT_SLUG ) );

		$action = REQUEST::key('action');
		$page = REQUEST::key('page');
		$tab = Admin::get_current_tab();
		$post_id = REQUEST::int('post');

		// Only load on edit screen
		if ( ( 'post-new.php' == $pagenow || ( $action == 'edit' && $post_id ) ) && ! wp_doing_ajax() ) {

			$this_post = get_post( $post_id );
			$handle = FIXALTTEXT_SLUG;

			if ( 'attachment' === $this_post->post_type ) {
				// Editing Attachment

				$handle .= '-edit-attachment';

				// Load main plugin JS file
				wp_enqueue_script( $handle, FIXALTTEXT_ASSETS_URL . 'js/edit-attachment.js', [
					'jquery',
					'wp-i18n',
				], filemtime( FIXALTTEXT_ASSETS_DIR . '/js/edit-attachment.js' ), true );

			} else {
				// Editing Other Post Type

				$handle .= '-edit-post';

				// Load main plugin JS file
				wp_enqueue_script( $handle, FIXALTTEXT_ASSETS_URL . 'js/edit-post.js', [
					'jquery',
					'wp-i18n',
				], filemtime( FIXALTTEXT_ASSETS_DIR . '/js/edit-post.js' ), true );

			}

			if ( ! defined( $handle . '-js' ) ) {
				// Setting constant so that we'll know its already set to prevent double setting
				define( $handle . '-js', true );

				// Pass settings to JS
				wp_localize_script( $handle, 'FixAltTextSettings', Settings::get_array() );

				// Translation support
				wp_set_script_translations( $handle, FIXALTTEXT_SLUG );

			}

		}

		if ( $page == FIXALTTEXT_SLUG ) {

			define( 'FIXALTTEXT_HELPERSLIBRARY_ADMIN_SCRIPTS', true );

			wp_enqueue_script( FIXALTTEXT_SLUG . '-settings', FIXALTTEXT_ASSETS_URL . 'js/settings.js', [ 'jquery', 'wp-i18n' ], filemtime( FIXALTTEXT_ASSETS_DIR . '/js/settings.js' ), true );
			wp_localize_script( FIXALTTEXT_SLUG . '-settings', 'FixAltTextAjax', [ 'ajaxURL' => admin_url( 'admin-ajax.php' ) ] );
			wp_set_script_translations( FIXALTTEXT_SLUG . '-settings', FIXALTTEXT_SLUG );

			wp_enqueue_script( FIXALTTEXT_SLUG . '-table', FIXALTTEXT_ASSETS_URL . 'js/table.js', [ 'jquery', 'wp-i18n' ], filemtime( FIXALTTEXT_ASSETS_DIR . '/js/table.js' ), true );
			wp_localize_script( FIXALTTEXT_SLUG . '-table', 'FixAltTextAjax', [ 'ajaxURL' => admin_url( 'admin-ajax.php' ) ] );
			wp_set_script_translations( FIXALTTEXT_SLUG . '-table', FIXALTTEXT_SLUG );

			if ( ! is_network_admin() && ( '' == $tab || 'dashboard' == $tab ) ) {
				// Load dashboard

				define( 'FIXALTTEXT_HELPERSLIBRARY_ADMIN_DASHBOARD_SCRIPTS', true );
				wp_enqueue_script( FIXALTTEXT_SLUG . '-dashboard', FIXALTTEXT_ASSETS_URL . 'js/dashboard.js', [], filemtime( FIXALTTEXT_ASSETS_DIR . '/js/dashboard.js' ), true );
				wp_localize_script( FIXALTTEXT_SLUG . '-dashboard', 'FixAltTextAjax', [ 'ajaxURL' => admin_url( 'admin-ajax.php' ) ] );
				wp_set_script_translations( FIXALTTEXT_SLUG . '-dashboard', FIXALTTEXT_SLUG );

			}

		}

		if ( FIXALTTEXT_SLUG === $page || 'edit' == $action ) {

			if ( ! defined( 'FIXALTTEXT_HELPERSLIBRARY_ADMIN_STYLING' ) ) {
				// Add Helpers Library Styling
				define( 'FIXALTTEXT_HELPERSLIBRARY_ADMIN_STYLING', true );
			}

			wp_enqueue_style( FIXALTTEXT_SLUG . '-styles', FIXALTTEXT_ASSETS_URL . 'styles.css', [], filemtime( FIXALTTEXT_ASSETS_DIR . '/styles.css' ), 'all' );
		}

	}

	/**
	 * Add A Setting Page: Admin > Settings > SARE Backups
	 *
	 * @package FixAltText
	 * @since   1.0.0
	 *
	 * @return void
	 */
	public static function admin_menu(): void {

		if ( is_multisite() ) {

			if ( is_network_admin() ) {
				// Super Admins Only
				add_submenu_page( 'settings.php', FIXALTTEXT_NAME, FIXALTTEXT_NAME, 'manage_network', FIXALTTEXT_SLUG, [
					self::class,
					'display_page',
				] );
			}

		}

		if ( is_admin() ) {

			$settings = Settings::get_current_settings();

			if ( $settings->can_user_access_tool() ) {
				// User is allowed access
				add_submenu_page( 'tools.php', FIXALTTEXT_NAME, FIXALTTEXT_NAME, Settings::get_user_access_capability(), FIXALTTEXT_SLUG, [
					self::class,
					'display_page',
				] );
			}

		}

	}

}
