<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class DateBook_Profile_Settings
 *
 * @class DateBook_Profile_Settings
 * @package DateBook/Classes
 * @author Pagick Themes
 */
class DateBook_Profile_Settings {


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

		add_action( 'init', array( __CLASS__, 'get_translated_cities' ) );

		add_action( 'datebook_register_proccess', array( __CLASS__, 'datebook_update_data' ) );
		add_action( 'datebook_registration_form', array( __CLASS__, 'datebook_show_register_form' ) );
		add_action( 'datebook_profile_settings', array( __CLASS__, 'datebook_show_register_form' ) );
		
		add_action( 'datebook_return_register_form', array( __CLASS__, 'datebook_return_register_form' ) );

		add_shortcode( 'datebook_registration_form', array( __CLASS__, 'datebook_return_register_form' ) );

	}


	/**
	 * Show the zodiac sign according to $day and $month on the Profile page
	 *
	 * @access public
	 */
	public static function datebook_zodiac($day, $month, $disable_html = 0, $display_title = 0) {

		global $datebook_zodiac_titles;

		$zodiac_name_out = '';

		if (isset($day) && $day > 0 && isset($month) && $month > 0) {

			if($display_title == 1){
				$zodiac_look = 2;
			} else {
				$zodiac_look = of_get_option('zodiac_look') ? of_get_option('zodiac_look') : 1;
			}

			$last_day = array('', 19, 18, 20, 20, 21, 21, 22, 22, 21, 22, 21, 20, 19);

			$month = ($month == 12) ? $month - 12 : $month;
			
			if($zodiac_look == 1){
				$zodiac_name = ($day > $last_day[$month]) ? esc_html__( $datebook_zodiac_titles[$month + 1][2], 'datebook' ) : esc_html__( $datebook_zodiac_titles[$month][2], 'datebook' );
			} else if($zodiac_look == 2){
				$zodiac_name = ($day > $last_day[$month]) ? esc_html__( $datebook_zodiac_titles[$month + 1][0], 'datebook' ) : esc_html__( $datebook_zodiac_titles[$month][0], 'datebook' );
			} else if($zodiac_look == 3){
				$zodiac_name = ($day > $last_day[$month]) ? $datebook_zodiac_titles[$month + 1][2] . ' ' . esc_html__( $datebook_zodiac_titles[$month + 1][0], 'datebook' ) : $datebook_zodiac_titles[$month][2] . ' ' . esc_html__( $datebook_zodiac_titles[$month][0], 'datebook' );
			} else if($zodiac_look == 4){
				$zodiac_name = ($day > $last_day[$month]) ? esc_html__( $datebook_zodiac_titles[$month + 1][0], 'datebook' ) . ' ' . $datebook_zodiac_titles[$month + 1][2] : esc_html__( $datebook_zodiac_titles[$month][0], 'datebook' ) . ' ' . $datebook_zodiac_titles[$month][2];
			}
			
			$zodiac_title = ($day > $last_day[$month]) ? esc_html__( $datebook_zodiac_titles[$month + 1][0], 'datebook' ) : esc_html__( $datebook_zodiac_titles[$month][0], 'datebook' );

			if($disable_html == 1){
				$zodiac_name_out = $zodiac_name;
			} else if($zodiac_look == 1){
				$zodiac_name_out = '<span title="' . $zodiac_title . '" data-toggle="tooltip" data-trigger="hover" data-placement="top" data-original-title="' . $zodiac_title . '">'. $zodiac_name . '</span>';
			} else {
				$zodiac_name_out = '<span class="badge badge-pill badge-light shadow-none" title="' . $zodiac_title . '" data-toggle="tooltip" data-trigger="hover" data-placement="top" data-original-title="' . $zodiac_title . '">'. $zodiac_name . '</span>';
			}

		}

		return $zodiac_name_out;

	}


	/**
	 * Check email, username and other data via ajax
	 *
	 * @access public
	 * @return void
	 */
	public static function proccess_ajax_settings() {
		
		if(isset($_GET['action']) && $_GET['action'] == 'datebook_ajax_actions' && isset($_GET['whatisit'])){

			$response = array('success' => 0, 'text' => esc_html__('Nothing changed', 'datebook' ));

			//Catch the whatisit - cities, logincheck, defaultimage, realphotodelete, activateprofile, logodelete, favoriteset, tourdelete, touredit
			$whatisit = isset( $_GET['whatisit'] ) ? esc_attr($_GET['whatisit']) : '';
			
			// Check if the email is free
			if ($whatisit == 'emailcheck') {

				$emailaddress = sanitize_email($_GET['email']);

				if ( is_email($emailaddress) ) {

					if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
						$current_user_id = DATEBOOK_CURRENT_USER_ID;
					} else {
						global $current_user;
						wp_get_current_user();
						$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
					}

					$currentauth = get_userdata($current_user_id);

					if ( email_exists($emailaddress) ) {

						if ( !is_user_logged_in() || (is_user_logged_in() && isset($currentauth->user_email) && $emailaddress != $currentauth->user_email) ) {

							$response = array(
								'success' => 1, 
								'text' => '<span class="badge badge-danger">' . esc_html__( 'This email is already registered. Try another.', 'datebook' ) . '</span>'
							);

						}

					} else {

						$response = array(
							'success' => 1, 
							'text' => '<span class="badge badge-success">' . esc_html__( 'You may use this email', 'datebook' ) . '</span>'
						);

					}

				}

			} else if ($whatisit == 'logincheck'){
				
				// Check if the login is free
				$username = !empty($_GET['user']) && strlen($_GET['user']) > 0 ? preg_replace("/([^a-zA-Z0-9])/", '', sanitize_text_field($_GET['user'])) : '';
				
				if ($username) {

					$min_characters_username = of_get_option('min_characters_username') ? of_get_option('min_characters_username') : 4;
					$max_characters_username = of_get_option('max_characters_username') ? of_get_option('max_characters_username') : 30;

					if (strlen($username) <= $min_characters_username || strlen($username) > $max_characters_username) {

						$response = array(
							'success' => 1, 
							'text' => '<span class="badge badge-danger">' . sprintf(esc_html__( 'Your username must be between %1$s and %2$s characters', 'datebook' ), $min_characters_username, $max_characters_username) . '</span>'
						);

					} else {

						if (username_exists($username)) {

							$response = array(
								'success' => 1, 
								'text' => '<span class="badge badge-danger">' . esc_html__( 'This username is already registered. Select another one.', 'datebook' ).'</span>'
							);

						} else {
							
							$response = array(
								'success' => 1, 
								'text' => ' '
							);
							
							}
					}
				}
			}

			wp_send_json($response);

			if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )) {

				die();

			}
		}
	}


	/**
	 * Create random number for Profile ID
	 *
	 * @access public
	 */
	public static function create_profile_slug($current_user_id) {

		$length = 10;

		$newprofile_number = substr( $current_user_id.time(), 0, $length );

		return $newprofile_number;

	}


	/**
	 * Update all data
	 *
	 * @access private
	 * @return void
	 */
	public static function datebook_update_data() {
		
		if ( isset( $_POST['change_profile_form'] ) &&  $_POST['change_profile_form'] == 1 && isset($_POST['action']) && $_POST['action'] == 'change') {

			if (is_user_logged_in()) {
				$whatform = 'settings_form';
				$termform = 'settings_formname';
			} else {
				$whatform = 'registration_form';
				$termform = 'registration_formname';
			}
			
			if(isset($_POST['profiletypereserved']) && $_POST['profiletypereserved'] > 0) {
				$profiletype = $_POST['profiletypereserved'];
				$term_category = get_term_meta( $profiletype, $termform, true );
			}

			$profile_form = isset($term_category) && !empty($term_category) ? $term_category : $whatform;

			// update all the input data
			DateBook_Forms::update_data($profile_form);

		}
	}


	/**
	 * Show settings form and process all data
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_return_register_form() {

		global $datebook_field_titles;
		set_query_var( 'datebook_field_titles', $datebook_field_titles );
		
		if (!is_user_logged_in() && of_get_option('enable_profile_registration') != '1') {

			// display the Registration Closed form
			return DateBook_Template_Loader::load( 'profile/register-closed' );

		} else if (!is_user_logged_in()) {

			// Get Profile types
			$categories = get_terms(array(
				'orderby' => 'term_id',
				'order' => 'ASC',
				'taxonomy' => DATEBOOK_PROFILES_TAX,
				'hide_empty' => false
			));

			// display the Rgistration form
			if (DateBook_Utilities::check_if_gateway_activated()) {

				$plans_count = 0;

				// Get Subscription plans
				$get_subscription_plans = get_option('datebook_subscription_plans');

				if (is_array($get_subscription_plans)){
					foreach($get_subscription_plans as $key => $value){
						if (isset($value['active']) && $value['active'] == 1) {
							$plans_count++;
						}
					}
				} 


				if(isset($_POST['action']) && ($_POST['action'] == 'change' || $_POST['action'] == 'subscriptionplan')) {

					return DateBook_Template_Loader::load( 'profile/profile-register-form' );

				} else if($plans_count > 0 && !isset($_POST['action'])) {

					if (of_get_option('register_subscribe_order') == '1') {

						if(isset($_POST['action']) && $_POST['action'] == 'profiletype' && $_POST['profiletypereserved'] > 0) {

							return DateBook_Template_Loader::load( 'profile/profile-register-form' );

						} else if(of_get_option('profiletype_order_in_registration') == 'profiletype_before_registration' && !empty($categories)){

							include DateBook_Template_Loader::locate( 'profile/profile-register-profile-type' );

						} else {

							return DateBook_Template_Loader::load( 'profile/profile-register-form' );
							
						}

					} else {

						if (of_get_option('profiletype_order_in_registration') == 'profiletype_before_registration' && !empty($categories)){

							include DateBook_Template_Loader::locate( 'profile/profile-register-profile-type' );

						} else {

							include DateBook_Template_Loader::locate( 'payment/registration-subscription-plans' );

						}
					}

				} else if(isset($_POST['action']) && $_POST['action'] == 'profiletype' && $_POST['profiletypereserved'] > 0) {

					if (of_get_option('register_subscribe_order') == '1') {

						return DateBook_Template_Loader::load( 'profile/profile-register-form' );

					} else {

						include DateBook_Template_Loader::locate( 'payment/registration-subscription-plans' );

					}

				}

			} else {

				if(isset($_POST['action']) && $_POST['action'] == 'profiletype' && $_POST['profiletypereserved'] > 0) {

					return DateBook_Template_Loader::load( 'profile/profile-register-form' );

				} else if(of_get_option('profiletype_order_in_registration') == 'profiletype_before_registration' && !empty($categories)){

					include DateBook_Template_Loader::locate( 'profile/profile-register-profile-type' );

				} else {

					return DateBook_Template_Loader::load( 'profile/profile-register-form' );

				}
			}

		} else {

			$option_name = preg_replace( "/\W/", '_', strtolower( get_option( 'stylesheet' ) ) );
			$themename = get_option( $option_name );
			if (!of_get_option('default_language') || $themename == '') {

				// display the Registration Closed form if Theme Options are not set yet
				return DateBook_Template_Loader::load( 'profile/register-closed' );
				
			} else {

				// display the Account Settings form
				return DateBook_Template_Loader::load( 'profile/profile-settings-shortcode' );

			}
		}
	}


	public static function get_language_code() {
		// Translated into = en_US, fr_FR, tr_TR, de_DE, es_ES, it_IT, ru_RU, nl
		$language_code = 'nl';
		return $language_code;
	}
	
	/**
	 * Get and save translated cities from Google
	 *
	 * @access private
	 */
	public static function get_translated_cities() {

		if (isset($_POST['action']) && $_POST['action'] == 'get_translated_words'){

			if (isset($_POST['datebook_city_name']) && is_array($_POST['datebook_city_name']) && !empty($_POST['datebook_city_name'])) {

				global $wpdb;

				$table_name = strtolower($wpdb->prefix) . 'datebook_countries'; // do not forget about tables prefix

				$languages_array = $item_ready = $get_translated_city = array();
				
				$success = $error = 0;
				
				// Get all translated cities
				$datebook_translated_cities = get_option('datebook_translated_cities') ? get_option('datebook_translated_cities') : array();

				$post_cities = $_POST['datebook_city_name'];
				
				foreach($post_cities as $key => $value){

					$get_translated_city[] = $key;

					$item = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table_name} WHERE id = %d", $key), ARRAY_A);

					if($item) {

						$item_name = maybe_unserialize($item['name']);
						
						foreach($item_name as $locale => $language) {
							$languages_array[$locale] = $language;
						}

						// Translated into = en_US, fr_FR, tr_TR, de_DE, es_ES, it_IT, ru_RU, nl
						$get_language_code = self::get_language_code();
						$languages_array[$get_language_code] = trim($value);

						$item_ready['name'] = maybe_serialize($languages_array);

						if( $wpdb->update($table_name, $item_ready, array('id' => $key)) === FALSE){
							//show failure message
							$error += 1;
						} else {
							// show success message
							$success += 1;
						}
					}
				}

				$all_translated_cities = array_merge($datebook_translated_cities, $get_translated_city);

				update_option('datebook_translated_cities', $all_translated_cities);

				$url = 'https://translate.google.com/translate?sl=en&tl=' . $get_language_code . '&u=https://demo1.pagickthemes.com/registration/?translate=google';

				//wp_redirect( $url );
				//exit;

			}
		}
	}


	/**
	 * Show Registration form
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_show_register_form() {

		if (is_user_logged_in() && !isset($_GET['translate'])) {

			echo DateBook_Template_Loader::load( 'profile/profile-settings' );

		} else {

			$get_language_code = self::get_language_code();

			if (of_get_option('enable_profile_registration') != '1') {

				// display the Registration Closed form
				echo DateBook_Template_Loader::load( 'profile/register-closed' );

			} else if(isset($_GET['translate']) && $_GET['translate'] == 'google'){

				global $wpdb;

				$table_name = strtolower($wpdb->prefix) . 'datebook_countries'; // do not forget about tables prefix

				// Get all countries
				$query_country = "SELECT * FROM {$table_name} WHERE parent_id = %d AND level = %d"; //  LIMIT 10 OFFSET 15

				// Select all countries only
				$get_countries_only = $wpdb->get_results($wpdb->prepare($query_country, 0, 0), ARRAY_A);


				// Get all countries
				if (count($get_countries_only) > 0) {

					$all_locations_array = array();

					$query_region = "SELECT * FROM {$table_name} WHERE parent_id = %d ORDER BY slug ASC";
					$query_city = "SELECT * FROM {$table_name} WHERE parent_id = %d ORDER BY slug ASC";

					// 1 step. Write all countries from database to file after they all were translated
					// Save only all countries in php file
					/*$str = serialize($get_countries_only);
					$str = urlencode($str);

					$content_out = '';

					$str_array = str_split($str, 30000);

					$content_out .= '
$content = \'\';';

					foreach($str_array as $str_content){

						$content_out .= '

$content .= \'' . $str_content . '\';';

					}

					$strenc = '<?php 
if ( ! defined("ABSPATH") ) {
	exit;
}
' . $content_out;

					$file = DATEBOOK_DIR . 'framework/sample/countries/all_countries.php';

					$myfile = fopen($file, "w") or die("Unable to open file!");
					fwrite($myfile, $strenc);
					fclose($myfile);*/


					// 2 step. Save all cities from database to php files
					/*for ($i = 1; $i <= 250; $i++) {
						$show_countries[] = $i;
					}
					foreach($get_countries_only as $key => $get_country_value){
						if(in_array($get_country_value['id'], $show_countries)){

							// Get all regions
							$all_regions_array = array();
							
							$get_regions_only = $wpdb->get_results($wpdb->prepare($query_region, $get_country_value['id']), ARRAY_A);

							if (count($get_regions_only) > 0) {
								foreach($get_regions_only as $key => $get_region_only){

									$all_cities_array = array();

									//$region_or_country = ($region_name != '') ? $region_name : $country_name;

									// Get all cities
									$get_cities_array = $wpdb->get_results($wpdb->prepare($query_city, $get_region_only['id']), ARRAY_A);

									if (count($get_cities_array) > 0) {
										foreach($get_cities_array as $key => $get_city_only){
											// All cities
											$all_cities_array[$get_city_only['id']] = array('name' => $get_city_only['name'], 'slug' => $get_city_only['slug'], 'parent_id' => $get_city_only['parent_id'], 'level' => 2, 'counter' => 0, 'class_counter' => 0, 'tour_counter' => 0, 'active' => 1);
										}
									}

									// All regions
									$all_regions_array[$get_region_only['id']] = array('name' => $get_region_only['name'], 'slug' => $get_region_only['slug'], 'parent_id' => $get_region_only['parent_id'], 'level' => 1, 'counter' => 0, 'class_counter' => 0, 'tour_counter' => 0, 'active' => 1, 'cities' => $all_cities_array);
									
								}
							}

							// All countries, regions, cities
							$all_locations_array = array('name' => $get_country_value['name'], 'slug' => $get_country_value['slug'], 'parent_id' => $get_country_value['parent_id'], 'level' => 0, 'counter' => 0, 'class_counter' => 0, 'tour_counter' => 0, 'active' => 1, 'regions' => $all_regions_array);

							$str = serialize($all_locations_array);
							$str = urlencode($str);

							$content_out = '';

							$str_array = str_split($str, 30000);
							
							$content_out .= '
$content = \'\';';

							foreach($str_array as $str_content){

								$content_out .= '

$content .= \'' . $str_content . '\';';

							}

							$strenc = '<?php 
if ( ! defined("ABSPATH") ) {
	exit;
}
' . $content_out;

							$file = DATEBOOK_DIR . 'framework/sample/countries/' . $get_country_value['slug'] . '.php';
							
							$myfile = fopen($file, "w") or die("Unable to open file!");
							fwrite($myfile, $strenc);
							fclose($myfile);

							

						}
					}*/

					//print_r($all_locations_array);
					//$arr = unserialize(urldecode($strenc));
					//var_dump($arr);
					
					/////////////////////////////////////////////////////////////////

					// Additional function. Display all cities that were not translated					
					/*$locale_array = array('en_US', 'fr_FR', 'tr_TR', 'de_DE', 'es_ES', 'it_IT', 'ru_RU', 'nl');

					echo '<table width="100%">';

					foreach( $all_locations_array as $key => $location ){

						$get_value_name_array = maybe_unserialize($location['name']);
						
						echo '<tr>';

						foreach( $locale_array as $locale ){

							$city_name = isset($get_value_name_array[$locale]) && !empty($get_value_name_array[$locale]) ? $get_value_name_array[$locale] : '';
							
							if($city_name == ''){$bgcolor = '#F9070B';} else {$bgcolor = '';}

							echo '<td bgcolor="' . $bgcolor . '">' . $locale . '</td><td bgcolor="' . $bgcolor . '">' . $city_name . '</td>';

						}

						echo '</tr>';

						foreach($location['regions'] as $subkey => $sublocation){

							$get_subvalue_name_array = maybe_unserialize($sublocation['name']);
							
							echo '<tr>';

							foreach( $locale_array as $locale ){

								$city_name = isset($get_subvalue_name_array[$locale]) && !empty($get_subvalue_name_array[$locale]) ? $get_subvalue_name_array[$locale] : '';
								
								if($city_name == ''){$bgcolor = '#F9070B';} else {$bgcolor = '';}

								echo '<td bgcolor="' . $bgcolor . '">' . $locale . '</td><td bgcolor="' . $bgcolor . '">' . $city_name . '</td>';

							}
							
							echo '</tr>';

							foreach($sublocation['cities'] as $subsubkey => $subsublocation){

								$get_subsubvalue_name_array = maybe_unserialize($subsublocation['name']);
								
								echo '<tr>';
								
								foreach( $locale_array as $locale ){

									$city_name = isset($get_subsubvalue_name_array[$locale]) && !empty($get_subsubvalue_name_array[$locale]) ? $get_subsubvalue_name_array[$locale] : '';
									
									if($city_name == ''){$bgcolor = '#F9070B';} else {$bgcolor = '';}

									echo '<td bgcolor="' . $bgcolor . '">' . $locale . '</td><td bgcolor="' . $bgcolor . '">' . $city_name . '</td>';

								}
								
								echo '</tr>';
								
							}
						}
					}

					echo '</table>';*/

					/////////////////////////////////////////////////////////////////

					// Display all cities for form to translate in Google
					// 1 step. Translate Countries
					//$pre_cities_only[] = $get_countries_only;

					// 2 step. Translate Regions
					/*foreach($get_countries_only as $key => $get_country_value){
							$country_name_array = maybe_unserialize( $get_country_value['name'] );
							$country_name = isset($country_name_array[DATEBOOK_WPLANG]) && !empty($country_name_array[DATEBOOK_WPLANG]) ? $country_name_array[DATEBOOK_WPLANG] : $country_name_array['en_US'];
							$pre_cities_only[$country_name] = $wpdb->get_results($wpdb->prepare($query_region, $get_country_value['id']), ARRAY_A);
					}*/

					// 3 step. Translate Cities
					/*for ($i = 241; $i <= 250; $i++) {
						$show_countries[] = $i;
					}

					foreach($get_countries_only as $key => $get_country_value){
						if(in_array($get_country_value['id'], $show_countries)){
							$country_name_array = maybe_unserialize( $get_country_value['name'] );
							$country_name = isset($country_name_array[DATEBOOK_WPLANG]) && !empty($country_name_array[DATEBOOK_WPLANG]) ? $country_name_array[DATEBOOK_WPLANG] : $country_name_array['en_US'];
							$get_regions_only = $wpdb->get_results($wpdb->prepare($query_region, $get_country_value['id']), ARRAY_A);

							// Get all regions
							if (count($get_regions_only) > 0) {
								foreach($get_regions_only as $key => $get_region_only){
									$cat_name_array = maybe_unserialize( $get_region_only['name'] );
									$region_name = isset($cat_name_array[DATEBOOK_WPLANG]) && !empty($cat_name_array[DATEBOOK_WPLANG]) ? $cat_name_array[DATEBOOK_WPLANG] : $cat_name_array['en_US'];

									$region_or_country = ($region_name != '') ? $region_name : $country_name;

									// Get all cities
									$pre_cities_only[$region_or_country] = $wpdb->get_results($wpdb->prepare($query_city, $get_region_only['id']), ARRAY_A);
								}
							}
						}
					}*/

				}

				// display the Countries list
				//include DateBook_Template_Loader::locate('search/countries-translate');

			} else {
				
				echo self::datebook_return_register_form();

				//echo DateBook_Template_Loader::load( 'profile/profile-register' );

			}
		}
	}


}

DateBook_Profile_Settings::init();