<?php

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

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


	private static $datebook_options = null;


    public function __construct($datebook_options_array) {

		self::$datebook_options = $datebook_options_array;

		self::init();

	}


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

		add_action( 'datebook_edit_tour', array( __CLASS__, 'datebook_process_edit_tour' ) );
		add_action( 'datebook_ajax_tour', array( __CLASS__, 'datebook_process_ajax_tour' ) );

	}


	/**
	 * Contact profile proccess
	 *
	 * @access private
	 * @return void
	 */
	private static function datebook_send_message_to_profile() {
		
		global $current_user, $post;
		wp_get_current_user();
		
		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);
		}

		// Someone sends a message to another user
		if (isset($_POST['action']) && $_POST['action'] == 'contacting') {

			if ($_POST['emails']) { $datebook_alert_error .= '.'; }
			
			if (is_user_logged_in()) {
				$from_contacting_name = $current_user->display_name;
				$from_contacting_email = $current_user->user_email;
			} else {
				$from_contacting_name = sanitize_text_field($_POST['contacting_name']);
				if (!$from_contacting_name) {
					$datebook_alert_error .= esc_html__( 'Your name is missing', 'datebook' )."<br />";
				}
				
				$from_contacting_email = sanitize_email($_POST['contacting_email']);
				if ($from_contacting_email) {
					if ( !is_email($from_contacting_email) ) {
						$datebook_alert_error .= esc_html__( 'Your email address seems to be wrong', 'datebook' )."<br />";
					}
				} else {
					$datebook_alert_error .= esc_html__( 'Your email is missing', 'datebook' )."<br />";
				}
			}
			
			$from_contacting_text = sanitize_text_field(wp_strip_all_tags($_POST['contacting_text']));
			if (!$from_contacting_text) {
				$datebook_alert_error .= esc_html__( 'You need to write a message', 'datebook' )."<br />";
			}

			if (!$datebook_alert_error) {
				
				$profile_id = get_the_ID();
				$profile_name = $from_contacting_name;

				$profile_get_permalink = get_permalink($profile_id);
				
				$to_email = get_the_author_meta(user_email);

				$select_email_template = 'new_message_to_profile';

				include DateBook_Template_Loader::locate( 'misc/email-templates' );

				$subject_in_email = esc_html__( 'Contact message from', 'datebook' ) . ' ' . self::$datebook_options['email_sitename'];

				$datebook_mail = DateBook_Utilities::datebook_email_send($from_contacting_name, $from_contacting_email, $to_email, $subject_in_email, $body);

				unset($from_contacting_name, $from_contacting_email, $from_contacting_text, $body);
				$alert_success = esc_html__( 'Your message has been sent', 'datebook' );

			}
		}
	}


	/**
	 * Delete tour
	 *
	 * @access private
	 * @return void
	 */
	private static function datebook_delete_tour() {

		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);
		}

		// Delete tour
		if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['confirm']) && $_GET['confirm'] == 'yes' && isset($_GET['tour_id']) && $_GET['tour_id'] > 0) {

			$tour = get_post(absint($_GET['tour_id']));
			$tour_author = isset($tour->post_author) && $tour->post_author > 0 ? $tour->post_author : 0;
			$tour_id = isset($tour->ID) && $tour->ID > 0 ? $tour->ID : 0;

			if ($tour_author == $current_user_id || is_super_admin()) {

				global $wpdb;
				
				$table_countries = strtolower($wpdb->prefix) . "datebook_countries";

				$get_tour_country = get_post_meta($tour_id, 'country', true);
				$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET tour_counter = tour_counter - 1 WHERE id = %d", $get_tour_country) );

				$get_tour_region = get_post_meta($tour_id, 'region', true);
				$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET tour_counter = tour_counter - 1 WHERE id = %d", $get_tour_region) );

				$get_tour_city = get_post_meta($tour_id, 'city', true);
				$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET tour_counter = tour_counter - 1 WHERE id = %d", $get_tour_city) );

				wp_delete_post($tour_id, true );

				echo '<div class="alert alert-success">'.esc_html__( 'Tour has been deleted', 'datebook' ).'</div>';

			}

		} else if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['tour_id']) && $_GET['tour_id'] > 0) {
			
			$my_tours_link = get_permalink(self::$datebook_options['my_tours_page']);

			$my_tours_link_args = add_query_arg( array(
				'action' => 'delete',
				'confirm' => 'yes',
				'tour_id' => absint($_GET['tour_id']),
			), $my_tours_link );

			echo '<div class="alert alert-danger alert-dismissable">';
			echo '<h4 class="alert-heading">' . esc_html__( 'Delete the tour', 'datebook' ) . ' - #' . absint($_GET['tour_id']) . '?</h4>';
			echo '<p>' . esc_html__( 'Do you really want to delete the tour', 'datebook' ) . '? ' . esc_html__( 'This action cannot be undone', 'datebook' ).'.</p>';
			echo '<p><a href="' . esc_url($my_tours_link_args) . '" class="btn btn-danger">' . esc_html__( 'Yes, delete!', 'datebook' ) . '</a> <a href="' . esc_url($my_tours_link) . '" class="btn btn-link">' . esc_html__( 'No, do not delete!', 'datebook' ) . '</a></p>';
			echo '</div>';

		}

	}


	/**
	 * Validate all input data
	 *
	 * @access private
	 */
	private static function datebook_validate_form() {

		if (isset($_POST['action']) && 
		($_POST['action'] == 'intro' || $_POST['action'] == 'addtour' || ($_POST['action'] == 'edittour' && isset($_POST['tour_id']) && $_POST['tour_id'] > 0))) {

			// Make global    
			global $datebook_form_error;

			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);
			}

			$update_data = array();

			$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );
			$profile_post = get_post($profile_id);

			if ($_POST['action'] == 'intro') {

				if (DateBook_Utilities::datebook_show_field('wishtravel', 1)) {
					if (isset($_POST['wishtravel']) && $_POST['wishtravel'] > 0) {

						$update_data['wishtravel'] = absint($_POST['wishtravel']);

					} else {

						$update_data['wishtravel'] = 0;
					}

					$update_data['wishtraveltext'] = DateBook_Utilities::datebook_word_filter(wp_trim_words(sanitize_text_field(wp_strip_all_tags($_POST['wishtraveltext'])), 500, ''));

				}

			} else if ($profile_post->post_author == $current_user_id || is_super_admin()) {
				// If any field is left empty, add the error message to the error object

				// instantiate the class
				$datebook_form_error = new WP_Error;

				$update_data['tour_id'] = (isset($_POST['tour_id']) && $_POST['tour_id'] > 0) ? $_POST['tour_id'] : 0;

				if ($_POST['title']) {
					$update_data['title'] = wp_trim_words(sanitize_text_field(wp_strip_all_tags($_POST['title'])), 200, '');
				} else {
					$datebook_form_error->add( 'title', esc_html__( 'Write title for your tour', 'datebook' ), 'has-error' );
				}


				if (isset($_POST['city']) && $_POST['city'] > 0) {

					$update_data['city'] = $_POST['city'];
					$update_data['region'] = $_POST['region'];
					$update_data['country'] = $_POST['country'];

				} else {

					$datebook_form_error->add( 'city', esc_html__( 'Select your city', 'datebook' ), 'has-error' );
					unset($_POST['city']);
				}


				if ($_POST['start']) {
					$start = preg_replace("/([^0-9\/])/", '', sanitize_text_field($_POST['start']));
					$start = explode("/", $start);
					if (count($start) != 3) {
						$datebook_form_error->add( 'start', esc_html__( 'The start date seems to be wrong', 'datebook' ), 'has-error' );
						unset($_POST['start']);
					}
					$update_data['start'] = mktime(0, 0, 0, $start[1], $start[0], $start[2]);
				} else {
					$datebook_form_error->add( 'start', esc_html__( 'You have to select a start date for the tour', 'datebook' ), 'has-error' );
				}
			
			
				if ($_POST['end']) {
					$end = preg_replace("/([^0-9\/])/", '', sanitize_text_field($_POST['end']));
					$end = explode("/", $end);
					if (count($end) != 3) {
						$datebook_form_error->add( 'end', esc_html__( 'The end date seems to be wrong', 'datebook' ), 'has-error' );
						unset($_POST['end']);
					}
					$update_data['end'] = mktime(23, 59, 59, $end[1], $end[0], $end[2]);
				} else {
					$datebook_form_error->add( 'end', esc_html__( 'You have to select the end date for the tour', 'datebook' ), 'has-error' );
				}

				if ($_POST['start'] && $_POST['end']) {
					if ($update_data['start'] > $update_data['end']) {
						$datebook_form_error->add( 'end', esc_html__( 'The end date must be after your start date', 'datebook' ), 'has-error' );
						unset($_POST['end']);
					}
				}

				$update_data['description'] = wp_trim_words(sanitize_text_field(wp_strip_all_tags($_POST['description'])), 2000, '');
			
			}

			return $update_data;

		}
	}


	/**
	 * Update all data
	 *
	 * @access private
	 * @return void
	 */
	private static function datebook_update_data() {

		global $datebook_form_error, $datebook_alert_error, $datebook_alert_text;

		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);
		}

		$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );
		$profile_post = get_post($profile_id);
		$profile_name = $profile_post->post_title;

		if ($_POST['action'] == 'intro') {

			// Validate the tour intro text
			$get_profile_data = self::datebook_validate_form();

			$datebook_get_data = get_post_meta($profile_id, 'profile_personal_data', true);
			
			$datebook_get_data['wishtravel'] = $get_profile_data['wishtravel'];
			$datebook_get_data['wishtraveltext'] = $get_profile_data['wishtraveltext'];

			// Update the post meta
			update_post_meta($profile_id, 'profile_personal_data', $datebook_get_data);
			
		// If any field is left empty, add the error message to the error object
		} else if ($profile_post->post_author == $current_user_id || is_super_admin()) {

			$options = array();

			// Check if profile is active otherwise do not allow to post a classified
			if ($profile_post->post_status == 'publish'){

				// validate the tour form input
				$datebook_get_data = self::datebook_validate_form();

				$datebook_get_data['tour_id'] = (isset($datebook_get_data['tour_id']) && $datebook_get_data['tour_id'] > 0) ? $datebook_get_data['tour_id'] : 0;
				$tour = get_post($datebook_get_data['tour_id']);
				// If any field is left empty, add the error message to the error object
				if (isset($datebook_get_data['tour_id']) && $datebook_get_data['tour_id'] > 0 && isset($tour->post_author) && $tour->post_author != $current_user_id) {

					$options = array('status' => 'alert alert-danger', 'message' => esc_html__( 'You are not allowed to edit this classified', 'datebook' ));

					// display alert message
					echo DateBook_Template_Loader::load( 'misc/alert', $options );

				} else {

					// Ensure WP_Error object ($datebook_form_error) contains no error
					if ( 1 > count( $datebook_form_error->get_error_messages() ) ) {

						$datebook_field_titles = get_query_var( 'datebook_field_titles' );
						if ( is_array( $datebook_field_titles ) ) { extract($datebook_field_titles); }
						
						$datebook_get_data['title'] = DateBook_Utilities::datebook_word_filter($datebook_get_data['title']);
						$datebook_get_data['description'] = DateBook_Utilities::datebook_word_filter($datebook_get_data['description']);

						if (isset($datebook_get_data['tour_id']) && $datebook_get_data['tour_id'] > 0) {
							
							// Approve edited tour automatically
							$approve_post = self::$datebook_options['approve_edited_tours'] ? 'publish' : 'private';

							// Update tour
							$tour_profile = array(
								'ID' => $datebook_get_data['tour_id'],
								'post_title' => $datebook_get_data['title'],
								'post_content' => $datebook_get_data['description'],
								'post_status' => $approve_post,
							);
							wp_update_post( $tour_profile );
							$tour_profile_id = $datebook_get_data['tour_id'];

						} else {
							
							// Approve newly submitted tour automatically
							$approve_post = self::$datebook_options['approve_new_tours'] ? 'publish' : 'private';

							// Insert tour
							$tour_profile = array(
								'post_title' => $datebook_get_data['title'],
								'post_content' => $datebook_get_data['description'],
								'post_status' => $approve_post,
								'post_author' => $current_user_id,
								'post_type' => DATEBOOK_TOUR_TYPE,
								'ping_status' => 'closed'
							);
							$tour_profile_id = wp_insert_post( $tour_profile );
						}

						$profile_get_permalink = get_permalink($tour_profile_id);

						$approval = array('title' => '', 'message' => '', 'class' => 'alert alert-success');

						if($approve_post == 'private'){

							$approval = array('title' => esc_html__('Tour review pending', 'datebook' ), 'message' => esc_html__(' and is waiting for approval', 'datebook' ), 'class' => 'alert alert-warning');

						}

						// Update location
						if($approve_post == 'publish'){

							global $wpdb;

							$table_countries = strtolower($wpdb->prefix) . 'datebook_countries';

							if(isset($datebook_get_data['city']) && $datebook_get_data['city'] > 0){

								$get_profile_city = get_post_meta($tour_profile_id, 'city', true);

								// compare if user set a new country then update counter in countries table
								if(isset($get_profile_city) && $get_profile_city != $datebook_get_data['city']){
									
									// increment counts in counter in city
									$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET tour_counter = tour_counter + 1 WHERE id = %d", $datebook_get_data['city']) );
									// decrement counts in counter in country
									$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET tour_counter = tour_counter - 1 WHERE id = %d", $get_profile_city) );

								} else {
									// increment counts in counter in city
									$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET tour_counter = tour_counter + 1 WHERE id = %d", $datebook_get_data['city']) );
								}

								update_post_meta($tour_profile_id, 'city', absint($datebook_get_data['city']));

							}

							if(isset($datebook_get_data['region']) && $datebook_get_data['region'] > 0){

								$get_profile_region = get_post_meta($tour_profile_id, 'region', true);

								// compare if user set a new country then update counter in countries table
								if(isset($get_profile_region) && $get_profile_region != $datebook_get_data['region']){

									// increment counts in counter in region
									$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET tour_counter = tour_counter + 1 WHERE id = %d", $datebook_get_data['region']) );
									// decrement counts in counter in country
									$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET tour_counter = tour_counter - 1 WHERE id = %d", $get_profile_region) );

								} else {
									// increment counts in counter in region
									$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET tour_counter = tour_counter + 1 WHERE id = %d", $datebook_get_data['region']) );
								}

								update_post_meta($tour_profile_id, 'region', absint($datebook_get_data['region']));

							}

							if(isset($datebook_get_data['country']) && $datebook_get_data['country'] > 0){

								$get_profile_country = get_post_meta($tour_profile_id, 'country', true);

								// compare if user set a new country then update counter in countries table
								if(isset($get_profile_country) && $get_profile_country != $datebook_get_data['country']){

									// increment counts in counter in country
									$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET tour_counter = tour_counter + 1 WHERE id = %d", $datebook_get_data['country']) );
									// decrement counts in counter in country
									$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET tour_counter = tour_counter - 1 WHERE id = %d", $get_profile_country) );

								} else {
									// increment counts in counter in country
									$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET tour_counter = tour_counter + 1 WHERE id = %d", $datebook_get_data['country']) );
								}

								update_post_meta($tour_profile_id, 'country', absint($datebook_get_data['country']));

							}

						}
						
						update_post_meta($tour_profile_id, 'country', $datebook_get_data['country']);
						update_post_meta($tour_profile_id, 'region', $datebook_get_data['region']);
						update_post_meta($tour_profile_id, 'city', $datebook_get_data['city']);
						update_post_meta($tour_profile_id, 'start', $datebook_get_data['start']);
						update_post_meta($tour_profile_id, 'end', $datebook_get_data['end']);

						update_post_meta($tour_profile_id, 'profile_tour_id', $profile_id);
						update_post_meta($tour_profile_id, 'tour_paid', '1');

						unset($datebook_get_data['country'], $datebook_get_data['region'], $datebook_get_data['city'], $datebook_get_data['start'], $datebook_get_data['end'], $datebook_get_data['description']);

						$_POST['action'] = '';

						if (isset($tour_profile_id) && $tour_profile_id > 0) {

							$options = array('status' => $approval['class'], 'message' => esc_html__( 'Tour has been updated', 'datebook' ) . $approval['message'], 'title' => $approval['title']);

							// display alert message
							echo DateBook_Template_Loader::load( 'misc/alert', $options );
							
							$select_email_template = 'tour_changed_to_admin';
							$subject_in_email = esc_html__('Tour has been edited by', 'datebook') . ': ' . $profile_name;

						} else {

							$options = array('status' => $approval['class'], 'message' => esc_html__( 'Tour has been added', 'datebook' ) . $approval['message'], 'title' => $approval['title']);

							// display alert message
							echo DateBook_Template_Loader::load( 'misc/alert', $options );
							
							$select_email_template = 'tour_added_to_admin';
							$subject_in_email = esc_html__('Tour has been added by', 'datebook') . ': ' . $profile_name;

						}
						

						// Let's send notification to administrator about tour update
						if(isset(self::$datebook_options['receive_email_on_tour_update']) && self::$datebook_options['receive_email_on_tour_update'] == '1'){

							$currentauth = get_userdata($current_user_id);
							$user_login = $currentauth->user_login;
							$emailaddress = $currentauth->user_email;

							include DateBook_Template_Loader::locate( 'misc/email-templates' );

							$send_to_this_email = self::$datebook_options['email_website'] ? self::$datebook_options['email_website'] : get_bloginfo('admin_email');

							$datebook_mail = DateBook_Utilities::datebook_email_send('', '', $send_to_this_email, $subject_in_email, $body);

						}

					} else {

						echo '<div class="alert alert-danger">' . esc_html__( 'Please, fill in all required fields colored red', 'datebook' ) . '</div>';

						$datebook_alert_error = array();
						$datebook_alert_text = array();

						foreach($datebook_form_error->get_error_codes() as $code){

							$datebook_alert_error[$code] = $datebook_form_error->get_error_data($code);
							$datebook_alert_text[$code] = $datebook_form_error->get_error_message($code);

						}
					}
				}

			} else {

				$options = array('status' => 'alert alert-danger', 'message' => esc_html__( 'You must first activate your profile in order to post a tour', 'datebook' ));

				// display alert message
				echo DateBook_Template_Loader::load( 'misc/alert', $options );

			}
		}
	}


	/**
	 * Show tour edit form and process all data
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_process_edit_tour() {

		if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['tour_id']) && $_GET['tour_id'] > 0) {

			// Delete tour
			self::datebook_delete_tour();

		}


		if (isset($_POST['action']) && 
		($_POST['action'] == 'intro' || $_POST['action'] == 'addtour' || ($_POST['action'] == 'edittour' && isset($_POST['tour_id']) && $_POST['tour_id'] > 0))) {

			// update all the input data
			self::datebook_update_data();

    	}


		if (
		(isset($_POST['action']) && $_POST['action'] == 'addtour') || 
		(isset($_GET['action']) && $_GET['action'] == 'newtour') || 
		(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edittour' && isset($_REQUEST['tour_id']) && $_REQUEST['tour_id'] > 0)) {

			// display the Tour form
			echo DateBook_Template_Loader::load( 'profile/profile-tours-form' );

		} else {

			global $datebook_field_titles;
			set_query_var( 'datebook_field_titles', $datebook_field_titles );
		
			// display the list of Tours
			echo DateBook_Template_Loader::load( 'profile/profile-tours' );

		}
		
	}


	/**
	 * Process ajax functions
	 *
	 * @access public
	 * @return void
	 */
	 public static function datebook_ajax_functions() {

		if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['tour_id']) && $_GET['tour_id'] > 0) {

			// Delete Tour
			$whatisit = isset( $_GET['whatisit'] ) ? esc_attr($_GET['whatisit']) : '';

			if ($whatisit == 'tourdelete') {

				self::datebook_delete_tour();

			}

			// Edit Tour
			if ($whatisit == 'touredit') {

				self::datebook_process_edit_tour();

			}

		}

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

			die();

		}

	}


	/**
	 * Process tour via ajax
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_process_ajax_tour() {
	
		if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
				
			// update all the input data
			add_action( 'wp_loaded', self::datebook_ajax_functions() );
			
		}
			
	}



}

//DateBook_Profile_Tours::init();
$dateBook_profile_tours = new DateBook_Profile_Tours($datebook_options_array);