<?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'));
}

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

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

$dependentrows = ((isset($_POST["dependentrows"]) && $_POST["dependentrows"] > 0) ? intval($_POST["dependentrows"]) : 0);

$property = new Property();
if(isset($_POST['id'])){
    $res = $property->getTenantInfo("id = " . $_POST['id']);
}
if($res){
    $id = $res['id'];
    $query = "
        lastname = '" . ((isset($_POST["lastname"]) && $_POST["lastname"] !== "") ? htmlentities($_POST["lastname"],ENT_QUOTES) : $res['lastname'] ) . "',
        firstname = '" . ((isset($_POST["firstname"]) && $_POST["firstname"] !== "") ? htmlentities($_POST["firstname"],ENT_QUOTES) : $res['firstname'] ) . "',
        othernames = '" . ((isset($_POST["othernames"]) && $_POST["othernames"] !== "") ? htmlentities($_POST["othernames"],ENT_QUOTES) : $res['othernames'] ) . "',
        officeaddress = '" . ((isset($_POST["officeaddress"]) && $_POST["officeaddress"] !== "") ? htmlentities($_POST["officeaddress"],ENT_QUOTES) : $res['officeaddress'] ) . "',
        
        phone = '" . ((isset($_POST["phone"]) && $_POST["phone"] !== "") ? htmlentities($_POST["phone"],ENT_QUOTES) : $res['phone'] ) . "',
        referee1 = '" . ((isset($_POST["referee1"]) && $_POST["referee1"] !== "") ? htmlentities($_POST["referee1"],ENT_QUOTES) : $res['referee1'] ) . "',
        refereeaddress1 = '" . ((isset($_POST["refereeaddress1"]) && $_POST["refereeaddress1"] !== "") ? htmlentities($_POST["refereeaddress1"],ENT_QUOTES) : $res['refereeaddress1'] ) . "',
        refereephone1 = '" . ((isset($_POST["refereephone1"]) && $_POST["refereephone1"] !== "") ? htmlentities($_POST["refereephone1"],ENT_QUOTES) : $res['refereephone1'] ) . "',
        referee2 = '" . ((isset($_POST["referee2"]) && $_POST["referee2"] !== "") ? htmlentities($_POST["referee2"],ENT_QUOTES) : $res['referee2'] ) . "',
        refereeaddress2 = '" . ((isset($_POST["refereeaddress2"]) && $_POST["refereeaddress2"] !== "") ? htmlentities($_POST["refereeaddress2"],ENT_QUOTES) : $res['refereeaddress2'] ) . "',
        refereephone2 = '" . ((isset($_POST["refereephone2"]) && $_POST["refereephone2"] !== "") ? htmlentities($_POST["refereephone2"],ENT_QUOTES) : $res['refereephone2'] ) . "',
        
        registrationdate = '" . ((isset($_POST["registrationdate"]) && $_POST["registrationdate"] !== "") ? $_POST["registrationdate"] : $res['registrationdate'] ) . "',
        occupation = '" . ((isset($_POST["occupation"]) && $_POST["occupation"] !== "") ? htmlentities($_POST["occupation"],ENT_QUOTES) : $res['occupation'] ) . "',
        maritalstatus = '" . ((isset($_POST["maritalstatus"]) && $_POST["maritalstatus"] !== "") ? htmlentities($_POST["maritalstatus"],ENT_QUOTES) : $res['maritalstatus'] ) . "',
        placeofbirth = '" . ((isset($_POST["placeofbirth"]) && $_POST["placeofbirth"] !== "") ? htmlentities($_POST["placeofbirth"],ENT_QUOTES) : $res['placeofbirth'] ) . "',
        imageurl = '" . (($filename1 !== "-") ? $filename1 : $res['imageurl']) . "',
        status = '" . ((isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : $res['status'] ) . "'";

    $result = $property->updateTenantDetails($query, $id);

    if ($result) {
            $delrental = $property->executeByQuerySelector("DELETE FROM dependents WHERE tenantid = $id");
            $dfield = "tenantid,fullname,occupation,relationship,phone,status,tlog";
            for($i=1;$i<=$dependentrows;$i++){
                $dvalues = "$id,
                '" . ((isset($_POST["fullname" . $i]) && $_POST["fullname" . $i] !== "") ? $_POST["fullname" . $i] : "-" ) . "',
                '" . ((isset($_POST["occupation" . $i]) && $_POST["occupation" . $i] !== "") ? $_POST["occupation" . $i] : "-" ) . "',
                '" . ((isset($_POST["relationship" . $i]) && $_POST["relationship" . $i] !== "") ? $_POST["relationship" . $i] : "-" ) . "',
                '" . ((isset($_POST["phone" . $i]) && $_POST["phone" . $i] !== "") ? $_POST["phone" . $i] : "-" ) . "',
                'OPEN',
                '" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "'";
                
                $resultd = $property->registerDependent($dfield, $dvalues);
            }            
        echo success($result, 200, "Successful", "Successful");
    }else {
        echo badRequest(204, "Not successful");
    }
    
}else{
    // fields names
    $fields = "lastname,firstname,othernames,officeaddress,phone,referee1,refereeaddress1,refereephone1,referee2,
    refereeaddress2,refereephone2,registrationdate,imageurl,occupation,maritalstatus,placeofbirth,status,tlog";
    $values = "
    '" . ((isset($_POST["lastname"]) && $_POST["lastname"] !== "") ? htmlentities($_POST["lastname"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["firstname"]) && $_POST["firstname"] !== "") ? htmlentities($_POST["firstname"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["othernames"]) && $_POST["othernames"] !== "") ? htmlentities($_POST["othernames"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["officeaddress"]) && $_POST["officeaddress"] !== "") ? htmlentities($_POST["officeaddress"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["phone"]) && $_POST["phone"] !== "") ? htmlentities($_POST["phone"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["referee1"]) && $_POST["referee1"] !== "") ? htmlentities($_POST["referee1"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["refereeaddress1"]) && $_POST["refereeaddress1"] !== "") ? htmlentities($_POST["refereeaddress1"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["refereephone1"]) && $_POST["refereephone1"] !== "") ? htmlentities($_POST["refereephone1"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["referee2"]) && $_POST["referee2"] !== "") ? htmlentities($_POST["referee2"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["refereeaddress2"]) && $_POST["refereeaddress2"] !== "") ? htmlentities($_POST["refereeaddress2"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["refereephone2"]) && $_POST["refereephone2"] !== "") ? htmlentities($_POST["refereephone2"],ENT_QUOTES) : "-" ) . "',
    
    '" . ((isset($_POST["registrationdate"]) && $_POST["registrationdate"] !== "") ? $_POST["registrationdate"] : date('Y-m-d H:i:s') ) . "',
    '$filename1',
    '" . ((isset($_POST["occupation"]) && $_POST["occupation"] !== "") ? htmlentities($_POST["occupation"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["maritalstatus"]) && $_POST["maritalstatus"] !== "") ? htmlentities($_POST["maritalstatus"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["placeofbirth"]) && $_POST["placeofbirth"] !== "") ? htmlentities($_POST["placeofbirth"],ENT_QUOTES) : "-" ) . "',
    
    '" . ((isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : "OPEN" ) . "',
    '" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "'";

    $result = $tenantid = $property->registerTenant($fields, $values);
    if($result){
        
            $dfield = "tenantid,fullname,occupation,relationship,phone,status,tlog";
            for($i=1;$i<=$dependentrows;$i++){
                $dvalues = "$tenantid,
                '" . ((isset($_POST["fullname" . $i]) && $_POST["fullname" . $i] !== "") ? htmlentities($_POST["fullname" . $i],ENT_QUOTES) : "-" ) . "',
                '" . ((isset($_POST["occupation" . $i]) && $_POST["occupation" . $i] !== "") ? htmlentities($_POST["occupation" . $i],ENT_QUOTES) : "-" ) . "',
                '" . ((isset($_POST["relationship" . $i]) && $_POST["relationship" . $i] !== "") ? htmlentities($_POST["relationship" . $i],ENT_QUOTES) : "-" ) . "',
                '" . ((isset($_POST["phone" . $i]) && $_POST["phone" . $i] !== "") ? htmlentities($_POST["phone" . $i],ENT_QUOTES) : "-" ) . "',
                'OPEN',
                '" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "'";
                
                $resultd = $property->registerDependent($dfield, $dvalues);
            }        
        echo success($result, 200, "Successful", "Successful");
    }else{
        echo badRequest(204, "Not successful");
    }
}
