<?php

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

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


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

		add_action( 'datebook_edit_photos', array( __CLASS__, 'datebook_process_edit_photos' ) );
		add_action( 'datebook_ajax_photos', array( __CLASS__, 'datebook_process_ajax_photos' ) );

	}


	/**
	 * Set default photo
	 *
	 * @access private
	 * @return void
	 */
	private static function datebook_set_default_photo() { 

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

		// Set Profile Default Photo
		$attachment_id = (int)$_GET['id'];
		if ($attachment_id == 0) { die(); }

		$post = get_post($attachment_id);
		$post_parent = get_post($post->post_parent);
		$author_id = $post_parent->post_author;

		if ($author_id == $current_user_id){

			$get_profile_data = get_post_meta($post_parent->ID, 'profile_personal_data', true);
			$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

			$datebook_get_data['profile_photo_id'] = $post->post_title;

			// Update the post meta
			update_post_meta($post_parent->ID, 'profile_personal_data', $datebook_get_data);
			update_post_meta($post_parent->ID, 'profile_photo_id', $datebook_get_data['profile_photo_id']);

			set_post_thumbnail($post_parent->ID, $post->ID);

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

		}
	}


	/**
	 * Upload photo
	 *
	 * @access private
	 * @return void
	 */
	private static function datebook_upload_photo() {

		if( isset( $_POST['datebook_image_upload'] ) && !empty( $_FILES['images'] )) {

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

			$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );
			
			if ($profile_id) {

				$datebook_post_image_upload = $_POST['datebook_image_upload'];

				$datebook_files_images = $_FILES['images'];

				// Mark this action as Profile Photos
				$datebook_photo_type = DATEBOOK_PROFILE_IMAGE_TYPE;

				// Define which image formats to be created
				$datebook_photo_formats = array(
					'image_big'				=> array('crop' => false, 'watermark' => true), 
					'image_profile'			=> array('crop' => true, 'watermark' => true), 
					'image_square_medium'	=> array('crop' => true, 'watermark' => false), 
					'image_front_medium'	=> array('crop' => true, 'watermark' => false), 
					'image_front_small'		=> array('crop' => true, 'watermark' => false), 
					'image_mini'			=> array('crop' => true, 'watermark' => false)
				);

				// Set up Default image to show after upload
				$default_thumbnail_show = array('format' => 'image_square_medium', 'crop' => true, 'watermark' => false);

				$image_result_array = DateBook_Utilities::process_upload_photo($datebook_post_image_upload, $datebook_files_images, $datebook_photo_type, $datebook_photo_formats, $profile_id, $default_thumbnail_show, $current_user_id);

				// Add this meta for moderator to know that this image uploaded recently
				if(isset($image_result_array['imgid'])){
					update_post_meta($image_result_array['imgid'], 'new', '1');
				}
				
				$datebook_get_data = isset($image_result_array['datebook_get_data']) && !empty($image_result_array['datebook_get_data']) ? $image_result_array['datebook_get_data'] : array();

				if(isset($datebook_get_data['profile_photo_id']) && $datebook_get_data['profile_photo_id'] != '' && of_get_option('user_must_upload_photo') == '1'){
					// If profile is private and needs to be manually activated by an admin
					$notactive = get_post_meta($profile_id, 'notactive', true);

					if ($notactive == 0) {

						// 2. Check a profile completed
						$profile_must_complete = 1;
						if(of_get_option('user_must_complete_profile') == '1'){
							$profile_must_complete = isset($datebook_get_data['profile_must_complete']) && $datebook_get_data['profile_must_complete'] == 1 ? 1 : 0;
						}

						// Check if Payment and Subscription are activated
						$plans_count = 0;

						if (DateBook_Utilities::check_if_gateway_activated()) {

							// 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++;

									}
								}
							}
						}

						// Check if user has a subscription
						$get_subsciption_status = DateBook_Profile_Subscription::get_subsciption_status($current_user_id);

						if ($plans_count > 0){

							if (isset($get_subsciption_status) && $get_subsciption_status == 'active'){

								// If subscription plan exists then publish profile
								$post_status = 'publish';

							} else {

								// If subscription plan does not exist then do not publish profile
								$post_status = 'private';

							}

						} else {

							// If subscription plan does not exist then publish profile
							$post_status = 'publish';

						}

						if ($profile_must_complete == 1 && $post_status == 'publish'){

							// Update post
							$profile_details = array(
								'ID' => $profile_id,
								'post_status' => 'publish'
							);
							wp_update_post( $profile_details );

						}
					}
				}

				echo wp_send_json($image_result_array);

			}
		}
	}


	/**
	 * Delete profile photo
	 *
	 * @access private
	 * @return void
	 */
	private static function datebook_delete_photo() { 

		// Delete Profile Images
		$attachment_id = (int)$_GET['id'];
		if ($attachment_id == 0) { die(); }

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

		$post = get_post($attachment_id);
		$post_parent = get_post($post->post_parent);
		$profile_id = $post_parent->ID;
		$author_id = $post_parent->post_author;

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

			// Get personal data
			$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
			$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

			$upload_folder = isset($datebook_get_data['upload_folder']) ? $datebook_get_data['upload_folder'] : '';

			// Delete all selected images
			$prohibit_images_delete = of_get_option('prohibit_images_delete');
			$prohibit_image = $prohibit_images_delete[1] == 1 ? 1 : 0;

			if ($prohibit_image == 1){

				// Update post
				$post_details = array(
					'ID' => $post->ID,
					'post_status' => 'private'
				);

				wp_update_post($post_details);

			} else if ($prohibit_image == 0){

				DateBook_Utilities::datebook_delete_all_photos($upload_folder, $post->post_title);

				wp_delete_attachment( $post->ID, $force_delete = true );

			}

			$profile_photo_id = isset($datebook_get_data['profile_photo_id']) ? $datebook_get_data['profile_photo_id'] : '';
			$profile_photo_parse = explode('/', $profile_photo_id);
			$profile_photo_id_array = count($profile_photo_parse) > 1 ? $profile_photo_parse[1] : $profile_photo_parse[0];

			// After deleting Default image let set a new default image
			if ($post->post_title == $profile_photo_id_array) {

				global $wpdb;

				$new_photo_array = $wpdb->get_var($wpdb->prepare("SELECT `ID`, `post_title` FROM {$wpdb->posts} WHERE `post_parent` = %d AND `post_type`='attachment' ORDER BY `ID` ASC LIMIT 1", $profile_id));

				if (isset($new_photo_array) && !empty($new_photo_array)) {

					$datebook_get_data['profile_photo_id'] = isset($new_photo_array->post_title) ? $new_photo_array->post_title : '';
					// Update the post meta
					update_post_meta($profile_id, 'profile_personal_data', $datebook_get_data);
					update_post_meta($profile_id, 'profile_photo_id', $datebook_get_data['profile_photo_id']);

					if(isset($new_photo_array->ID) && $new_photo_array->ID > 0){
						set_post_thumbnail($profile_id, $new_photo_array->ID);
					}

				} else {

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

					
					if(of_get_option('user_must_upload_photo') == '1'){
						// Update post
						$profile_details = array(
							'ID' => $profile_id,
							'post_status' => 'private'
						);
						wp_update_post( $profile_details );

					}
				}
			}



			$data = array();
			$data['successtext'] = '<div class="alert alert-success">' . esc_html__( 'Image has been deleted', 'datebook' ) . '</div>';
			$data['imgid'] = $post->ID;


			// Show result by JSON
			echo json_encode($data);

			exit;

		}

	}


	/**
	 * Rotate photo process
	 *
	 * @access private
	 * @return void
	 */
	public static function process_rotate_photo($attachment_id, $rotation_degree, $datebook_photo_type, $datebook_photo_formats, $profile_id, $default_thumbnail_show, $current_user_id) {

		if( isset($attachment_id) && isset( $rotation_degree )) {
			
			$postvals = array();

			if ($profile_id) {

				global $datebook_image_sizes;
				
				// Get personal data
				$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
				$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

				$upload_folder = isset($datebook_get_data['upload_folder']) ? $datebook_get_data['upload_folder'] : '';

				if (!$upload_folder) {

					$upload_folder = $datebook_get_data['upload_folder'] = time().rand(1,999);

				}

				$upload_dir = wp_upload_dir();

				$targetURL = $upload_dir['baseurl'] . '/' . $upload_folder;
				$targetPath = $upload_dir['basedir'] . '/' . $upload_folder;

				if ( ! file_exists( $targetPath ) ) {

					wp_mkdir_p( $targetPath );

				}

				if(!function_exists('wp_handle_upload')){
		        	include_once(ABSPATH . 'wp-admin/includes/file.php');
		    	}
				include_once(ABSPATH . 'wp-admin/includes/image.php');


				// remove it
				function remove_image_sizes($sizes){

					unset( $sizes['thumbnail']);
					unset( $sizes['medium']);
					unset( $sizes['large']);
					unset( $sizes['datebook-featured']);
					unset( $sizes['medium_large']);

					return $sizes;

				}

				add_filter('intermediate_image_sizes_advanced', 'remove_image_sizes' );
				add_filter('image_size_names_choose', 'remove_image_sizes' );


				// Generate new file name
				$file = get_attached_file($attachment_id);
				$path = pathinfo($file); // dirname = File Path; basename = Filename.Extension; extension = Extension; filename = Filename

				$newfilename = time().rand(1, 999);
				$newfile_URI = $path['dirname'] . '/' . $newfilename . '.' . $path['extension'];

				rename($file, $newfile_URI);

				//update_attached_file( $new_attachment_id, $newfile_URI );

				$attachment = array(
					'post_mime_type' => 'image/jpeg',
					'guid' => $targetURL . '/' . $newfilename . '.' . $path['extension'],
					'post_status ' => 'inherit',
					'post_parent' => $profile_id,
					'post_title' => $newfilename . '.' . $path['extension'],
					'post_type' => 'attachment'
				);
				$path_to_original_file = $path['dirname'] . '/' . $newfilename . '.' . $path['extension'];

				// Save the attachment metadata
				$new_attachment_id = wp_insert_attachment($attachment, $path_to_original_file, $profile_id);
				$attach_data = wp_generate_attachment_metadata( $new_attachment_id, $path_to_original_file );
				wp_update_attachment_metadata( $new_attachment_id, $attach_data );

				// Add what type of photo we uploaded. We will need this information later
				update_post_meta($new_attachment_id, DATEBOOK_IMAGE_TYPE, DATEBOOK_PROFILE_IMAGE_TYPE);

				$get_new_image = get_post_meta($attachment_id, 'new', true);
				if(isset($get_new_image) && $get_new_image == 1){
					update_post_meta($new_attachment_id, 'new', '1');
				}
				
				// Delete old images
				$post = get_post($attachment_id);
				DateBook_Utilities::datebook_delete_all_photos($upload_folder, $post->post_title);
				wp_delete_attachment( $attachment_id, $force_delete = true );

				if($datebook_get_data['profile_photo_id'] == $path['basename']){
					$datebook_get_data['profile_photo_id'] = $newfilename . '.' . $path['extension'];
					// Update the post meta
					update_post_meta($profile_id, 'profile_photo_id', $datebook_get_data['profile_photo_id']);
					update_post_meta($profile_id, 'profile_personal_data', $datebook_get_data);
				}


				$attach = wp_get_attachment_image_src($new_attachment_id);
				
				if(isset($attach[0])) {

					$enable_retina_images = of_get_option('enable_retina_images') == '1' ? 1 : 0;

					$blur_variant = of_get_option('blur_variant') ? of_get_option('blur_variant') : 0;

					$targetFile = basename($attach[0]);
					$explode_picName = explode('.', $targetFile);
					$generate_picName = $explode_picName[0];

					$filename = $targetPath . '/' . $targetFile;

					//$exif = exif_read_data( $filename );
					//if ( isset( $exif ) && isset( $exif['Orientation'] ) && $exif['Orientation'] > 1 ) {

						// Need it so that image editors are available to us.
						include_once ABSPATH . 'wp-admin/includes/image-edit.php';

					//}


					add_filter( 'wp_image_editors', function( $editors ) {
						require_once DATEBOOK_DIR . 'includes/class-datebook-watermark.php';
						if ( ! is_array( $editors ) ) return $editors; //someone broke the filtered value

						array_unshift( $editors, 'DateBook_Watermark');
						return $editors;
					});

					$rotation_degree = -$rotation_degree;

					// Let's create images of defined formats only
					foreach($datebook_photo_formats as $format => $actions) {

						$thumb_width = $datebook_image_sizes[$format]['width'];
						$thumb_height = $datebook_image_sizes[$format]['height'];

						// Create this format image
						$different_thumbnail = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height']) . '.jpg';//$extension;
						$different_thumbnail_blur = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height'] . '-blur') . '.jpg';//$extension;
						//if (!file_exists($targetPath . '/' . $different_thumbnail)) {

							$image = wp_get_image_editor($filename);
							if ( ! is_wp_error( $image ) ) {

								// Lets rotate and flip the image based on exif orientation.
								$image->rotate($rotation_degree);
								/*if ( false !== $operations['flipper'] ) {
									$image->flip( $operations['flipper'][0], $operations['flipper'][1] );
								}*/
								
								$image->resize($datebook_image_sizes[$format]['width'], $datebook_image_sizes[$format]['height'], $actions['crop']);
								if($actions['watermark']){
									$image->add_watermark($datebook_image_sizes[$format]['width'], $datebook_image_sizes[$format]['height']);
								}
								$image->save($targetPath . '/' . $different_thumbnail);

								// Create and blur a new image
								if($blur_variant > 0){
									$image->save($targetPath . '/' . $different_thumbnail_blur);
									$image->add_blur($targetPath . '/' . $different_thumbnail_blur);
								}
							}
						//}

						// Create Retina images
						if($enable_retina_images == 1){

							// Get size of original image
							list($orig_thumb_width, $orig_thumb_height) = getimagesize($filename);

							// Create retina 2x size
							$retina_thumbnail_url = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height']) . '@2x.jpg';
							$retina_thumbnail_url_blur = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height'] . '-blur') . '@2x.jpg';

							//if (!file_exists($targetPath . '/' . $retina_thumbnail_url)){
								$image = wp_get_image_editor($filename);
								if (!is_wp_error($image)){
									$thumb_width = $datebook_image_sizes[$format]['width'] * 2;
									$thumb_height = $datebook_image_sizes[$format]['height'] * 2;

									// Compare original image to retina sizes
									$thumb_width = $orig_thumb_width < $thumb_width ? $orig_thumb_width : $thumb_width;
									$thumb_height = $orig_thumb_height < $thumb_height ? $orig_thumb_height : $thumb_height;

									// Lets rotate and flip the image based on exif orientation.
									$image->rotate($rotation_degree);
									/*if ( false !== $operations['flipper'] ) {
										$image->flip( $operations['flipper'][0], $operations['flipper'][1] );
									}*/
									$image->resize($thumb_width, $thumb_height, $actions['crop']);
									$image->save($targetPath . '/' . $retina_thumbnail_url);

									// Create and blur a new image
									if($blur_variant > 0){
										$image->save($targetPath . '/' . $retina_thumbnail_url_blur);
										$image->add_blur($targetPath . '/' . $retina_thumbnail_url_blur);
									}
								}
							//}

							// Create retina 1.5x size
							$retina_thumbnail_url_15 = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height']) . '@1.5x.jpg';
							$retina_thumbnail_url_blur_15 = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height'] . '-blur') . '@1.5x.jpg';

							//if (!file_exists($targetPath . '/' . $retina_thumbnail_url_15)){
								$image = wp_get_image_editor($filename);
								if (!is_wp_error($image)){

									$percentage = 50;
									$thumb_width = round(($percentage / 100) * $datebook_image_sizes[$format]['width'] + $datebook_image_sizes[$format]['width']);
									$thumb_height = round(($percentage / 100) * $datebook_image_sizes[$format]['height'] + $datebook_image_sizes[$format]['height']);

									// Compare original image to retina sizes
									$thumb_width = $orig_thumb_width < $thumb_width ? $orig_thumb_width : $thumb_width;
									$thumb_height = $orig_thumb_height < $thumb_height ? $orig_thumb_height : $thumb_height;

									// Lets rotate and flip the image based on exif orientation.
									$image->rotate($rotation_degree);
									/*if ( false !== $operations['flipper'] ) {
										$image->flip( $operations['flipper'][0], $operations['flipper'][1] );
									}*/

									$image->resize($thumb_width, $thumb_height, $actions['crop']);
									$image->save($targetPath . '/' . $retina_thumbnail_url_15);

									// Create and blur a new image
									if($blur_variant > 0){
										$image->save($targetPath . '/' . $retina_thumbnail_url_blur_15);
										$image->add_blur($targetPath . '/' . $retina_thumbnail_url_blur_15);
									}
								}
							//}

							// Create retina 1.25x size
							$retina_thumbnail_url_125 = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height']) . '@1.25x.jpg';
							$retina_thumbnail_url_blur_125 = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height'] . '-blur') . '@1.25x.jpg';

							//if (!file_exists($targetPath . '/' . $retina_thumbnail_url_125)){
								$image = wp_get_image_editor($filename);
								if (!is_wp_error($image)){

									$percentage = 25;
									$thumb_width = round(($percentage / 100) * $datebook_image_sizes[$format]['width'] + $datebook_image_sizes[$format]['width']);
									$thumb_height = round(($percentage / 100) * $datebook_image_sizes[$format]['height'] + $datebook_image_sizes[$format]['height']);

									// Compare original image to retina sizes
									$thumb_width = $orig_thumb_width < $thumb_width ? $orig_thumb_width : $thumb_width;
									$thumb_height = $orig_thumb_height < $thumb_height ? $orig_thumb_height : $thumb_height;

									// Lets rotate and flip the image based on exif orientation.
									$image->rotate($rotation_degree);
									/*if ( false !== $operations['flipper'] ) {
										$image->flip( $operations['flipper'][0], $operations['flipper'][1] );
									}*/

									$image->resize($thumb_width, $thumb_height, $actions['crop']);
									$image->save($targetPath . '/' . $retina_thumbnail_url_125);

									// Create and blur a new image
									if($blur_variant > 0){
										$image->save($targetPath . '/' . $retina_thumbnail_url_blur_125);
										$image->add_blur($targetPath . '/' . $retina_thumbnail_url_blur_125);
									}
								}
							//}
						}
					}

					// Retrieve default image to show after uploading
					$thumbnail_url = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$default_thumbnail_show['format']]['width'] . 'x' . $datebook_image_sizes[$default_thumbnail_show['format']]['height']) . '.jpg';//$extension;
					$thumbnail_url_blur = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$default_thumbnail_show['format']]['width'] . 'x' . $datebook_image_sizes[$default_thumbnail_show['format']]['height'] . '-blur') . '.jpg';//$extension;
					//if (!file_exists($targetPath . '/' . $thumbnail_url)) {

						$image = wp_get_image_editor($filename);
						if ( ! is_wp_error( $image ) ) {
							
							// Lets rotate and flip the image based on exif orientation.
							$image->rotate($rotation_degree);
							/*if ( false !== $operations['flipper'] ) {
								$image->flip( $operations['flipper'][0], $operations['flipper'][1] );
							}*/

							$image->resize($datebook_image_sizes[$default_thumbnail_show['format']]['width'], $datebook_image_sizes[$default_thumbnail_show['format']]['height'], $default_thumbnail_show['crop']);

							if($default_thumbnail_show['watermark']){
								$image->add_watermark($datebook_image_sizes[$default_thumbnail_show['format']]['width'], $datebook_image_sizes[$default_thumbnail_show['format']]['height']);
							}
							$image->save($targetPath . '/' . $thumbnail_url);

							// Create and blur a new image
							if($blur_variant > 0){
								$image->save($targetPath . '/' . $thumbnail_url_blur);
								$image->add_blur($targetPath . '/' . $thumbnail_url_blur);
							}
						}
					//}

					list($width, $height, $type, $attr) = getimagesize($targetPath . '/' . $thumbnail_url);

					// Retrieve big image to show after uploading
					$big_thumbnail_url = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes['image_big']['width'] . 'x' . $datebook_image_sizes['image_big']['height']) . '.jpg';//$extension;
					$big_thumbnail_url_blur = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes['image_big']['width'] . 'x' . $datebook_image_sizes['image_big']['height'] . '-blur') . '.jpg';//$extension;
					//if (!file_exists($targetPath . '/' . $big_thumbnail_url)) {

						$image = wp_get_image_editor($filename);
						if ( ! is_wp_error( $image ) ) {

							// Lets rotate and flip the image based on exif orientation.
							$image->rotate($rotation_degree);
							/*if ( false !== $operations['flipper'] ) {
								$image->flip( $operations['flipper'][0], $operations['flipper'][1] );
							}*/

							$image->resize($datebook_image_sizes['image_big']['width'], $datebook_image_sizes['image_big']['height'], false);
							$image->add_watermark($datebook_image_sizes['image_big']['width'], $datebook_image_sizes['image_big']['height']);
							$image->save($targetPath . '/' . $big_thumbnail_url);

							// Create and blur a new image
							if($blur_variant > 0){
								$image->save($targetPath . '/' . $big_thumbnail_url_blur);
								$image->add_blur($targetPath . '/' . $big_thumbnail_url_blur);
							}
						}
					//}

					// Rotate Original image
					if (file_exists($filename)) {

						$image = wp_get_image_editor($filename);
						if ( ! is_wp_error( $image ) ) {

							// Lets rotate and flip the image based on exif orientation.
							$image->rotate($rotation_degree);
							/*if ( false !== $operations['flipper'] ) {
								$image->flip( $operations['flipper'][0], $operations['flipper'][1] );
							}*/

							$image->save($filename);

						}
					}
					
					$postvals['success'] = 1; // 1 - success, 0 - error
					$postvals['imgid'] = $attachment_id;
					$postvals['newimgid'] = $new_attachment_id;
					$postvals['imgbig'] = $targetURL . '/' . $big_thumbnail_url;
					$postvals['imgurl'] = $targetURL . '/' . $thumbnail_url;

					$postvals['width'] = $width;
					$postvals['height'] = $height;

					$postvals['successtext'] = '<div class="alert alert-success">'. esc_html__( 'Image has been rotated!', 'datebook' ).'</div>';

				} else {

					$postvals['success'] = 0; // 1 - success, 0 - error
					$postvals['imgid'] = '';
					$postvals['newimgid'] = '';
					$postvals['imgbig'] = '';
					$postvals['imgurl'] = '';
					$postvals['width'] = '';
					$postvals['height'] = '';
					$postvals['successtext'] = '<div class="alert alert-warning">' . esc_html__( 'Oops! Something went wrong. Image could not be rotated.', 'datebook' ) . '</div>';

				}

			} else {

				$postvals['success'] = 0; // 1 - success, 0 - error
				$postvals['imgid'] = '';
				$postvals['newimgid'] = '';
				$postvals['imgbig'] = '';
				$postvals['imgurl'] = '';
				$postvals['width'] = '';
				$postvals['height'] = '';
				$postvals['successtext'] = '<div class="alert alert-warning">' . esc_html__( 'Oops! Something went wrong. We cannot detect your profile ID', 'datebook' ) . '</div>';

			}

			return $postvals;

		}
	}


	/**
	 * Rotate photo
	 *
	 * @access private
	 * @return void
	 */
	private static function rotate_photo() {

		if( isset( $_GET['id'] )) {

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

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

			if ($profile_id) {

				$attachment_id = $_GET['id'];

				$rotation_degree = $_GET['rotation_degree'];

				// Mark this action as Profile Photos
				$datebook_photo_type = DATEBOOK_PROFILE_IMAGE_TYPE;

				// Define which image formats to be created
				$datebook_photo_formats = array(
					'image_mini'			=> array('crop' => true, 'watermark' => false),
					'image_small'			=> array('crop' => true, 'watermark' => false),
					'image_medium'			=> array('crop' => true, 'watermark' => false),
					'image_square_small'	=> array('crop' => true, 'watermark' => false),
					'image_square_medium'	=> array('crop' => true, 'watermark' => false),
					'image_feature'			=> array('crop' => true, 'watermark' => true),
					'image_front_small'		=> array('crop' => true, 'watermark' => false),
					'image_front_medium'	=> array('crop' => true, 'watermark' => false), 
					'image_front_feature'	=> array('crop' => true, 'watermark' => false),
					'image_profile'			=> array('crop' => true, 'watermark' => true),
					'image_big'				=> array('crop' => false, 'watermark' => true)
				);

				// Set up Default image to show after upload
				$default_thumbnail_show = array('format' => 'image_square_medium', 'crop' => true, 'watermark' => false);

				$image_result_array = self::process_rotate_photo($attachment_id, $rotation_degree, $datebook_photo_type, $datebook_photo_formats, $profile_id, $default_thumbnail_show, $current_user_id);

				echo wp_send_json($image_result_array);

			}
		}
	}


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

		if( isset($_GET['action']) &&  $_GET['action'] == 'datebook_ajax_actions' ) {

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

			if ($whatisit == 'imagedelete') {

				// Delete profile images
				self::datebook_delete_photo();

			} else if ($whatisit == 'defaultimage') {

				// Set default profile image
				self::datebook_set_default_photo();

			} else if ($whatisit == 'rotation') {

				// Set default profile image
				self::rotate_photo();

			}

		}

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

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

		}

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

			die();

		}

	}


	/**
	 * Process photos via ajax
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_process_ajax_photos() {

		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() );
				
		} else {
				
			// update all the input data
			self::datebook_upload_photo();
				
		}
	
	}


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

		self::datebook_process_ajax_photos();
     
	    // display the Edit Profile form
		echo DateBook_Template_Loader::load( 'profile/profile-photos-form' );

	}


}

DateBook_Profile_Photos::init();