<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/* This function enables you to run your website in a different language than the backend of your website. So you can serve your website using e.g. German as the default language for the users, but keep English as the language for the administration.
*/

/**
 * Class DateBook_Post_Type_Property
 *
 * @class DateBook_Post_Type_Property
 * @package DateBook/Classes/Post_Types
 * @author Pagick Themes
 */
class DateBook_Localization {

	/**
	 * Hook actions and filters.
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function init() {
		
		self::datebook_all_locale();

		add_action( 'datebook_languages_dropdown', array( __CLASS__, 'datebook_languages_dropdown' ) );
		add_shortcode( 'datebook_languages_dropdown', array( __CLASS__, 'return_languages_dropdown' ) );

		add_filter( 'locale', array( __CLASS__, 'datebook_localize' ) );
	
	}
	
	
	/**
	 * List of locales
	 */
	private static function datebook_all_locale() {
	
		global $wp_locale_all;

		// locales available in the I18n repository: http://svn.automattic.com/wordpress-i18n/
		$wp_locale_all = array(
			'af' => esc_html__( 'Afrikaans', 'datebook' ),
			'sq' => esc_html__( 'Albanian', 'datebook' ),
			'am' => esc_html__( 'Amharic', 'datebook' ),
			'ar' => esc_html__( 'Arabic', 'datebook' ),
			'an' => esc_html__( 'Aragonese', 'datebook' ),
			'hy' => esc_html__( 'Armenian', 'datebook' ),
			'as' => esc_html__( 'Assamese', 'datebook' ),
			'az' => esc_html__( 'Azerbaijani', 'datebook' ),
			'az_TR' => esc_html__( 'Azerbaijani (Turkey)', 'datebook' ),
			'bcc' => esc_html__( 'Balochi Southern', 'datebook' ),
			'eu' => esc_html__( 'Basque', 'datebook' ),
			'be' => esc_html__( 'Belarusian', 'datebook' ),
			'bn_BD' => esc_html__( 'Bengali', 'datebook' ),
			'bs_BA' => esc_html__( 'Bosnian', 'datebook' ),
			'bg_BG' => esc_html__( 'Bulgarian', 'datebook' ),
			'my_MM' => esc_html__( 'Burmese (Myanmar)', 'datebook' ),
			'cpp' => esc_html__( 'Cape Verdean Creole', 'datebook' ),
			'ca' => esc_html__( 'Catalan', 'datebook' ),
			'zh_CN' => esc_html__( 'Chinese', 'datebook' ),
			'zh_HK' => esc_html__( 'Chinese (Hong Kong)', 'datebook' ),
			'zh_TW' => esc_html__( 'Chinese (Taiwan)', 'datebook' ),
			'co' => esc_html__( 'Corsican', 'datebook' ),
			'hr' => esc_html__( 'Croatian', 'datebook' ),
			'cy' => esc_html__( 'Cymraeg (Welsh)', 'datebook' ),
			'cs_CZ' => esc_html__( 'Czech', 'datebook' ),
			'da_DK' => esc_html__( 'Danish', 'datebook' ),
			'dv' => esc_html__( 'Divehi/Maldivian', 'datebook' ),
			'nl' => esc_html__( 'Dutch', 'datebook' ),
			'nl_BE' => esc_html__( 'Dutch (Belgium)', 'datebook' ),
			'nl_NL' => esc_html__( 'Dutch (Netherlands)', 'datebook' ),
			'en_US' => esc_html__( 'English', 'datebook' ),
			'en_AU' => esc_html__( 'English (Australia)', 'datebook' ),
			'en_CA' => esc_html__( 'English (Canada)', 'datebook' ),
			'en_GB' => esc_html__( 'English (United Kingdom)', 'datebook' ),
			'eo' => esc_html__( 'Esperanto', 'datebook' ),
			'et' => esc_html__( 'Estonian', 'datebook' ),
			'fo' => esc_html__( 'Faroese', 'datebook' ),
			'fi' => esc_html__( 'Finnish', 'datebook' ),
			'fr_FR' => esc_html__( 'French', 'datebook' ),
			'fr_BE' => esc_html__( 'French (Belgium)', 'datebook' ),
			'fuc' => esc_html__( 'Fulah', 'datebook' ),
			'ga' => esc_html__( 'Gaeilge/Irish', 'datebook' ),
			'gl_ES' => esc_html__( 'Galician', 'datebook' ),
			'ka_GE' => esc_html__( 'Georgian', 'datebook' ),
			'de_DE' => esc_html__( 'German', 'datebook' ),
			'de_CH' => esc_html__( 'German (Switzerland)', 'datebook' ),
			'el' => esc_html__( 'Greek', 'datebook' ),
			'gu' => esc_html__( 'Gujarati', 'datebook' ),
			'haw_US' => esc_html__( 'Hawaiian', 'datebook' ),
			'haz' => esc_html__( 'Hazaragi', 'datebook' ),
			'he_IL' => esc_html__( 'Hebrew', 'datebook' ),
			'hi_IN' => esc_html__( 'Hindi', 'datebook' ),
			'hu_HU' => esc_html__( 'Hungarian', 'datebook' ),
			'is_IS' => esc_html__( 'Icelandic', 'datebook' ),
			'ido' => esc_html__( 'Ido', 'datebook' ),
			'id_ID' => esc_html__( 'Indonesian', 'datebook' ),
			'it_IT' => esc_html__( 'Italian', 'datebook' ),
			'ja' => esc_html__( 'Japanese', 'datebook' ),
			'jv_ID' => esc_html__( 'Javanese', 'datebook' ),
			'kea' => esc_html__( 'Kabuverdianu', 'datebook' ),
			'kn' => esc_html__( 'Kannada', 'datebook' ),
			'kk' => esc_html__( 'Kazakh', 'datebook' ),
			'kin' => esc_html__( 'Kinyarwanda', 'datebook' ),
			'ko_KR' => esc_html__( 'Korean', 'datebook' ),
			'ku' => esc_html__( 'Kurdish', 'datebook' ),
			'ckb' => esc_html__( 'Kurdish', 'datebook' ),
			'ky_KY' => esc_html__( 'Kyrgyz', 'datebook' ),
			'lo' => esc_html__( 'Lao', 'datebook' ),
			'la' => esc_html__( 'Latin', 'datebook' ),
			'lv' => esc_html__( 'Latvian', 'datebook' ),
			'li' => esc_html__( 'Limburgish', 'datebook' ),
			'lt_LT' => esc_html__( 'Lithuanian', 'datebook' ),
			'mk_MK' => esc_html__( 'Macedonian', 'datebook' ),
			'mg_MG' => esc_html__( 'Malagasy', 'datebook' ),
			'ms_MY' => esc_html__( 'Malay', 'datebook' ),
			'ml_IN' => esc_html__( 'Malayalam', 'datebook' ),
			'mri' => esc_html__( 'Maori', 'datebook' ),
			'mr' => esc_html__( 'Marathi', 'datebook' ),
			'mn' => esc_html__( 'Mongolian', 'datebook' ),
			'me_ME' => esc_html__( 'Montenegrin', 'datebook' ),
			'ne_NP' => esc_html__( 'Nepali', 'datebook' ),
			'nb_NO' => esc_html__( 'Norwegian (Bokm&aring;l)', 'datebook' ),
			'nn_NO' => esc_html__( 'Norwegian (Nynorsk)', 'datebook' ),
			'ory' => esc_html__( 'Oriya', 'datebook' ),
			'os' => esc_html__( 'Ossetic/Ossetian', 'datebook' ),
			'pap' => esc_html__( 'Papiamento', 'datebook' ),
			'fa_IR' => esc_html__( 'Persian', 'datebook' ),
			'fa_AF' => esc_html__( 'Persian (Afghanistan)', 'datebook' ),
			'pl_PL' => esc_html__( 'Polish', 'datebook' ),
			'pt_PT' => esc_html__( 'Portuguese', 'datebook' ),
			'pt_BR' => esc_html__( 'Portuguese (Brazil)', 'datebook' ),
			'pa_IN' => esc_html__( 'Punjabi', 'datebook' ),
			'rhg' => esc_html__( 'Rohingya', 'datebook' ),
			'ro_RO' => esc_html__( 'Romanian', 'datebook' ),
			'ru_RU' => esc_html__( 'Russian', 'datebook' ),
			'ru_UA' => esc_html__( 'Russian (Ukraine)', 'datebook' ),
			'sah' => esc_html__( 'Sakha', 'datebook' ),
			'sa_IN' => esc_html__( 'Sanskrit', 'datebook' ),
			'srd' => esc_html__( 'Sardinian', 'datebook' ),
			'gd' => esc_html__( 'Scottish Gaelic', 'datebook' ),
			'sr_RS' => esc_html__( 'Serbian', 'datebook' ),
			'sd_PK' => esc_html__( 'Sindhi', 'datebook' ),
			'si_LK' => esc_html__( 'Sinhalese', 'datebook' ),
			'sk_SK' => esc_html__( 'Slovak', 'datebook' ),
			'sl_SI' => esc_html__( 'Slovenian', 'datebook' ),
			'so_SO' => esc_html__( 'Somali', 'datebook' ),
			'azb' => esc_html__( 'South Azerbaijani', 'datebook' ),
			'es_ES' => esc_html__( 'Spanish', 'datebook' ),
			'es_AR' => esc_html__( 'Spanish (Argentina)', 'datebook' ),
			'es_CL' => esc_html__( 'Spanish (Chile)', 'datebook' ),
			'es_MX' => esc_html__( 'Spanish (Mexico)', 'datebook' ),
			'es_PE' => esc_html__( 'Spanish (Peru)', 'datebook' ),
			'es_VE' => esc_html__( 'Spanish (Venezuela)', 'datebook' ),
			'su_ID' => esc_html__( 'Sundanese', 'datebook' ),
			'sw' => esc_html__( 'Swahili', 'datebook' ),
			'sv_SE' => esc_html__( 'Swedish', 'datebook' ),
			'gsw' => esc_html__( 'Swiss German', 'datebook' ),
			'tl' => esc_html__( 'Tagalog', 'datebook' ),
			'tg' => esc_html__( 'Tajik', 'datebook' ),
			'tzm' => esc_html__( 'Tamazight (Central Atlas)', 'datebook' ),
			'ta_IN' => esc_html__( 'Tamil', 'datebook' ),
			'ta_LK' => esc_html__( 'Tamil (Sri Lanka)', 'datebook' ),
			'tt_RU' => esc_html__( 'Tatar', 'datebook' ),
			'te' => esc_html__( 'Telugu', 'datebook' ),
			'th' => esc_html__( 'Thai', 'datebook' ),
			'bo' => esc_html__( 'Tibetan', 'datebook' ),
			'tr_TR' => esc_html__( 'Turkish', 'datebook' ),
			'tuk' => esc_html__( 'Turkmen', 'datebook' ),
			'ug_CN' => esc_html__( 'Uighur', 'datebook' ),
			'uk' => esc_html__( 'Ukrainian', 'datebook' ),
			'ur' => esc_html__( 'Urdu', 'datebook' ),
			'uz_UZ' => esc_html__( 'Uzbek', 'datebook' ),
			'vi' => esc_html__( 'Vietnamese', 'datebook' ),
			'fy' => esc_html__( 'Western Frisian', 'datebook' )
		);

	}


	/**
	 * Get all active languages from theme options
	 */
	public static function datebook_get_languages() {

		$datebook_locale_array = array();

		$files = glob( DATEBOOK_DIR . 'languages' . '/*.mo' );

		foreach ( $files as $file ) {

			$fileParts = pathinfo( $file );

			$fileParts[ 'filename' ] = substr( $fileParts[ 'basename' ], 0, strpos( $fileParts[ 'basename' ], '.' ) );
			$datebook_locale_array[] = str_replace( 'datebook' . '-', '', $fileParts[ 'filename' ] );

		}

		if ( ! in_array( 'en_US', $datebook_locale_array ) ) {
			$datebook_locale_array[] = 'en_US';
		}

		return $datebook_locale_array;

	}


	/**
	 * Check all language files available in language folder
	 */
	public static function datebook_all_available_language_files() {

		$languages_options = $active_languages = array();

		$changed_files = 0;

		if(isset($_GET['page']) && $_GET['page'] == 'datebook-options-framework' && isset($_GET['update']) && $_GET['update'] == 'percentage-translated-languages'){
			delete_option('datebook_all_languages_data');
		}

		$datebook_all_languages_data = get_option('datebook_all_languages_data');

		$active_languages = of_get_option('active_languages');

		$files = glob( DATEBOOK_DIR . 'languages' . '/*.mo' );

		foreach($files as $file) {

			// Check if translation file MO exists
			if (file_exists($file)) {

				$filemtime = filemtime($file);
				$filesize = filesize($file);
				$fileParts = pathinfo($file);
				$locale = str_replace( 'datebook-', '', $fileParts[ 'filename' ] );

				$percentage = isset($datebook_all_languages_data[$locale]['percent']) ? $datebook_all_languages_data[$locale]['percent'] : 0;
				$total = isset($datebook_all_languages_data[$locale]['total']) ? $datebook_all_languages_data[$locale]['total'] : 0;
				$untranslated = isset($datebook_all_languages_data[$locale]['untranslated']) ? $datebook_all_languages_data[$locale]['untranslated'] : 0;
				$translated = isset($datebook_all_languages_data[$locale]['translated']) ? $datebook_all_languages_data[$locale]['translated'] : 0;

				$all_languages_filemtime = isset($datebook_all_languages_data[$locale]['filemtime']) ? $datebook_all_languages_data[$locale]['filemtime'] : 0;
				$all_languages_filesize = isset($datebook_all_languages_data[$locale]['filesize']) ? $datebook_all_languages_data[$locale]['filesize'] : 0;

				if($all_languages_filemtime !== $filemtime || $all_languages_filesize !== $filesize){

					$changed_files++;

					$translations = Gettext\Extractors\Po::extract($fileParts['dirname'] . '/' . $fileParts['filename'].'.po');

					// Count translated strings
					foreach ($translations as $translation) {
						$total++;
						if (!$translation->hasTranslation()) {
							$untranslated++;
						}
					}

					$translated = $total - $untranslated;
					$percentage = round($translated / $total * 100, 2 );

				}

				$add_active_language = isset($active_languages[$locale]) && $active_languages[$locale] == 1 ? 1 : 0;

				$checked = ($percentage == 100 || $add_active_language == 1) ? 1 : 0;

				$languages_options[$locale] = array('locale' => $locale, 'percent' => $percentage, 'total' => $total, 'untranslated' => $untranslated, 'translated' => $translated, 'filemtime' => $filemtime, 'filesize' => $filesize, 'checked' => $checked);

			}

		}

		if($changed_files > 0){
			update_option('datebook_all_languages_data', $languages_options);
		}

		return $languages_options;

	}


	/**
	 * Get saved locale
	 */
	private static function datebook_get_locale() {
		
		$datebook_cookie_return = isset( $_REQUEST[ 'datebook_language' ] ) ? htmlspecialchars( $_REQUEST[ 'datebook_language' ] ) : ( isset( $_COOKIE[ 'datebook_language' ] ) ? $_COOKIE[ 'datebook_language' ] : of_get_option('default_language') );
		
		return $datebook_cookie_return;
	}
	

	/**
	 * Sets the cookie. (1 year expiry)
	 */
	private static function datebook_set_cookie() {
		setcookie( 'datebook_language', '', strtotime( '-1 hour' ), '/' );
		setcookie( 'datebook_language', htmlspecialchars( $_REQUEST[ 'datebook_language' ] ), strtotime( '+1 year' ), '/' );
	}
	

	/**
	 * Set locale for the frontend of website
	 */
	public static function datebook_localize( $locale ) {
		
		if (isset($_COOKIE['datebook_language'])) {

			$locale = self::datebook_get_locale();

		} else if (of_get_option('default_language') != '' ){

			$locale = of_get_option('default_language');

		} else {

			$locale = 'en_US';

		}

		return $locale;

	}


	/**
	 * Return dropdown menu - This is for shortcode
	 */
	public static function return_languages_dropdown($atts = array()) {

		global $wp_locale_all;
		
		$layout = $layout_list = '';

		if (of_get_option('show_language_menu') == '1') {
			
			// Catch request for language and set cookie
			if(isset($_REQUEST[ 'datebook_language' ])) {
				
				//Cast variable
				$cookie_value = intval($_REQUEST[ 'datebook_language' ]);

				//Set cookie
				$cookie_value === 1 ? self::datebook_set_cookie(1) : self::datebook_set_cookie(0);

			}

			$datebook_locale = self::datebook_get_locale();

			$active_languages = of_get_option('active_languages');

			$default_language = of_get_option('default_language');

			if(empty($active_languages) || $default_language == 'en_US'){
				$active_languages['en_US'] = 1;
			}
			
			if(isset($atts['style'])){
				$language_menu_style = $atts['style'] == 'dropdown' ? 'dropdown' : 'list';
			} else {
				$language_menu_style = of_get_option('language_menu_style') == 'dropdown' ? 'dropdown' : 'list';
			}

			if($language_menu_style == 'dropdown'){

				$layout .= '<select id="datebook-language" class="custom-select custom-select-sm w-auto" name="datebook_language">';

				foreach ( $active_languages as $locale_key => $locale_value ) :

					if((isset($default_language) && $default_language == $locale_key) || (isset($active_languages[$locale_key]) && $active_languages[$locale_key] == 1)){

						$selected = ( $datebook_locale == $locale_key ) ? ' selected="selected"' : '';

						$layout .= '<option value="' . esc_attr( $locale_key ) . '"' . $selected . '>' . esc_html($wp_locale_all[$locale_key]) . '</option>';

					}

				endforeach;

				$layout .= '</select>';

			} else if($language_menu_style == 'list'){

				$shortcode_color = isset($atts['color']) ? 'color:' . $atts['color'] . ';' : '';

				$layout .= '<ul class="list-inline text-center">';

				foreach ( $active_languages as $locale_key => $locale_value ) :

					if((isset($default_language) && $default_language == $locale_key) || (isset($active_languages[$locale_key]) && $active_languages[$locale_key] == 1)){

						$selected = ( $datebook_locale == $locale_key ) ? ' border-bottom' : '';

						$layout .= '<li class="list-inline-item"><a class="datebook-language' . $selected . '" data-id="' . esc_attr( $locale_key ) . '" href="javascript:void(0)" style="' . $shortcode_color . '">' . esc_html($wp_locale_all[$locale_key]) . '</a></li>';

					}

				endforeach;

				$layout .= '</ul>';

			}

		}

		return $layout;

	}


	/**
	 * Create dropdown menu - frontend
	 */
	public static function datebook_languages_dropdown() {

		echo self::return_languages_dropdown();

	}
	
	
}

DateBook_Localization::init();