<?php
/**
 * Readabler
 * Web accessibility for Your WordPress site.
 * Exclusively on https://1.envato.market/readabler
 *
 * @encoding        UTF-8
 * @version         2.0.12
 * @copyright       (C) 2018 - 2024 Merkulove ( https://merkulov.design/ ). All rights reserved.
 * @license         Envato License https://1.envato.market/KYbje
 * @contributors    Nemirovskiy Vitaliy (nemirovskiyvitaliy@gmail.com), Dmitry Merkulov (dmitry@merkulov.design)
 * @support         help@merkulov.design
 * @license         Envato License https://1.envato.market/KYbje
 **/

namespace Merkulove\Readabler;

use Exception;
use Merkulove\Readabler\Tabs\TabAccessibilityStatement;
use Merkulove\Readabler\Tabs\TabAdvanced;
use Merkulove\Readabler\Tabs\TabAnalyzer;
use Merkulove\Readabler\Tabs\TabDesign;
use Merkulove\Readabler\Tabs\TabHotKeys;
use Merkulove\Readabler\Tabs\TabInitialSettings;
use Merkulove\Readabler\Tabs\TabModalPopup;
use Merkulove\Readabler\Tabs\TabOpenButton;
use Merkulove\Readabler\Tabs\TabReadablerGeneral;
use Merkulove\Readabler\Tabs\TabUsageAnalytics;
use Merkulove\Readabler\Tabs\TabVoiceNavigation;
use Merkulove\Readabler\Unity\Plugin;
use Merkulove\Readabler\Unity\Settings;

/** Exit if accessed directly. */
if ( ! defined( 'ABSPATH' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit;
}

final class Config {

	/**
	 * The one true Settings.
	 *
	 * @since 1.0.0
	 * @access private
	 * @var Config
	 **/
	private static $instance;

	/**
	 * All accessibility modes
	 * @return array
	 */
	public static function all_accessibility_modes(): array {

		return array(
			'profile_epilepsy'             => esc_html__( 'Epilepsy Safe Mode', 'readabler' ),
			'profile_visually_impaired'    => esc_html__( 'Visually Impaired Mode', 'readabler' ),
			'profile_cognitive_disability' => esc_html__( 'Cognitive Disability Mode', 'readabler' ),
			'profile_adhd_friendly'        => esc_html__( 'ADHD Friendly Mode', 'readabler' ),
			'profile_blind_users'          => esc_html__( 'Blindness Mode', 'readabler' ),
			'content_scaling'              => esc_html__( 'Content Scaling', 'readabler' ),
			'readable_font'                => esc_html__( 'Readable Font', 'readabler' ),
			'dyslexia_font'                => esc_html__( 'Dyslexia Friendly', 'readabler' ),
			'highlight_titles'             => esc_html__( 'Highlight Titles', 'readabler' ),
			'highlight_links'              => esc_html__( 'Highlight Links', 'readabler' ),
			'font_sizing'                  => esc_html__( 'Font Sizing', 'readabler' ),
			'line_height'                  => esc_html__( 'Line Height', 'readabler' ),
			'letter_spacing'               => esc_html__( 'Letter Spacing', 'readabler' ),
			'text_magnifier'               => esc_html__( 'Text Magnifier', 'readabler' ),
			'align_center'                 => esc_html__( 'Align Center', 'readabler' ),
			'align_left'                   => esc_html__( 'Align Left', 'readabler' ),
			'align_right'                  => esc_html__( 'Align Right', 'readabler' ),
			'dark_contrast'                => esc_html__( 'Dark Contrast', 'readabler' ),
			'light_contrast'               => esc_html__( 'Light Contrast', 'readabler' ),
			'monochrome'                   => esc_html__( 'Monochrome', 'readabler' ),
			'high_saturation'              => esc_html__( 'High Saturation', 'readabler' ),
			'high_contrast'                => esc_html__( 'High Contrast', 'readabler' ),
			'low_saturation'               => esc_html__( 'Low Saturation', 'readabler' ),
			'mute_sounds'                  => esc_html__( 'Mute Sounds', 'readabler' ),
			'hide_images'                  => esc_html__( 'Hide Images', 'readabler' ),
			'hide_emoji'                   => esc_html__( 'Hide Emoji', 'readabler' ),
			'virtual_keyboard'             => esc_html__( 'Virtual Keyboard', 'readabler' ),
			'reading_guide'                => esc_html__( 'Reading Guide', 'readabler' ),
			'cognitive_reading'            => esc_html__( 'Cognitive Reading', 'readabler' ),
			'useful_links'                 => esc_html__( 'Useful Links', 'readabler' ),
			'stop_animations'              => esc_html__( 'Stop Animations', 'readabler' ),
			'reading_mask'                 => esc_html__( 'Reading Mask', 'readabler' ),
			'highlight_hover'              => esc_html__( 'Highlight Hover', 'readabler' ),
			'highlight_focus'              => esc_html__( 'Highlight Focus', 'readabler' ),
			'big_black_cursor'             => esc_html__( 'Big Dark Cursor', 'readabler' ),
			'big_white_cursor'             => esc_html__( 'Big Light Cursor', 'readabler' ),
			'text_to_speech'               => esc_html__( 'Text to Speech', 'readabler' ),
			'voice_navigation'             => esc_html__( 'Voice Navigation', 'readabler' ),
			'keyboard_navigation'          => esc_html__( 'Keyboard Navigation', 'readabler' )
		);

	}

	/**
	 * Google languages
	 * @var string[][]
	 */
	public static $languages = [ // TODO: Remove this and make works this with Language.php
		'da-DK'  => 'Danish (Dansk)',
		'nl-NL'  => 'Dutch (Nederlands)',
		'en-AU'  => 'English (Australian)',
		'en-GB'  => 'English (UK)',
		'en-US'  => 'English (US)',
		'fr-CA'  => 'French Canada (Français)',
		'fr-FR'  => 'French France (Français)',
		'de-DE'  => 'German (Deutsch)',
		'it-IT'  => 'Italian (Italiano)',
		'ja-JP'  => 'Japanese (日本語)',
		'ko-KR'  => 'Korean (한국어)',
		'nb-NO'  => 'Norwegian (Norsk)',
		'pl-PL'  => 'Polish (Polski)',
		'pt-BR'  => 'Portuguese Brazil (Português)',
		'pt-PT'  => 'Portuguese Portugal (Portugal)',
		'ru-RU'  => 'Russian (Русский)',
		'sk-SK'  => 'Slovak (Slovenčina)',
		'es-ES'  => 'Spanish (Español)',
		'sv-SE'  => 'Swedish (Svenska)',
		'tr-TR'  => 'Turkish (Türkçe)',
		'uk-UA'  => 'Ukrainian (Українська)',
		'ar-XA'  => 'Arabic (العربية)',
		'cs-CZ'  => 'Czech (Čeština)',
		'el-GR'  => 'Greek (Ελληνικά)',
		'en-IN'  => 'Indian English',
		'fi-FI'  => 'Finnish (Suomi)',
		'vi-VN'  => 'Vietnamese (Tiếng Việt)',
		'id-ID'  => 'Indonesian (Bahasa Indonesia)',
		'fil-PH' => 'Philippines (Filipino)',
		'hi-IN'  => 'Hindi (हिन्दी)',
		'hu-HU'  => 'Hungarian (Magyar)',
		'cmn-CN' => 'Chinese (官话)',
		'cmn-TW' => 'Taiwanese Mandarin (中文(台灣))',
		'bn-IN'  => 'Bengali (বাংলা)',
		'gu-IN'  => 'Gujarati (ગુજરાતી)',
		'kn-IN'  => 'Kannada (ಕನ್ನಡ)',
		'ml-IN'  => 'Malayalam (മലയാളം)',
		'ta-IN'  => 'Tamil (தமிழ்)',
		'te-IN'  => 'Telugu (తెలుగు)',
		'th-TH'  => 'Thai (ภาษาไทย)',
		'yue-HK' => 'Yue Chinese',
		'ro-RO'  => 'Romanian (Română)',
		'ca-ES'  => 'Catalan (Català)',
		'af-ZA'  => 'Afrikaans (South Africa)',
		'bg-BG'  => 'Bulgarian (Български)',
		'lv-LV'  => 'Latvian (Latvietis)',
		'sr-RS'  => 'Serbian (Cрпски)',
		'is-IS'  => 'Icelandic (Íslensk)',
		'es-US'  => 'US Spanish (Hispanoamericano)',
		'ms-MY'  => 'Malay (Malaysia)',
		'nl-BE'  => 'Dutch (Belgium)',
		'pa-IN'  => 'Punjabi (India)',
		'mr-IN'  => 'Marathi (India)',
		'eu-ES'  => 'Basque (Vasco)',
		'gl-ES'  => 'Galician (Galego)'
	];

	/**
	 * Get all tabs controls
	 *
	 * @return array
	 */
	public static function controls(): array {
		$controls                                    = [];
		$controls[ TabReadablerGeneral::$key ]       = TabReadablerGeneral::controls();
		$controls[ TabOpenButton::$key ]             = TabOpenButton::controls();
		$controls[ TabModalPopup::$key ]             = TabModalPopup::controls();
		$controls[ TabDesign::$key ]                 = TabDesign::controls();
		$controls[ TabAccessibilityStatement::$key ] = TabAccessibilityStatement::controls();
		$controls[ TabHotKeys::$key ]                = TabHotKeys::controls();
		$controls[ TabInitialSettings::$key ]        = TabInitialSettings::controls();
		$controls[ TabAnalyzer::$key ]               = TabAnalyzer::controls();
		$controls[ TabUsageAnalytics::$key ]         = TabUsageAnalytics::controls();
		$controls[ TabAdvanced::$key ]               = TabAdvanced::controls();
		$controls[ TabVoiceNavigation::$key ]        = TabVoiceNavigation::controls();

		return $controls;
	}

	/**
	 * Get default settings
	 *
	 * @return array
	 */
	public static function defaults(): array {
		// Get default settings from all controls
		$controls_by_tab = self::controls();
		$defaults = [];
		foreach ( $controls_by_tab as $tab_key => $control ) {
			foreach ( $control as $field_key => $field ) {
				if ( isset( $field['default'] ) ) {
					$defaults[ $field_key ] = $field['default'];
				}
			}
		}

		// Meger with Unity default settings
		$unity_defaults = Settings::get_instance()->get_default_settings();
		return array_merge( $unity_defaults, $defaults, );
	}

	/**
	 * Add tabs to settings page
	 *
	 * @return void
	 */
	private function add_tabs() {
		TabReadablerGeneral::add_tab();
		TabOpenButton::add_tab();
		TabModalPopup::add_tab();
		TabDesign::add_tab();
		TabAccessibilityStatement::add_tab();
		TabHotKeys::add_tab();
		TabInitialSettings::add_tab();
		TabAnalyzer::add_tab();
		TabUsageAnalytics::add_tab();
		TabAdvanced::add_tab();
		TabVoiceNavigation::add_tab();
		TabTextToSpeech::add_tab();

		do_action( 'readabler_add_tabs' );
	}

	/**
	 * Add controls to tabs
	 *
	 * @return void
	 */
	private function add_controls() {
		TabReadablerGeneral::add_controls();
		TabOpenButton::add_controls();
		TabModalPopup::add_controls();
		TabDesign::add_controls();
		TabAccessibilityStatement::add_controls();
		TabHotKeys::add_controls();
		TabInitialSettings::add_controls();
		TabAnalyzer::add_controls();
		TabUsageAnalytics::add_controls();
		TabAdvanced::add_controls();
		TabVoiceNavigation::add_controls();
		try {
			TabTextToSpeech::add_controls();
		} catch ( Exception $e ) {
			error_log( $e->getMessage() );
		}

		do_action( 'readabler_add_controls' );
	}

	public function prepare_settings() {

		/** Reset API Key on fatal error. */
		if ( isset( $_GET['reset-api-key'] ) && '1' === $_GET['reset-api-key'] ) {
			$this->reset_api_key();
		}

		// Include the necessary WordPress file
		if ( ! function_exists( 'is_plugin_active' ) ) {
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
		}

		/** PHP version check. */
		if ( version_compare( PHP_VERSION, '8.1', '<' ) ) {
			if ( ! is_plugin_active( 'readabler-php7/readabler-php7.php' ) ) {
				add_action( 'admin_notices', function () {
					echo self::msg_php_7_to_8();
				} );
			}
		} else {
			if ( is_plugin_active( 'readabler-php7/readabler-php7.php' ) ) {
				add_action( 'admin_notices', function () {
					echo wp_sprintf(
						'<div class="notice notice-warning is-dismissible"><p><strong>Readabler</strong>: %s %s. %s</p></div>', //But you have installed the PHP 7 compatibility plugin.
						esc_html__( 'You have installed the Readabler PHP 7 compatibility plugin. Your current PHP version is', 'readabler' ),
						esc_attr( PHP_VERSION ),
						esc_html__( 'Readabler plugin compatible with PHP 8.1 or higher by default, you can deactivate and remove the Readabler PHP 7 compatibility plugin.', 'readabler' )
					);
				} );
			}
		}

		// Add server requirements to Status tab
		$this->add_server_requirements();

		// Add tabs
		$this->add_tabs();

		// Add controls
		$this->add_controls();

		/** Refresh settings. */
		Settings::get_instance()->get_options();

	}

	private function refresh_settings( $tabs ): array {

		/** Set updated tabs. */
		Plugin::set_tabs( $tabs );

		/** Refresh settings. */
		Settings::get_instance()->get_options();

		/** Get default plugin settings. */
		return Plugin::get_tabs();

	}

	/**
	 * Reset API Key on fatal error.
	 *
	 * @return void
	 **@since  1.0.0
	 * @access public
	 */
	public function reset_api_key() {

		/** Remove API Key. */
		$options            = get_option( 'mdp_readabler_text_to_speech_settings' );
		$options['api_key'] = '';

		/** Save new value. */
		update_option( 'mdp_readabler_text_to_speech_settings', $options );

		/** Go to Text to Speech tab. */
		wp_redirect( admin_url( '/admin.php?page=mdp_readabler_settings&tab=text_to_speech' ) );
		exit;

	}

	/**
	 * @return string
	 */
	private static function msg_php_7_to_8(): string {

		if ( version_compare( PHP_VERSION, '8.1', '<' ) ) {
			if ( ! is_plugin_active( 'readabler-php7/readabler-php7.php' ) ) {
				return wp_sprintf(
					'<div class="notice notice-error is-dismissible">
                                    <p>
                                        <strong>Readabler</strong>: %s %s. %s <strong>%s</strong> %s <code>%s</code> %s <code>%s</code> %s <a href="https://1.envato.market/cc-downloads" target="_blank">Codecanyon</a>.
                                    </p>
                                </div>',
					esc_html__( 'Plugin requires PHP 8.1 or higher. Your current PHP version is', 'readabler' ),
					esc_attr( PHP_VERSION ),
					esc_html__( 'Update your PHP version or install', 'readabler' ),
					'Readabler - PHP7',
					esc_html__( 'extension to continue using the plugin with the current PHP version. Find the', 'readabler' ),
					'readabler-php7.zip',
					esc_html__( 'in', 'readabler' ),
					'plugin/readabler-extensions',
					esc_html__( 'folder of the Readabler package downloaded from', 'readabler' )
				);
			}
		}

		return '';

	}

	/**
	 * Display server requirements on status tab
	 */
	private function add_server_requirements() {

		$tabs = Plugin::get_tabs();

		// Remove 'Delete plugin, settings, and data' option from Uninstall tab.
		unset( $tabs['migration']['fields']['delete_plugin']['options']['plugin+settings+data'] );

		$tabs['status']['reports']['server']['mbstring_installed'] = true;
		$tabs['status']['reports']['server']['server_time']        = true;
		$tabs['status']['reports']['server']['allow_url_fopen']    = false;
		$tabs['status']['reports']['server']['dom_installed']      = true;
		$tabs['status']['reports']['server']['xml_installed']      = true;
		$tabs['status']['reports']['server']['bcmath_installed']   = true;

		$tabs['custom_css']['description']  = esc_html__( 'Use custom CSS for more flexibility in customizing the accessibility window view for your theme. The parent class of the block with the player:', 'readabler' ) . ' <code>.mdp-readabler-wrapper</code>';
		$tabs['assignments']['description'] = esc_html__( 'Set the conditions under which the accessibility window will be shown/hidden on the page. Find out more about this from', 'readabler' ) . ' <a href="https://docs.merkulov.design/assignments-in-wordpress-plugins/" target="_blank">' . esc_html__( 'Assignments in WordPress plugin', 'readabler' ) . '</a>.';
		$tabs['migration']['description']   = esc_html__( 'Use this tab to export (import) plugin settings to another site and(or) permanently remove all settings from the current site.', 'readabler' );
		$tabs['status']['description']      = esc_html__( 'This tab displays the status of the plugin and the server requirements for its operation. Please note that all the necessary items are marked with a green checkmark, otherwise the plugin will not be able to work on your server.', 'readabler' );
		$tabs['updates']['description']     = esc_html__( 'This page contains all information about plugin updates and also allows you to check for an update for this plugin only.', 'readabler' );

		Plugin::set_tabs( $tabs );

	}

	/**
	 * Get default accessibility statement
	 * @return string
	 */
	public static function get_default_statement(): string {
		error_log( 'Readabler AI: Config::get_default_statement is deprecated. Update yor plugin for latest version' );

		return TabAccessibilityStatement::get_default_statement();
	}

	/**
	 * Main Settings Instance.
	 * Insures that only one instance of Settings exists in memory at any one time.
	 *
	 * @static
	 * @return Config
	 **@since 1.0.0
	 * @access public
	 *
	 */
	public static function get_instance(): Config {

		if ( ! isset( self::$instance ) && ! ( self::$instance instanceof self ) ) {

			self::$instance = new self;

		}

		return self::$instance;

	}

}
