<?php

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

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


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

		add_action( 'datebook_privacy_proccess', array( __CLASS__, 'datebook_proccess_register' ) );
		add_action( 'datebook_profile_privacy', array( __CLASS__, 'datebook_process_edit_privacy' ) );

	}


	/**
	 * Validate all input data
	 *
	 * @access private
	 */
	private static function datebook_validate_form() {
	
		if ( ! isset($_POST['action']) && $_POST['action'] != 'change') {
			return;
		}

		// Make global    
		global $current_user, $datebook_form_error;
		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);
		}

		$datebook_field_titles = get_query_var( 'datebook_field_titles' );
		if ( is_array( $datebook_field_titles ) ) { extract($datebook_field_titles); }

		$update_data = array();
		
		// instantiate the class
		$datebook_form_error = new WP_Error;

		$update_data['profile_id'] = get_user_meta( $current_user_id, 'profile_postid', true );

		$get_profile_data = get_post_meta($update_data['profile_id'], 'profile_personal_data', true);
		$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();


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


		if (of_get_option('registration_method') == 1) {
			
			$user = isset($current_user->user_login) && strlen($current_user->user_login) > 0 ? $current_user->user_login : '';
			
			if ( !is_user_logged_in() || (is_user_logged_in() && strlen($user) < 1)) {

				$update_data['user'] = isset($_POST['user']) && strlen($_POST['user']) > 0 ? preg_replace("/([^a-zA-Z0-9])/", '', sanitize_text_field($_POST['user'])) : '';
				
				if ($update_data['user']) {

					if (strlen($update_data['user']) < 4 || strlen($update_data['user']) > 30) {
						$datebook_form_error->add( 'user', esc_html__( 'Your username must be between 4 and 30 characters', 'datebook' ), 'has-error' );
					} else {
						if (username_exists($update_data['user'])) {
							$datebook_form_error->add( 'user', esc_html__( 'This username already exists. Please select another one', 'datebook' ), 'has-error' );
						}
					}

				} else {

					$datebook_form_error->add( 'user', esc_html__( 'Create your username', 'datebook' ), 'has-error' );

				}

			}
		}


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

			if (isset($_POST['currentpass'])) {

				$update_data['currentpass'] = sanitize_text_field($_POST['currentpass']);

				if ($update_data['currentpass']) {

					if (isset($current_user->user_pass) && strlen($current_user->user_pass) > 0 && ! wp_check_password( $update_data['currentpass'], $current_user->user_pass, $current_user_id ) ) {
						$datebook_form_error->add( 'currentpass', esc_html__( 'You have entered wrong current password', 'datebook' ), 'has-error' );
						unset($update_data['currentpass']);
					}

					$update_data['newpass'] = sanitize_text_field($_POST['newpass']);

					if (strlen($update_data['newpass']) < 4 || strlen($update_data['newpass']) > 100) {
						$datebook_form_error->add( 'newpass', esc_html__( 'Your password must be at least 4 characters', 'datebook' ), 'has-error' );
						unset($update_data['newpass']);
					} else if ( false !== strpos( stripslashes($update_data['newpass']), "\\" ) ) {
						$datebook_form_error->add( 'newpass', esc_html__( 'Password may not contain the character "\"', 'datebook' ), 'has-error' );
						unset($update_data['newpass']);
					}

				} else {

					if ($update_data['profile_id']) {
						$datebook_form_error->add( 'currentpass', esc_html__( 'Enter your current password in order to set a new password', 'datebook' ), 'has-error' );
					}
				}

			}

		} else {

			if (!is_user_logged_in()) {
				$datebook_form_error->add( 'newpass', esc_html__( 'Create a new password', 'datebook' ), 'has-error' );
			}
		}

		$update_data['datebook_who_can_see_my_profile'] = isset($_POST['datebook_who_can_see_my_profile']) ? sanitize_text_field($_POST['datebook_who_can_see_my_profile']) : '';

		$update_data['datebook_who_can_see_my_images'] = isset($_POST['datebook_who_can_see_my_images']) ? sanitize_text_field($_POST['datebook_who_can_see_my_images']) : '';

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

		return $update_data;

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

		global $datebook_get_data, $datebook_form_error, $datebook_alert_error, $datebook_alert_text;
		
		// validate the Profile form input
		$datebook_get_data = self::datebook_validate_form();

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

			// If user logged in then let's update his data
			if ($datebook_get_data['profile_id']) {

				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_user_args = array(
					'ID' => $current_user_id
				);

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

					$update_user_args['user_pass'] = $datebook_get_data['newpass'];

				}

				// Update profile
				wp_update_user($update_user_args);

				$get_profile_data = get_post_meta($datebook_get_data['profile_id'], 'profile_personal_data', true);
				$get_profile_data = !empty($get_profile_data) ? $get_profile_data : array();

				if (isset($datebook_get_data['datebook_deactivate_account']) && $datebook_get_data['datebook_deactivate_account'] > 0 || isset($datebook_get_data['datebook_delete_account']) && $datebook_get_data['datebook_delete_account'] > 0) {

					// If user deactivates his profile
					$datebook_publish_profile = 'private';

					$get_profile_data['datebook_deactivate_account'] = 1;

				} else {

					// If user activates his profile
					$datebook_publish_profile = 'publish';

					$get_profile_data['datebook_deactivate_account'] = 0;

				}


				$get_profile_data['datebook_delete_account'] = sanitize_text_field($datebook_get_data['datebook_delete_account']);

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

					$delete_profile_days = of_get_option('delete_profile_days') > 0 ? of_get_option('delete_profile_days') * 60 * 60 * 24 : 0;

					$get_profile_data['delete_profile_days'] = time() + $delete_profile_days;

					// Update the post meta
					update_post_meta($datebook_get_data['profile_id'], 'delete_profile_days', $get_profile_data['delete_profile_days']);

				} else {

					delete_post_meta($datebook_get_data['profile_id'], 'delete_profile_days');

				}


				// Update post
				$post_profile = array(
					'ID' => $datebook_get_data['profile_id'],
					'post_status' => $datebook_publish_profile,
				);

				wp_update_post( $post_profile );


				// Let's save or update only these data for search
				foreach($datebook_get_data as $key => $value) {

					// sanitize data in array
					if (is_array($value)) {
						$value = array_map( 'sanitize_text_field', $value );
					} else {
						$value = sanitize_text_field( $value );
					}

					//Alter the options array appropriately
					$get_profile_data[sanitize_key($key)] = $value;

				}

				// Update the post meta
				update_post_meta($datebook_get_data['profile_id'], 'profile_personal_data', $get_profile_data);

				// If no errors let's show success alert
				$datebook_alert_text['success_profile_updated'] = esc_html__( 'Privacy data have been updated', 'datebook' );

				// Send an email notification about profile deactivation to admin
				if (of_get_option('email_when_profile_deactivated_by_user') == '1' || of_get_option('email_when_profile_deleted_by_user') == '1') {
					
					$profile_get_permalink = get_permalink($datebook_get_data['profile_id']);

					// Email
					$to_email = of_get_option('email_website') ? of_get_option('email_website') : get_bloginfo('admin_email');

					// Message
					$body = esc_html__( 'Hello', 'datebook' ) . ', ' . esc_html__( 'Admin', 'datebook' ) . '!<br /><br />';

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

						// Subject
						$subject_in_email = esc_html__('User has deactivated his profile', 'datebook');
						$body .= esc_html__( 'User deactivated his profile manually', 'datebook' ) . '.<br />';

					} else if (isset($datebook_get_data['datebook_delete_account']) && $datebook_get_data['datebook_delete_account'] > 0) {

						// Subject
						$subject_in_email = esc_html__('User has deleted his profile', 'datebook');
						$body .= esc_html__( 'User deleted his profile manually', 'datebook' ) . '.<br />';

					}

					$body .= esc_html__( 'Profile', 'datebook' ).': <a href="' . $profile_get_permalink . '">' . $profile_get_permalink . '</a>';

					// Send email to admin
					$datebook_mail = DateBook_Utilities::datebook_email_send(NULL, NULL, $to_email, $subject_in_email, $body);

				}
			}

		} else {

			$datebook_alert_error = array();
			$datebook_alert_text = array();
			
			$datebook_alert_text['error_required_fields'] = esc_html__( 'Please, fill in all required fields colored red', 'datebook' );

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

			}

		}

	}


	/**
	 * Proccess registration data
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_proccess_register() {

		global $datebook_field_titles;
		set_query_var( 'datebook_field_titles', $datebook_field_titles );

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

			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_type = get_user_meta( $current_user_id, 'profile_type', true);
			$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );
			$profile_post = get_post($profile_id);
			$profile_post_author = isset($profile_post->post_author) && $profile_post->post_author > 0 ? $profile_post->post_author : 0;

			// If any field is left empty, add the error message to the error object
			if ($profile_post_author != $current_user_id && is_user_logged_in()) {

				echo '<div class="alert alert-danger">' . esc_html__( 'You are not allowed to edit this profile', 'datebook' ) . '</div>';

			} else {

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

			}

    	}

	}


	/**
	 * Show privacy form and process all data
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_process_edit_privacy() {
		
		// display the Account Privacy form
		echo DateBook_Template_Loader::load( 'profile/profile-privacy' );

	}


}

DateBook_Profile_Privacy::init();