<?php
if(!isset($_SESSION)) 
{ 
session_start(); 
} 
if(!isset($_SESSION['is_login']) ){
header("location: login.php");
?>
<script>
window.location="login.php";
</script>
<?php
}

// $permission  = explode(',',$_SESSION['permission_id']);
// if(!in_array(19,$permission) && !in_array(1,$permission)  ){

// $op['is_success'] = false;
// $op['data'] 	  = "عذرا انت غير مخول للوصل الى هذه الصفحة";
// echo json_encode($op);
// exit;

// }

date_default_timezone_set($_SESSION['SYSTimezone']);

		$Validator = array('success'=>false, 'data'=>array());
		// date_default_timezone_set('Asia/Baghdad');
		$LogTime = date('Y-m-d H:i:s');

		require_once "db_connect.php";

		if(isset($_GET['type']) AND $_GET['type']=='load'){
						$sql = "SELECT * FROM staff WHERE staff_id = '" . $_SESSION['user_id'] ."'  AND is_deleted=0 ";

						$query = $db->query($sql);

						if (!$query) {
									$error= "Error: " . $db->error;
									$State=false;

						}else{
									$Records = $query->fetch_assoc();


									$LogTime = date('Y-m-d H:i:s');


									// $Records = mysqli_fetch_array($Rows);

									if($Records){
										$_SESSION['user_id'] 				= $Records['staff_id'];
										$_SESSION['profile_type'] 	= $Records['profile_type'];
										$_SESSION['username'] 			= $Records['username'];
										$_SESSION['full_name'] 			= $Records['full_name'];
										$_SESSION['email'] 					= $Records['email'];
										$_SESSION['profile_image'] 	= $Records['profile_img'];
										$_SESSION['cover_image'] 		= $Records['cover_img'];
										$_SESSION['phone_number'] 	= $Records['phone_number'];
										$_SESSION['updated_at'] 		= $Records['updated_at'];
										$_SESSION['image_path'] 		= 'image/profile/';
										$_SESSION['language_id'] 		= $Records['language_id_fk'];

										$error= " Retrive Successfully";
										$State= true;

									}
									else{
												$error= " Can Not Retrieve Your Profile Information ";
												$State=false;
									} // if records

						}

						$Validator['success'] = $State;
						$Validator['data'] 		= $error;
						echo json_encode($Validator);
						exit();
		}

		if($_POST['type']=='update_profile_image'){
					$LogTime = date('Y-m-d H:i:s');
					$target_dir = "../image/profile/";
					$fileBook = rand(1000,100000) . "-" . $_FILES['profile_image']['name'];
					$target_file = $target_dir . basename($fileBook);
					$uploadOk = 1;
					$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
					// Check if image file is a actual image or fake image

			    $check = getimagesize($_FILES["profile_image"]["tmp_name"]);
			    if($check == false) {
							$error= " File is not an image. ";
							$State=false;
			    }else {
			    	$State=true;
			    }


					// Check file size
					if ($_FILES["profile_image"]["size"] > 1500000) {
							$error= " Sorry, your file is too large. ";
							$State=false;
					}
					// Allow certain file formats
					if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
					&& $imageFileType != "gif" ) {
							$error= " Sorry, only JPG, JPEG, PNG & GIF files are allowed. ";
							$State=false;
					}
					// Check if $uploadOk is set to 0 by an error
					if ($State == false) {
							$error= " Sorry, your file was not uploaded. ";
					// if everything is ok, try to upload file
					} else {

					    if (move_uploaded_file($_FILES["profile_image"]["tmp_name"], $target_file)) {

								$sql = "UPDATE staff SET last_action='Update Profile Image', updated_at='$LogTime',profile_img='$fileBook'   WHERE staff_id = '".$_SESSION['user_id']."'";

								$query = $db->query($sql);
								if (!$query) {
											$error= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
											$State=false;

								}else{
										$error= " Profile Picture Successfully updated ";
										$State=true;
								}

					    } else {
									$error= " Sorry, there was an error uploading your file. ";
									$State=false;
					    }
					}

					$Validator['success'] = $State;
					$Validator['data'] = $error;

		}



		if($_POST['type']=='update_profile_cover_image'){
					$LogTime = date('Y-m-d H:i:s');
					$target_dir = "../image/profile/";
					$fileBook = rand(1000,100000) . "-" . $_FILES['cover_image']['name'];
					$target_file = $target_dir . basename($fileBook);
					$uploadOk = 1;
					$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
					// Check if image file is a actual image or fake image

					$check = getimagesize($_FILES["cover_image"]["tmp_name"]);
					if($check == false) {
							$error= " File is not an image. ";
							$State=false;
					}else {
						$State=true;
					}


					// Check file size
					if ($_FILES["cover_image"]["size"] > 1500000) {
							$error= " Sorry, your file is too large. ";
							$State=false;
					}
					// Allow certain file formats
					if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
					&& $imageFileType != "gif" ) {
							$error= " Sorry, only JPG, JPEG, PNG & GIF files are allowed. ";
							$State=false;
					}
					// Check if $uploadOk is set to 0 by an error
					if ($State == false) {
							$error= " Sorry, your file was not uploaded. ";
					// if everything is ok, try to upload file
					} else {

							if (move_uploaded_file($_FILES["cover_image"]["tmp_name"], $target_file)) {

								$sql = "UPDATE staff SET last_action='Update Profile Image', updated_at='$LogTime',cover_img='$fileBook'   WHERE staff_id = '".$_SESSION['user_id']."'";

								$query = $db->query($sql);
								if (!$query) {
											$error= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
											$State=false;

								}else{
										$error= " Cover Picture Successfully updated ";
										$State=true;
								}

							} else {
									$error= " Sorry, there was an error uploading your file. ";
									$State=false;
							}
					}

					$Validator['success'] = $State;
					$Validator['data'] = $error;

		}

		if($_POST['type']=='update_profile'){

			$LastLoging 	= $LogTime;
			$full_name 		= $_POST['full_name'];
			$phone_number 	= $_POST['phone_number'];
			$email 			= $_POST['email'];
			$lang_id 		= $_POST['lang_id'];

			$sql = "UPDATE staff SET last_action='Update Profile', updated_at='$LastLoging',full_name='$full_name' ,phone_number='$phone_number',email='$email',language_id_fk='$lang_id'  WHERE staff_id = '".$_SESSION['user_id']."'";

			$query = $db->query($sql);
			if (!$query) {
						$error= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
						$State=false;

			}else{
						$error= "Successfully Update Your Profile";
						$State=true;
			}
			$Validator['success'] = $State;
			$Validator['data'] = $error;
		}

		if($_POST['type']=='update_password'){
			$LastLoging = $LogTime;
			$password 	= $_POST['password'];
			$repassword = $_POST['repassword'];

			if($repassword == $password){
				$password=hash('sha256',$password);
		    $password= stripslashes($password);
		    $password=mysqli_real_escape_string($db,$password);

				$sql = "UPDATE staff SET last_action='Change Password', updated_at='$LastLoging',password='$password' WHERE staff_id = '".$_SESSION['user_id']."'";

				$query = $db->query($sql);
				if (!$query) {
							$error= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
							$State=false;

				}else{
							$error= "Successfully Update Your Password";
							$State=true;
				}

			}else{
				$error= "Passwords does not match";
				$State=false;
			}


			$Validator['success'] = $State;
			$Validator['data'] = $error;
		}

		echo json_encode($Validator);

?>
