<?php
/**
* Roman P. 
* Mobile requests handler all methods exiting with die
*/
class Mobile extends Controller{
	/**
	* Construct this object by extending the basic Controller class
	*/
	// private $_login_model;
	function __construct(){
		parent::__construct();
		// $this->_login_model = $this->loadModel('login_model');
		// $this->_login_model = new login_m();
		// Language::load();
		$this->loadModel('mobile');
	}

	/**
	* In Box requests requiring users ID & UID & optionally page id,
	* will return any conversation & page number & total found conversations if such exists to user 
	*/
	public function inbox(){
		$user_id = @filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
		$user_uid = @filter_var($_POST['user_uid'], FILTER_SANITIZE_STRING);
		/* simple check for emptiness and length */ 
		if(!empty($user_id) AND !empty($user_uid)){
			/* Simple check if request is came from mobile device */
			$valid = $this->_model->get_UserValid($user_id,$user_uid);
			//error_log(" inbox user approved");
			if($valid){
				$pageId = (int)@filter_var($_POST['page_id'], FILTER_SANITIZE_NUMBER_INT);
				/* If page is not specified set it to 0, i presume the page is first time requested */
				if(empty($pageId))
					$pageId = "0";
				$convs = $this->_model->get_UserConvs($pageId,DISPLAY_USERS,$user_id);
				$userConvs['s'] = 0;
				/* Check if the user has any conversations at all, may be he first time on site :) */
				if($convs){
					$userConvs['s'] = 1;
					$userConvs["page_id"] = $pageId;
					$userConvs["total_found"] = $convs["add"][0]->total_found;
					$userConvs["users"] = $convs["usr"];
				/* User don't have any conversations */
				}else{
					$userConvs["error"] = 1;
					$userConvs["error_msg"] = "NO_CONVERSATIONS";
				}
				echo json_encode($userConvs,JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_NUMERIC_CHECK);
				die();
			}
			else
				die();
		}
		die();
	}

	/**
	* Posting new message to DB 
	* Sender, receiver and message content 
	*/
	public function msg_send(){
		$user_id = @filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
		$user_uid = @filter_var($_POST['user_uid'], FILTER_SANITIZE_STRING);
		/* simple check for emptiness and length */ 
		if(!empty($user_id) AND !empty($user_uid)){
			/* Simple check if request is came from mobile device */
			$valid = $this->_model->get_UserValid($user_id,$user_uid);
			if($valid){
				$convs = false;
				/* Target message user */
				$user_two = @filter_var($_POST['user_two'], FILTER_SANITIZE_NUMBER_INT);
				/* Message content */
				$msg = @filter_var($_POST['msg'], FILTER_SANITIZE_STRING);
				if(!empty($msg) AND !empty($user_two)){
					/* New message delivered by user, try update DB */
					$convs = $this->_model->set_ConvMsg($user_id,$user_two,$msg);
				}
				/* Set default return as failed, will not return anything else because i don't want to "stress" the user */
				$userConvs['s'] = 0;
				/* Check if the user has any conversations at all, may be he first time on site :) */
				if($convs){
					$userConvs['s'] = 1;
					/* Check if limit is came along with the request */
					$con_from_id = @filter_var($_POST['con_id'], FILTER_SANITIZE_NUMBER_INT);
					$userConvs["users"] = $this->_model->get_ConvNew($user_id,$user_two,$con_from_id);
				
				}/* User don't have any conversations */
				// else{
					// $userConvs["error"] = 1;
					// $userConvs["error_msg"] = "NO_CONVERSATIONS";
				// }
				echo json_encode($userConvs,JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_NUMERIC_CHECK);
			}
			die();
		}
	}

	/**
	* Request the conversation between two users, will return all messages or none if no conversation existed
	*/
	public function msg_chat(){
		$user_id = @filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
		$user_uid = @filter_var($_POST['user_uid'], FILTER_SANITIZE_STRING);
		/* simple check for emptiness and length */ 
		if(!empty($user_id) AND !empty($user_uid)){
			/* Simple check if request is came from mobile device */
			$valid = $this->_model->get_UserValid($user_id,$user_uid);
			if($valid){
				/* The send user whom is going requested chat */
				$user_two = (int)filter_var($_POST['user_two'], FILTER_SANITIZE_NUMBER_INT);
				/* Check if limit is came along with the request */
				$limit = @filter_var($_POST['limit'], FILTER_SANITIZE_NUMBER_INT);
				/* Check if limit is came along with the request */
				$con_from_id = @filter_var($_POST['con_id'], FILTER_SANITIZE_NUMBER_INT);
				$convs;
				/* Get any conversations if any existed... with or without limit request */
				if(!empty($limit)){
					$convs = $this->_model->get_Conv($user_id,$user_two,$limit);
				}else if(!empty($con_from_id)){
					$convs = $this->_model->get_ConvNew($user_id,$user_two,$con_from_id);
				}else{
					$convs = $this->_model->get_Conv($user_id,$user_two);
				}
				/* Check if the user has any conversations at all, may be he first time on site :) */
				if($convs){
					$userConvs['s'] = 1;
					$userConvs["users"] = $convs;
				/* User don't have any conversations */
				}else{
					$userConvs['s'] = 0;
					// $userConvs["error"] = 1;
					// $userConvs["error_msg"] = "NO_CONVERSATIONS";
				}
				echo json_encode($userConvs,JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_NUMERIC_CHECK);
				die();
			}
			else
				die();
		}
		die();
	}

	/**
	* Check if user have received any new messages,
	* will return success with users id's and number of messages respectively
	*/
	public function msg_check(){
		$user_id = @filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
		$user_uid = @filter_var($_POST['user_uid'], FILTER_SANITIZE_STRING);
		/* simple check for emptiness and length */ 
		if(!empty($user_id) AND !empty($user_uid)){
			/* Simple check if request is came from mobile device */
			$valid = $this->_model->get_UserValid($user_id,$user_uid);
			if($valid){
				/* Request new incoming message from DB if such exists */
				$userConvs = $this->_model->get_ConvNewMsgCheck($user_id);
				/* Check if the user has any conversations at all, may be he first time on site :) */
				if($userConvs){
					$userConvs['s'] = 1;
				/* User don't have any conversations */
				}else{
					$userConvs['s'] = 0;
					// $userConvs["error"] = 1;
					// $userConvs["error_msg"] = "NO_CONVERSATIONS";
				}
				echo json_encode($userConvs,JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_NUMERIC_CHECK);
				die();
			}
			else
				die();
		}
	}

	/* 
	* Login request 
	* @param email and password POST value type
	* @return JSON object with user details for current account else error login even if the account doesn't exists  
	*/
	public function login(){
		$email = @filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
		$password = @filter_var($_POST['password'], FILTER_SANITIZE_STRING);
		/* simple check for emptiness and length */ 
		if(!empty($email) AND !empty($password)){
			/* get user details upon success the important is to pass the UID */
			$response = $this->_model->getUserByEmailAndPassword($email, $password);
			if ($response != false) {
				$response['s'] = 1;
				/* get users age is not necessary here */
				// $dateTime = new DateTime();
				// $dateTimeUser = new DateTime($response["user_birth"]);
				// $response["user_birth"]= $dateTimeUser->diff($dateTime)->format('%y');
				echo json_encode($response,JSON_NUMERIC_CHECK );
				die();
			} else {
				$response["error"] = 1;
				$response["error_msg"] = "INPUT_WRONG";
				echo json_encode($response,JSON_NUMERIC_CHECK );
				die();
			}
		}
		/* forced default die */
		die();
	}

	/**
	* Return users profile information or pictures depends on requested tag
	* TAG : 
	* 1. last_modified => will return only modification date or false 
	* 2. profile => will return all profile information table
	**/
	public function info(){
		$user_id = @filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
		/* The request tag that i will handle appropriate request */
		$user_tag = @filter_var($_POST['tag'], FILTER_SANITIZE_STRING);
		/* Simple check for emptiness and length */
		if(!empty($user_id) AND !empty($user_tag)){
			/* Request for last profile modification time */
			if($user_tag === "last_modified"){
				/* get users last modification time if such user exists */
				$response = $this->_model->get_ProfileModified($user_id);
				if($response){
					$response['s'] = 1;
				}else{
					$response['s'] = 0;
					$response["error"] = 1;
					$response["error_msg"] = 0;
				}
				echo json_encode($response,JSON_NUMERIC_CHECK );
			}else if($user_tag === "profile"){
				/* get users information if such user exists */
				$response = $this->_model->get_UserInformation($user_id);
				if($response){
					$response['s'] = 1;
				}else{
					$response['s'] = 0;
					$response["error"] = 1;
					$response["error_msg"] = 0;
				}
				echo json_encode($response,JSON_NUMERIC_CHECK );
			}
		}
		/* Die any way :) */
		die();
	}


	/**
	* Handle users profile editing (updating) and returns last profile modification time depends on requested tag
	* TAG : 1. last_modified => last modified date request 
	*		2. edit => edit profile
	**/
	public function edit(){
		$user_id = @filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
		$user_uid = @filter_var($_POST['user_uid'], FILTER_SANITIZE_STRING);
		/* The request tag that i will handle appropriate request */
		$user_tag = @filter_var($_POST['tag'], FILTER_SANITIZE_STRING);
		/* simple check for emptiness and length */
		if(!empty($user_id) AND !empty($user_uid) AND !empty($user_tag)){
			$response = array('s' => 0);
			/* Request for last profile modification time */
			if($user_tag === "last_modified"){
				/* get users last modification time if such user exists */
				// $modification = $this->_model->get_ProfileModified($user_id);
				$response = $this->_model->get_ProfileModified($user_id);
				if($response){
					// $response["user_modified"] = $modification->user_modified;
					$response['s'] = 1;
				}
				/* i will not return any error message for current request, no need */
				echo json_encode($response,JSON_NUMERIC_CHECK );
				die();
			}else if($user_tag === "edit"){
				/* Simple check if request is came from mobile device and valid user */
				$valid = $this->_model->get_UserValid($user_id,$user_uid);
				/* If user is valid will try to update else WTF! will exit on die*/
				if($valid){
					$p_user_name = filter_var($_POST['user_name'], FILTER_SANITIZE_SPECIAL_CHARS);
					$p_user_height = filter_var($_POST['user_height'], FILTER_SANITIZE_NUMBER_INT);
					$user_smokes = filter_var($_POST['user_smokes'], FILTER_SANITIZE_NUMBER_INT);
					$user_face = filter_var($_POST['user_face'], FILTER_SANITIZE_NUMBER_INT);
					$user_body = filter_var($_POST['user_body'], FILTER_SANITIZE_NUMBER_INT);
					$p_user_about_me = filter_var($_POST['user_about'], FILTER_SANITIZE_STRING);
					$p_user_looking_for = filter_var($_POST['user_looking'], FILTER_SANITIZE_STRING);
					$p_user_interpersonal_stat = filter_var($_POST['user_interpersonal_stat'], FILTER_SANITIZE_NUMBER_INT);
					$user_eyes = filter_var($_POST['user_ec'], FILTER_SANITIZE_NUMBER_INT);
					$user_kids = filter_var($_POST['user_k'], FILTER_SANITIZE_NUMBER_INT);
					$user_vehicle = filter_var($_POST['user_v'], FILTER_SANITIZE_NUMBER_INT);
					$user_alcohol = filter_var($_POST['user_a'], FILTER_SANITIZE_NUMBER_INT);
					$user_hair_color = filter_var($_POST['user_hc'], FILTER_SANITIZE_NUMBER_INT);
					$p_user_user_district = filter_var($_POST['user_district'], FILTER_SANITIZE_NUMBER_INT);
					$p_user_city = filter_var($_POST['user_city'], FILTER_SANITIZE_NUMBER_INT);
					$updateValues;
					/** check if user name present and fit's size **/
					if(strlen($p_user_name) >= 4 AND strlen($p_user_name) <= 62)
						$updateValues['user_name']=$p_user_name;
					/** check if user height present and fit's size **/
					if($p_user_height >= 0 AND $p_user_height <= 270)
						$updateValues['user_height']=$p_user_height;
					/** check if user smokes present and fit's size **/
					if($user_smokes >= 0 AND $user_smokes <= 3){
						$updateValues['user_smokes']=$user_smokes;
						// error_log(" updated user_smokes");
					}
					/** check if user smokes present and fit's size **/
					if($user_face >= 0 AND $user_face <= 7){
						$updateValues['user_face']=$user_face;
						// error_log(" updated user_face");
					}
					/** check if user smokes present and fit's size **/
					if($user_body >= 0 AND $user_body <= 7)
						$updateValues['user_body']=$user_body;
					if($user_eyes >= 0 AND $user_eyes <= 7)
						$updateValues['user_ec']=$user_eyes;
					if($user_kids >= 0 AND $user_kids <= 7)
						$updateValues['user_k']=$user_kids;
					if($user_vehicle >= 0 AND $user_vehicle <= 7)
						$updateValues['user_v']=$user_vehicle;
					if($user_alcohol >= 0 AND $user_alcohol <= 7)
						$updateValues['user_a']=$user_alcohol;
					if($user_hair_color >= 0 AND $user_hair_color <= 7)
						$updateValues['user_hc']=$user_hair_color;
					/** check if user wrote something about himself and allowed long **/
					if(isset($_POST['user_about']) AND strlen($p_user_about_me) <= 400){
						$updateValues['user_about']=$p_user_about_me;
						// error_log(" updated user_about");
					}
					/** check if user wrote something what he is looking for and allowed long **/
					if(isset($_POST['user_looking']) AND strlen($p_user_looking_for) <= 400){
						// error_log(" updated user_looking");
						$updateValues['user_looking']=$p_user_looking_for;
					}
					/** check if user change his interpersonal status **/
					if($p_user_interpersonal_stat >= 0 AND $p_user_interpersonal_stat <= 20)
						$updateValues['user_interpersonal_stat']=$p_user_interpersonal_stat;
					/** Both City and District are coming as couple other vise no updating ! **/
					/** CURRENTLY no check against array for existing object's just for known values range **/
					if($p_user_user_district >= 1 AND $p_user_user_district <= 7 AND $p_user_city >= 7 AND $p_user_city <= 9800){
						$updateValues['user_district']=$p_user_user_district;
						$updateValues['user_city']=$p_user_city;
					}
					/** Check if at least one field is filled and update DB else why this request was came or some errors DO DIE **/
					if(!empty($updateValues)){
						// error_log("will update");
						/** Add current update date **/
						$updateValues['user_modified']=date("Y-m-d H:i:s");
						$updated = $this->_model->set_EditProfile($user_id,$updateValues);
						/* in case the update was OK i also return the new modification time stamp to update in users DB */
						if($updated){
							$response = $this->_model->get_ProfileModified($user_id);
							// $response["user_modified"] = $modification->user_modified;
							$response['s'] = 1;
						}else{
							$response["error_msg"] = "UPDATE_FAILED";
						}
						echo json_encode($response,JSON_NUMERIC_CHECK );
						die();
					}
				}
			}else{
				/* Die the hard way because none of requests meets criteria */
				die();
			}
		}
		die();
	}

	/**
	* New user registration request 
	**/
	public function reg(){
		/* Get the request tag */
		$tag = @filter_var($_POST['tag'], FILTER_SANITIZE_STRING);
		$email = @filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
		if(!empty($tag) AND !empty($email)){
			// response Array
			$response = array("tag" => $tag, 's' => 0, "error" => 0);
			// Request type is Register new user
			if($tag === 'reg_request'){
				/* Check if corresponding email is available */
				$isTaken = $this->_model->get_EmailTaken($email);
				if(!$isTaken){
					// Return email is free
					$response['s'] = 1;
				}else {
					// Return error message email is taken
					$response["error"] = 1;
					$response["error_msg"] = "EMAIL_TAKEN";
				}
				echo json_encode($response,JSON_NUMERIC_CHECK | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
				die();
			// Request type is Register new user
			}else if($tag == 'reg_perform'){
				$password = @filter_var($_POST['password'], FILTER_SANITIZE_STRING);
				$user_birth = @filter_var($_POST['user_birth'], FILTER_SANITIZE_STRING);
				$user_gender = @filter_var($_POST['user_gender'], FILTER_SANITIZE_NUMBER_INT);
				$user_name = @filter_var($_POST['user_name'], FILTER_SANITIZE_SPECIAL_CHARS);
				//get last added users to DB
				$isTaken = $this->_model->set_RegisterNewUser($email,$password,$user_birth,$user_gender,$user_name);
				if($isTaken){
					/* Get posting with user language interface  */
					$langLoc = @filter_var($_POST['lang'], FILTER_SANITIZE_STRING);
					if(!empty($langLoc))
						Language::load($langLoc);
					else
						Language::load(LANGUAGE_DEFAULT_CODE);
					/* Compose and send email to newly created account to active it */
					// It's better to get the return in case of send if failed
					$this->mail_ActivateLink($isTaken->user_id,$isTaken->user_email,$isTaken->user_activation_hash);
					// Return registration was successfully for new user
					$response['s'] = 1;
				}else{
					// Return error message email is taken
					$response["error"] = 1;
					$response["error_msg"] = "ERROR_RETRY";
				}
				echo json_encode($response,JSON_NUMERIC_CHECK | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
				die();
			}
			die();
		}
		die();
	}


	/**
	* Users search requests may be with additional filters and page numbers
	*/
	public function users(){
		$pageId = (int)@filter_var($_POST['page_id'], FILTER_SANITIZE_NUMBER_INT);
		/** arguments patter to filter are set here **/
		$filterArgs = array(
			'user_gender' => array('filter' => FILTER_VALIDATE_INT,
									'flags' => FILTER_REQUIRE_SCALAR, 
									'options' => array('min_range' => 1,'max_range' => 2)),
			'user_age_from' => array('filter' => FILTER_VALIDATE_INT,
									'flags' => FILTER_REQUIRE_SCALAR, 
									'options' => array('min_range' => 19,'max_range' => 98)),
			'user_age_to' => array('filter' => FILTER_VALIDATE_INT,
									'flags' => FILTER_REQUIRE_SCALAR, 
									'options' => array('min_range' => 19,'max_range' => 98)),
			'srch_dstrct' => array('filter' => FILTER_VALIDATE_INT,
									'flags' => FILTER_REQUIRE_SCALAR, 
									'options' => array('min_range' => 1,'max_range' => 7))
		);
		/** Filter POST request against array with NULL flag enabled **/
		$getValues = filter_input_array(INPUT_POST, $filterArgs,false);
		if(!empty($getValues['user_gender']))
			$setValues['user_gender']=$getValues['user_gender'];
		if(!empty($getValues['user_age_from']))
			$setValues['user_age_from']=date((date("Y")-$getValues['user_age_from'])."-m-d");
		if(!empty($getValues['user_age_to']))
			$setValues['user_age_to']=date((date("Y")-$getValues['user_age_to'])."-m-d");
		if(!empty($getValues['srch_dstrct']))
			$setValues['user_district']=$getValues['srch_dstrct'];
		// Build user list
		$response;
		if(!empty($setValues)){
			$response = $this->_model->get_Search($pageId,DISPLAY_USERS,$setValues);
		}else{
			$response = $this->_model->get_Users($pageId,DISPLAY_USERS);
		}
		if($response){
			$response['s'] = 1;
			echo json_encode($response,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
			die();
		}else {
			// Some problem return as retry option
			$response['s'] = 0;
			echo json_encode($response,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
			die();
		}
	}

	/** 
	* Retrieve user pictures
	*/
	public function pictures(){
		$user_id = @filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
		/* simple check for emptiness and length */ 
		if(!empty($user_id)){
			/* user images as one string with combination "|(image_path)|(imagepath) and etc..." or false if empty or not exists */
			$u_images = $this->_model->get_UserImages($user_id);
			if($u_images){
				// Build user image paths list
				$response="";
				$response .= '<user>';
				foreach($u_images as $holder){
					/* This check is for user if he set image private and the images are confirmed by administrator */
					if(!$holder->user_img_private && $holder->user_img_active){
						$response .= '<user_img_path>'.$holder->user_img_path.'</user_img_path>';
					}
				}
				$response .= '</user>';
				echo json_encode($response,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
				die();
			}else {
				// echo "No user pictures found";
				die();
			}
		}else {
			die();
		}
	}



	/**
	* Compose and send verification mail with New Account Activation link to newly created user
	* @param INT user id, STRING email, STRING activation hash
	* @return BOOL for successfully send mail or failure
	*/
	public function mail_ActivateLink($user_id,$user_mail,$user_activation_hash){
		/* render mail content with user information */
		$data=['user_id'=>$user_id,'user_mail'=>$user_mail,'user_activation_hash'=>$user_activation_hash];
		ob_start();
		$this->_view->renderPath('mails/login/verify',$data);
		$content = ob_get_clean();
		try{
			$mail = new Mailer();
			$mail->setSender(SITETITLE, EMAIL_NO_REPLY.EMAIL_ADDRESS);
			$mail->setReplyTo(SITETITLE, EMAIL_INFO.EMAIL_ADDRESS);
			$mail->addRecipient("User ID : ".$user_id,$user_mail);
			$mail->setSubject(Language::getValue('mail_acnt_actv'));
			$mail->setMessage($content);
			$mail->send();
		}catch(Exception $e){
			error_log($e->getMessage());
			return false;
		}
		return true;
	}

	/** 
	* deleting users profile image from DB and from local disk
	**/
	public function image_Delete(){
		$user_id = @filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
		$user_uid = @filter_var($_POST['user_uid'], FILTER_SANITIZE_STRING);
		/* simple check for emptiness and length */ 
		if(!empty($user_id) AND !empty($user_uid)){
			/* Simple check if request is came from mobile device */
			$valid = $this->_model->get_UserValid($user_id,$user_uid);
			if($valid){
				/* user image path */
				$img_delete = @filter_var($_POST['user_img_delete'], FILTER_SANITIZE_STRING);
				/* Check is this string contains users details in case some one will want to delete accounts private data */
				if(strpos($img_delete,'/'.$user_id.'_') !== false){
					/* Delete the image from images DB */
					$updated = $this->_model->set_ImageDelete($user_id,$img_delete);
					/* Excellent lets delete file from server */
					if(file_exists($img_delete)){
						// error_log( ' unlinked existing file...');
						unlink($img_delete);
					}
					/* Write response only current time that will be passed to server and DB */
					$response['user_modified']=date("Y-m-d H:i:s");
					if($updated){
						/** If OK add current update date **/
						$updated = $this->_model->set_EditProfile($user_id,$response);
					}
					$response['s'] = 1;
					echo json_encode($response,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
					die();
				}
			}
		}
		die();
	}

	/** 
	* Getting new image stream, compressing, setting on server and in db ,NO RENDER
	* remember to change all images to JPEG !!??
	**/
	public function image_Upload(){
		$user_id = @filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
		$user_uid = @filter_var($_POST['user_uid'], FILTER_SANITIZE_STRING);
		/* simple check for emptiness and length */ 
		if(!empty($user_id) AND !empty($user_uid)){
			/* Simple check if request is came from mobile device */
			$valid = $this->_model->get_UserValid($user_id,$user_uid);
			if($valid){
				$folder = 'images/';
				$img_name = $user_id.'_'.md5('KISS Salt'.time()).'.jpeg';
				/* An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded */
				$img_test = imagecreatefromstring(base64_decode($_POST['user_avatar']));
				/* Simple check if file is image type */
				if (!$img_test) {
					die();
				}
				/* Save the image */
				imagejpeg($img_test, $folder.$img_name);
				/* Free up memory */
				imagedestroy($img_test);
				/* Get image info and check if actually this is an real image and not injection */
				$info = getimagesize($folder.$img_name);
				if ($info[0] > 0 && $info[1] > 0 && $info['mime']) {
					/* update pictures table with new image... */
					$updated = $this->_model->set_ConcatNewImage($user_id,$folder.$img_name);
					/* Write response only current time that will be passed to server and db */
					$response['user_modified']=date("Y-m-d H:i:s");
					if($updated){
						/** If OK add current update date **/
						$updated = $this->_model->set_EditProfile($user_id,$response);
					}
					$response['s'] = 1;
					/* Return created image path */
					$response["user_avatar"] = $folder.$img_name;
					echo json_encode($response,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
					die();
				}else{
					error_log( "Image injection from user: " .$user_id );
				}
				die();
			}
		}
	}



}
/* Close the PHP file no need to further routing, all methods exiting die */
?>