<?php
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/Property.php';
date_default_timezone_set('Africa/Lagos');

if ($_SESSION['wuseremail'] === null || !isset($_SESSION['wuseremail'])) {
     exit(badRequest(204,'Invalid session data. Proceed to login'));
}

$tenantid = (isset($_POST["tenantid"]) && $_POST["tenantid"] > 0) ? $_POST["tenantid"] : 0;
if($tenantid == 0){
    exit(badRequest(204, "Tenant id is invalid"));
}

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

$returnvalue = '';
if($_POST["document"] !== null && $_POST["document"] !== "-"){	
	$allowedExts = array("gif", "jpeg", "jpg","pdf","png");
	$temp = explode(".", $_FILES["document"]["name"]);
	$returnvalue .= '' . $_FILES["document"]["name"];
	$extension = end($temp);
	if ((($_FILES["document"]["type"] === "image/gif") || ($_FILES["document"]["type"] === "image/jpeg") || ($_FILES["document"]["type"] === "image/jpg") || ($_FILES["document"]["type"] === "image/pjpeg") || ($_FILES["document"]["type"] === "image/png") || ($_FILES["document"]["type"] === "application/pdf")) && in_array($extension, $allowedExts)){
		if ($_FILES["document"]["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["document"]["tmp_name"],"../images/" . $filename1);
				$returnvalue .= "Upload Successful";
  		    //}
		}
	}else{
         $returnvalue .= ' | Invalid file type';	    
	}
}

$property = new Property();
// fields names
$fields = "tenantid,description,document,tlog";
$values = "" . $tenantid . ",
'" . ((isset($_POST["description"]) && $_POST["description"] !== "") ? htmlentities($_POST["description"],ENT_QUOTES) : "-" ) . "',
'$filename1',
'" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "'";

$result = $property->registerTenancyDocs($fields, $values);
if($result){
    echo success($result, 200, "Successful", "Successful");
}else{
    echo badRequest(204, "Not successful");
}

