<?php
//ini_set('display_errors', 1);
session_start();

require_once '../utils/errorhandler.php';
require_once '../utils/response.php';
require_once '../model/dbclass.php';
require_once '../model/model.php';
require_once '../model/user.php';
require_once '../utils/sanitize.php';

$filename1 = "";
if($_FILES["imageurl"]["name"] !== "" && $_FILES["imageurl"]["name"] !== null && $_FILES["imageurl"]["name"] !== "-"){
	$filenamearray = explode(".",$_FILES["imageurl"]["name"]); 
	$filename1 = $filenamearray[0] . mt_rand(10,111111111) . "." . end($filenamearray);
}else { $filename1 = "-"; }

	$returnvalue = '';
    if($_FILES["imageurl"] !== null && $_FILES["imageurl"] !== "-"){	
    	$allowedExts = array("gif", "jpeg", "jpg","pdf","png","PNG");
    	$temp = explode(".", $_FILES["imageurl" . $i]["name"]);
    	$returnvalue .= '' . $_FILES["imageurl"]["name"];
    	$extension = end($temp);
    	if ((($_FILES["imageurl" . $i]["type"] === "image/gif") || ($_FILES["imageurl" . $i]["type"] === "image/jpeg") || ($_FILES["imageurl" . $i]["type"] === "image/jpg") || ($_FILES["imageurl" . $i]["type"] === "image/pjpeg") || ($_FILES["imageurl" . $i]["type"] === "image/png") || ($_FILES["imageurl" . $i]["type"] === "image/PNG") || ($_FILES["imageurl" . $i]["type"] === "application/pdf")) && in_array($extension, $allowedExts)){
			if ($_FILES["imageurl"]["error"] > 0){
				$returnvalue .= ' | error saving photo'; //echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
			}else{
				/*
				if (file_exists("../images/borrowers/" . $_FILES["userphotoname"]["name"])){
					$returnvalue .= ' | the file exists'; //echo $_FILES["userphoto"]["name"] . " already exists. ";
      		    }else{ */
					move_uploaded_file($_FILES["imageurl"]["tmp_name"],"../images/" . $filename1);
					$returnvalue .= "Upload Successful";
      		    //}
    		}
		}else{
             $returnvalue .= ' | Invalid file type';	    
		}
      }

$user = new User();
$res = $user->getUserInfo("email = '" . $_SESSION["wuseremail"] . "'");

//exit("Email Session: " . $_SESSION["email"]);
//if($res && $_POST["email"] === $_SESSION["email"]){
if($res){
    $id = $res["id"];

    $phone = ((isset($_POST["phone"]) && is_numeric($_POST["phone"]) && strlen($_POST["phone"]) === 11) ? $_POST["phone"] : $res["phone"]);
    
	$query = "lastname = '" . ((isset($_REQUEST["lastname"]) && $_REQUEST["lastname"] !== '') ? htmlentities($_REQUEST["lastname"]) : $res["lastname"]) . "',
	firstname = '" . ((isset($_REQUEST["firstname"]) && $_REQUEST["firstname"] !== '') ? htmlentities($_REQUEST["firstname"]) : $res["firstname"]) . "',
	othernames = '" . ((isset($_REQUEST["othernames"]) && $_REQUEST["othernames"] !== '') ? htmlentities($_REQUEST["othernames"]) : $res["othernames"]) . "',
	dateofbirth = '" . ((isset($_REQUEST["dateofbirth"]) && $_REQUEST["dateofbirth"] !== '') ? $_REQUEST["dateofbirth"] : $res["dateofbirth"]) . "',
	imageurl = '" . (($filename1 !== "" && $filename1 !== "-") ? $filename1 : $res["imageurl"]) . "',
	address = '" . ((isset($_REQUEST["address"]) && $_REQUEST["address"] !== '') ? htmlentities($_REQUEST["address"],ENT_QUOTES) : $res["address"]) . "',
	phone = '" . $phone . "',
	class = '" . ((isset($_REQUEST["class"]) && $_REQUEST["class"] !== '') ? htmlentities($_REQUEST["class"]) : $res["class"]) . "'";
	//location_id = ". ((isset($_REQUEST["location_id"]) && intval($_REQUEST["location_id"]) > 0) ? intval($_REQUEST["location_id"]) : $res["location_id"]) .",
	//supervisoremail = '" . ((isset($_REQUEST["supervisoremail"]) && $_REQUEST["supervisoremail"] !== '') ? htmlentities($_REQUEST["supervisoremail"]) : $res["supervisoremail"]) . "',
	//supervisoremail2 = '" . ((isset($_REQUEST["supervisoremail2"]) && $_REQUEST["supervisoremail2"] !== '') ? htmlentities($_REQUEST["supervisoremail2"]) : $res["supervisoremail2"]) . "',
	//organisation_id = ". ((isset($_REQUEST["organisation_id"]) && intval($_REQUEST["organisation_id"]) > 0)  ? intval($_REQUEST["organisation_id"]) : $res["organisation_id"]). ",
	//permissions = '" . ((isset($_REQUEST["permissions"]) && $_REQUEST["permissions"] !== '' ) ? htmlentities($_REQUEST["permissions"]) : $res["permissions"]) . "'";	
	
	//exit("Values: " . $query);
	$result = $user->updateUserDetails($query, $id);
	if($result){
		echo success($result,200, "Successful","Successful");
	}else{
		echo badRequest(204, "Not successful");
	}
	
}else{
    
    $hpassword = (isset($_POST["upw"]) && $_POST["upw"] !== "") ? hash('sha256', escape($_POST["upw"])) : "BAD";
    
    $email = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) ? $_POST["email"] : "BAD";
    $phone = ((isset($_POST["phone"]) && is_numeric($_POST["phone"]) && strlen($_POST["phone"]) === 11) ? $_POST["phone"] : "BAD");
    
	$fields = "email,lastname,firstname,othernames,imageurl,address,phone,upw,class,
	permissions,status,tlog,role,dateofbirth,online";
	
	$values = "'" . $email . "',
	'" . ((isset($_REQUEST["lastname"]) && $_REQUEST["lastname"] !== '') ? htmlentities($_REQUEST["lastname"]) : '-') . "',
	'" . ((isset($_REQUEST["firstname"]) && $_REQUEST["firstname"] !== '') ? htmlentities($_REQUEST["firstname"]) : '-') . "',
	'" . ((isset($_REQUEST["othernames"]) && $_REQUEST["othernames"] !== '') ? htmlentities($_REQUEST["othernames"]) : '-') . "',
	'" . $filename1 . "',
	'" . ((isset($_REQUEST["address"]) && $_REQUEST["address"] !== '') ? htmlentities($_REQUEST["address"],ENT_QUOTES) : '-') . "',
	'" . $phone . "',
	
	'" . $hpassword . "',
	'" . ((isset($_REQUEST["class"]) && $_REQUEST["class"] !== '') ? htmlentities($_REQUEST["class"]) : '-') . "',	
	
	'" . ((isset($_REQUEST["permissions"]) && $_REQUEST["permissions"] !== '' )? htmlentities($_REQUEST["permissions"]) : '-') . "',
	'NOT VERIFIED',
	'" . $_SESSION["user_id"] . " " . date('Y-m-d H:i:s') . "',
	'STAFF',
	'" . ((isset($_REQUEST["dateofbirth"]) && $_REQUEST["dateofbirth"] !== '' )? $_REQUEST["dateofbirth"] : '2000-01-01') . "',
	'NO'";
	
	if($hpassword === "BAD" || $email === "BAD" || $phone === "BAD"){
	    //exit(success("Invalid User",201, "Invalid user or password","Invalid user or password"));
	    exit(badRequest(204, "Bad credentials"));
	}else{
	    $result = $user->registerUser($fields, $values);
	}
	
	if($result){
		echo success($result,200, "Successful","Successful");
	}else{
	    echo badRequest(204, "Registration not successful");
		//echo success($result,204, "Failed: " . $result,"ERROR"); 
	}
    
    
}

?>

