<?php
// namespace controllers;
// use core\view as View;
// use core\auth as Auth;

/**
* Class Profile
* This is a controller that is only visible for the logged in user
* constructed with Auth::handleLogin(); so all Auth::handleCookedLogin() may be omitted... ???
*/
class Profile extends Controller{
	/**
	 * Construct this object by extending the basic Controller class
	 */
	function __construct(){
		parent::__construct();
		/* This controller should only be visible/usable by logged in users, so i put login-check here, but a problem with fucking Chrome */
		// Auth::handleLogin();
		Language::load();
		$this->loadModel('profile');
	}

	/**
	* Index, method controls what happens when you move to /profile/index or just /profile
	* will build all user view and construct images for it...
	*/
	function index(){
		if(Auth::handleCookedLogin()){
			$usedData = $this->_model->get_User(Session::get("user_id"));
			$u_images = $this->_model->get_UserImages(Session::get("user_id"));
			if($u_images){
				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_active)
						$usedData->user_img_paths .= "|".$holder->user_img_path;
					else
						$usedData->user_img_paths .= "|&".$holder->user_img_path;
				}
			}
			$this->_view->rendercusttmpl('orn','header');
			$this->_view->render('listed/top');
			$this->_view->render('profile/index',$usedData);
			$this->_view->render('listed/bottom');
			$this->_view->rendercusttmpl('orn','footer');
		}else{
			Url::redirect('');
		}
	}

	/**
	* Showing user INBOX with send/received and read/unread messages
	* @param INT(r) current page to show messages if greater than defined
	**/
	function inbox($pageId=0){
		if(Auth::handleCookedLogin()){
			$pageId = (int)filter_var($pageId, 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;
			$this->_view->rendercusttmpl('orn','header');
			$this->_view->render('listed/top');
			$usedData = $this->_model->get_UserConvs($pageId,DISPLAY_USERS,Session::get("user_id"));
			/* Check if the user has any conversations at all, may be he first time on site :) */
			if($usedData){
				$usedData['add']['user_id'] = Session::get("user_id");
				$usedData['add']['pid'] = $pageId;
				$this->_view->render('profile/inbox',$usedData);
			}else{
				$this->_view->render('profile/nothing',$usedData);
			}
			$this->_view->render('listed/bottom');
			$this->_view->rendercusttmpl('orn','footer');
		}else{
			Url::redirect('');
		}
	}

	/**
	* Delete image file from DB and server and clean selected image if this is the case, NO RENDER
	*/
	public function imgDelete(){
		$p_user_img_delete = filter_var($_POST['user_img_delete'], FILTER_SANITIZE_STRING);
		if(Auth::handleCookedLogin() AND !empty($p_user_img_delete)){
			/* check if the image path actually contains images directory, if no ... */
			if (strpos($p_user_img_delete, 'images/') !== false){
				/* Get user images array from DB */
				$u_images = $this->_model->get_UserImages(Session::get('user_id'));
				if($u_images){
					foreach($u_images as $holder){
						/* This check is meant to find if our friendly user not "accidentally" not trying to delete someone else image */
						if($p_user_img_delete == $holder->user_img_path){
							/* Excellent i found the file now lets delete file from server */
							if(file_exists($p_user_img_delete)){
								// error_log( ' unlinked existing file...');
								unlink($p_user_img_delete);
							}
							/* Delete the image from DB both the user and image id passed */
							$deleted = $this->_model->set_ImageDelete(Session::get('user_id'),$holder->user_img);
							/* Formally i was selecting for a user new avatar if current was default... but there is no need, just delete from main and clean additionally user images */
							if($holder->user_img_selected)
								$deleted = $this->_model->set_ImageSelectedNone(Session::get('user_id'));
							/* for me this is just a return no check needed for deleted item because most important is to delete on server hard drive */
							return;
						}
					}
				}
			}
			/* this is just a return no check needed for deleted item because most important is to delete on server hard drive */
			return;
		}else{
			Url::redirect('');
		}
	}

	/**
	* Update user profiles avatar (main selected image) ,NO RENDER
	* The selected image should NOT be a private NOR unconfirmed !!!
	*/
	public function imgUpdate(){
		$p_img_selected = filter_var($_POST['user_img_selected'], FILTER_SANITIZE_STRING);
		if(Auth::handleCookedLogin() AND !empty($p_img_selected)){
			/* Get user images array from DB */
			$u_images = $this->_model->get_UserImages(Session::get('user_id'));
			if($u_images){
				foreach($u_images as $holder){
					/* This check is for user if he set image private and the images are confirmed by administrator */
					/* As i mentioned : no selecting for private image nor for unconfirmed image and only if such image exists */
					if(!$holder->user_img_private && $holder->user_img_active && $p_img_selected == $holder->user_img_path){
						/* We just return the result from DB */
						return $this->_model->set_ImageSelected(Session::get('user_id'),$holder->user_img,$holder->user_img_path);
					}
				}
			}else{
				/* The users select but nothing exists ?!!! it's strange */
				// error_log(' User tries to update selected image but do not have any images ID : '.Session::get('user_id'));
				return;
			}
		}else{
			Url::redirect('');
		}
	}

	/** 
	* Getting new image stream, compressing, setting on server and in db ,NO RENDER
	* remember to change all images to JPEG !!??
	**/
	public function addImage(){
		if(Auth::handleCookedLogin()){
			if($_FILES["file"]["error"] > 0){
				error_log( "Return Code: " . $_FILES["file"]["error"] . "\r\n" );
			}else{
				$file = $_FILES['file']['tmp_name'];
				// error_log($file);
				list($width,$height,$type,$attr) = getimagesize($file);
				$mime = image_type_to_mime_type($type);
				//echo 'file-size : '.filesize($file);
				$folder = 'images/';
				// mime checks add a layer of security that keeps out less sophisticated attackers
				// and file size greater than 400KB 
				if(($mime != "image/jpeg") && ($mime != "image/pjpeg") && ($mime != "image/png") && !$width && !$height){
					error_log( 'Error3: Upload file type un-recognized. Only .JPG/.JPEG or .PNG images allowed' );
				}else{
					// If the file has no width its not a valid image
					// generate simple salt for file name
					$Newname = md5('KISS Salt'.time());
					// the first file name should be user id
					$name = Session::get('user_id').'_'.$Newname.'.'.substr($mime,6);
					// error_log(' image suit , and file size is : '.filesize($file));
					if(!!$height && filesize($file) < 1000000){
						// Should I remove this second mime check? since the info comes form the same spoofable source in the image
						$fileType = exif_imagetype($file);
						$allowed = array(IMAGETYPE_JPEG, IMAGETYPE_PNG);
						if(in_array($fileType, $allowed)){
							//var_dump($mime);
							// error_log($folder.$name);
							if(move_uploaded_file($file, $folder.$name)){
								// un check if file exist from server
								// if (file_exists($file)){
									// echo ' unlinked existing file...';
									// unlink($file);
								// }
								// set good permissions for the file
								//chmod($name, 0644);
								//chmod($name, 0755);
								$usedData = $this->_model->set_ConcatNewImage(Session::get('user_id'),$folder.$name);
								// error_log(' db update result --> '.$usedData.' <--');
								/* The concatenation new returns string with user images paths separated by "|" */
								echo $usedData;
							}else{
								error_log( 'Server Error! unable to move profile new image' );
							} 
						}
						// error_log( 'no file type '.$fileType );
					}else if($width > 700 && filesize($file) >= 1000000){
						// normalizing factor for maximum image width of 700px and set linear height
						$norm_factor = 700 / $width;
						$compress_factor = 45;
						// error_log('got herre'.$folder.$name);
						// set new image dimensions
						$new_width = $width * $norm_factor;
						$new_height = $height * $norm_factor;
						// Re-sample
						$image_new = imagecreatetruecolor($new_width, $new_height);
						// ternary mime .png or .jpg select operator
						$image = ($mime == "image/png") ? imagecreatefrompng($file) : imagecreatefromjpeg($file);
						//  check if file exist on server and delete the original file because we don't need it any more
						if (file_exists($file)){
							//echo ' unlinked existing file...';
							unlink($file);
						}
						imagecopyresampled($image_new, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
						// set the content type header - in this case image/jpeg
						header('Content-Type: image/jpeg');
						// check and output the new file to folder and set the compress quality
						if(imagejpeg($image_new, $folder.$name, $compress_factor)){
							//chmod($name, 0644);
							//chmod($name, 0755);
							$usedData = $this->_model->set_ConcatNewImage(Session::get('user_id'),$folder.$name);
							echo $usedData;
						}else{
							error_log( 'Server Error!');
						}
						// Free up memory
						imagedestroy($image);
					}
				}
			}
		}else{
			Url::redirect('');
		}
	}

	/**
	* Edit user profile page 
	*/
	public function edit(){
		if(Auth::handleCookedLogin()){
			$usedData = $this->_model->get_User(Session::get("user_id"));
			$this->_view->rendercusttmpl('orn','header');
			$this->_view->render('profile/edit',$usedData);
			$this->_view->rendercusttmpl('orn','footer');
		}else{
			Url::redirect('');
		}
	}

	/**
	* Update user profile information, only with supplied POST variables
	* @param mix POST value type
	* @return STRING with feedback result
	*/
	public function update(){
		if(Auth::handleCookedLogin()){
			$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_me'], FILTER_SANITIZE_STRING);
			$p_user_looking_for = filter_var($_POST['user_looking_for'], FILTER_SANITIZE_STRING);
			$p_user_interpersonal_stat = filter_var($_POST['user_inter'], 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(!empty($p_user_name) AND 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(!empty($p_user_height) AND $p_user_height >= 100 AND $p_user_height <= 270)
				$updateValues['user_height']=$p_user_height;
			/** check if user smokes present and fit's size **/
			if(!empty($user_smokes) AND $user_smokes >= 1 AND $user_smokes <= 3)
				$updateValues['user_smokes']=$user_smokes;
			/** check if user smokes present and fit's size **/
			if(!empty($user_face) AND $user_face >= 1 AND $user_face <= 7)
				$updateValues['user_face']=$user_face;
			/** check if user smokes present and fit's size **/
			if(!empty($user_body) AND $user_body >= 1 AND $user_body <= 7)
				$updateValues['user_body']=$user_body;
			/** check if user wrote something about himself and allowed long **/
			if(!empty($p_user_about_me) AND strlen($p_user_about_me) <= 400)
				$updateValues['user_about']=$p_user_about_me;
			/** check if user wrote something what he is looking for and allowed long **/
			if(!empty($p_user_looking_for) AND strlen($p_user_looking_for) <= 400)
				$updateValues['user_looking']=$p_user_looking_for;
			/** check if user change his interpersonal status **/
			if(!empty($p_user_interpersonal_stat) AND $p_user_interpersonal_stat >= 1 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(!empty($p_user_user_district) AND !empty($p_user_city) AND $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 **/
			if(!empty($updateValues)){
				/** Add current update date **/
				$updateValues['user_modified']=date("Y-m-d H-i");
				$updated = $this->_model->set_EditProfile(Session::get("user_id"),$updateValues);
				if($updated){
					echo 'SUCCESS';
					return;
				}else{
					echo 'UPDATE_FAILED';
					return;
				}
			}else{
				echo 'UPDATE_NOTHING';
				return;
			}
		}
		Url::redirect('login/index');
	}

}