<?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';
require_once '../model/organisationinfo.php';
require_once '../model/glaccount.php';

date_default_timezone_set('Africa/Lagos');

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


$organisation = new OrganisationInfo();
$organisationres = $organisation->retrieveOrganisationByQuery("companyname NOT LIKE '-'", 1, 1);
$recaccount = $organisationres["default_receivableaccount"];

$glaccount = new GLAccount();
$glres = $glaccount->getGLAccountInfo("accountnumber = '$recaccount'");

//for tenant photo
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';	    
	}
}


$property = new Property();

$propertyid = ((isset($_POST["propertyid"]) && $_POST["propertyid"] > 0) ? intval($_POST["propertyid"]) : -1);
$unitid = ((isset($_POST["unitid"]) && $_POST["unitid"] > 0) ? intval($_POST["unitid"]) : -1);
$tenantid = ((isset($_POST["tenantid"]) && $_POST["tenantid"] > 0) ? intval($_POST["tenantid"]) : -1);
$tenant = ((isset($_POST["tenant"]) && $_POST["tenant"] !== "") ? $_POST["tenant"] : "NO");
$amountpaid = ((isset($_POST["amountpaid"]) && $_POST["amountpaid"] > 0) ? $_POST["amountpaid"] : 0);
$otherfees = ((isset($_POST["otherfees"]) && $_POST["otherfees"] > 0) ? $_POST["otherfees"] : 0);
$rowcount = ((isset($_POST["rowcount"]) && $_POST["rowcount"] > 0) ? intval($_POST["rowcount"]) : 0);
$dependentrows = ((isset($_POST["dependentrows"]) && $_POST["dependentrows"] > 0) ? intval($_POST["dependentrows"]) : 0);
$lastname = (isset($_POST["lastname"]) && $_POST["lastname"] !== "") ? htmlentities($_POST["lastname"],ENT_QUOTES) : "-";
if($rowcount == 0){
    exit(badRequest(204, "Not successful. Property units not added. Rowcount for property units is zero"));
}

if($propertyid == -1 || $unitid == -1 || $amountpaid == 0){
    exit(badRequest(204,'Not successful. Property or unit or annual rent or amount paid may not be available'));
}
if($lastname === "-"){
    if($tenantid == -1){
        exit(badRequest(204,'Not successful. Tenant may not be available'));
    }
    $tenant = "NO";
}else{
    $tenant = "YES";
}
$resultunit = $property->getPropertyUnitInfo("id = $unitid");
if($resultunit){
    $annualrent = ((isset($_POST["rent"]) && $_POST["rent"] > 0) ? $_POST["rent"] : $resultunit["rent"]);
}else{
    exit(badRequest(204,'Not successful. We could not find this unit'));
}
if($resultunit["rented"] === "YES"){
    exit(badRequest(204,'Not successful. This unit is already rented and not available.'));
}
$ref = (isset($_POST["reference"]) && $_POST["reference"] !== "") ? htmlentities($_POST["reference"],ENT_QUOTES) : mt_rand(100000000,999999999999 ) ;
if(isset($_POST['id']) || !empty($_POST['id'])){
    $res = $property->getRentAPropertyInfo("id = " . $_POST['id']);
}
if($res){
    $id = $res['id'];
    $resref = $res['reference'];
    $query = "
        propertyid = " . ((isset($_POST["propertyid"]) && $_POST["propertyid"] > 0) ? $_POST["propertyid"] : $res['propertyid'] ) . ",
        unitid = " . ((isset($_POST["unitid"]) && $_POST["unitid"] > 0) ? $_POST["unitid"] : $res['unitid'] ) . ",
        tenantid = " . ((isset($_POST["tenantid"]) && $_POST["tenantid"] > 0) ? $_POST["tenantid"] : $res['tenantid'] ) . ",
        
        begindate = '" . ((isset($_POST["begindate"]) && $_POST["begindate"] !== "") ? $_POST["begindate"] : $res['begindate'] ) . "',
        expirationdate = '" . ((isset($_POST["expirationdate"]) && $_POST["expirationdate"] !== "") ? $_POST["expirationdate"] : $res['expirationdate'] ) . "',
        paymentdate = '" . ((isset($_POST["paymentdate"]) && $_POST["paymentdate"] !== "") ? $_POST["paymentdate"] : $res['paymentdate'] ) . "',
        
        rent = " . ((isset($_POST["rent"]) && $_POST["rent"] > 0) ? $_POST["rent"] : $res['rent'] ) . ",
        otherfees = " . ((isset($_POST["otherfees"]) && $_POST["otherfees"] > 0) ? $_POST["otherfees"] : 0 ) . ",
        amountpaid = " . ((isset($_POST["amountpaid"]) && $_POST["amountpaid"] > 0) ? $_POST["amountpaid"] : $res['tenantid'] ) . ",
        
        otherfeesdescription = '" . ((isset($_POST["otherfeesdescription"]) && $_POST["otherfeesdescription"] !== "") ? htmlentities($_POST["otherfeesdescription"],ENT_QUOTES) : $res['otherfeesdescription'] ) . "',
        status = '" . ((isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : $res['status'] ) . "'";

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

    if ($result) {
        //$delrental = $property->executeByQuerySelector("DELETE FROM rentedproperty WHERE id = $id");
        $resdelete = $property->executeByQuerySelector("DELETE FROM accounts WHERE reference = '$resref'");
        
        $fields2 = "rentalid,feenameid,amount,status,renewable,unitid,tlog";
        $otherfeesname = "";
        $otherfees = 0;
        
        $pres = $property->getPropertyInfo("id = $propertyid");
        $presunit = $property->getPropertyUnitInfo("id = $unitid");
        
        for($i=1;$i<=$rowcount;$i++){
            $resfeenam = $property->executeByQuerySelector("SELECT feename FROM morefees WHERE id = " . $_POST["feenameid".$i]);
            $annualrent = 0;
            //$renewable = ((isset($_POST["renewable"]) && $_POST["renewable"] !== "") ? $_POST["renewable"] : "NO" );
            $renewable = ((isset($_POST["renewable" . $i]) && $_POST["renewable" . $i] !== "") ? $_POST["renewable" . $i] : "NO" );
            if (str_contains(strtoupper($resfeenam[0]["feename"]), "RENT")){
            //if($resfeenam[0]["feename"] === "ANNUAL RENT"){
                $annualrent = $_POST["amount".$i];
                $renewable = "YES";
            }else{
                $otherfeesname .= strtoupper($resfeenam[0]["feename"]) . "/";
                $otherfees += $_POST["amount".$i];
            }
            $values2 = "$id,
            " . ((isset($_POST["feenameid".$i]) && $_POST["feenameid".$i] > 0) ? $_POST["feenameid".$i] : 0 ) . ",
            " . ((isset($_POST["amount".$i]) && $_POST["amount".$i] > 0) ? $_POST["amount".$i] : 0 ) . ",
            '" . ((isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : "OPEN" ) . "',
            '$renewable',
            " . $unitid . ",
            '" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "'";
            
            $resultrentalfees = $property->registerRentalFees($fields2, $values2);
            
            
            $description = "Fee: " . $resfeenam[0]["feename"] . " | " . $pres["propertyname"] . " unit: " . $presunit["unitname"];
            $debit = $_POST["amount".$i]; //$annualrent + $otherfees;
            $feenameid = $_POST["feenameid".$i];
            
            $fields2 = "accountnumber,accountname,description,ownerid,debit,credit,transactiondate,reference,feenameid,propertyid,status,tlog,user";
            $values2 = "'$recaccount','" . $glres["accountname"] . "','$description',$tenantid,$debit,$amountpaid,
            '" . ((isset($_POST["paymentdate"]) && $_POST["paymentdate"] !== "") ? $_POST["paymentdate"] : date('Y-m-d H:i:s') ) . "',
            '$ref',
            $feenameid,
            $propertyid,
            '" . ((isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : "OPEN" ) . "',
            '" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "',
            '" . $_SESSION['wuseremail'] . "'";
            
            $resultaccounts = $property->registerAccount($fields2, $values2);
            
        }

        $resproperty = $property->executeByQuerySelector("UPDATE propertyunit SET rented = 'YES' WHERE id = $unitid");
        $updaterental = $property->executeByQuerySelector("UPDATE rentedproperty SET otherfees=$otherfees,otherfeesdescription='$otherfeesname',rent=$annualrent WHERE id = $id");
        
        /*
        $pres = $property->getPropertyInfo("id = $propertyid");
        $presunit = $property->getPropertyUnitInfo("id = $unitid");
        $description = "Rent: " . $pres["propertyname"] . " unit: " . $presunit["unitname"];
        $debit = $annualrent + $otherfees;
        
        $fields2 = "accountname,description,ownerid,debit,credit,transactiondate,reference,status,tlog";
        $values2 = "'RECEIVABLES','$description',$tenantid,$debit,$amountpaid,
        '" . ((isset($_POST["paymentdate"]) && $_POST["paymentdate"] !== "") ? $_POST["paymentdate"] : date('Y-m-d H:i:s') ) . "',
        '$ref',
        '" . ((isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : "OPEN" ) . "',
        '" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "'";
        
        $resultaccounts = $property->registerAccount($fields2, $values2);
        $resproperty = $property->executeByQuerySelector("UPDATE propertyunit SET rented = 'YES' WHERE id = $unitid");
        */
        
        echo success($result, 200, "Successful", "Successful");
    }else {
        echo badRequest(204, "Not successful");
    }
    
}else{
    if($tenant === "YES"){
        // 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") . "'";
    
        $tenantid = $resulttenant = $property->registerTenant($fields, $values);
        
        
 
        //exit("dependentrows: $dependentrows values: $dvalues");
    }
    
    if($tenantid && $dependentrows > 0){
        $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($resulttenant, 200, "Successful", "Successful");
    }else{
        //echo badRequest(204, "Not successful");
    }   
        
    // fields names
    $fields = "propertyid,unitid,tenantid,begindate,expirationdate,paymentdate,rent,otherfees,
    otherfeesdescription,amountpaid,reference,status,tlog";
    $values = "
    " . ((isset($_POST["propertyid"]) && $_POST["propertyid"] > 0) ? $_POST["propertyid"] : -1) . ",
    " . ((isset($_POST["unitid"]) && $_POST["unitid"] > 0) ? $_POST["unitid"] : -1) . ",
    " . $tenantid . ",
    '" . ((isset($_POST["begindate"]) && $_POST["begindate"] !== "") ? $_POST["begindate"] : date('Y-m-d') ) . "',
    '" . ((isset($_POST["expirationdate"]) && $_POST["expirationdate"] !== "") ? $_POST["expirationdate"] : date('Y-m-d') ) . "',
    '" . ((isset($_POST["paymentdate"]) && $_POST["paymentdate"] !== "") ? $_POST["paymentdate"] : date('Y-m-d H:i:s') ) . "',
    
    " . ((isset($_POST["rent"]) && $_POST["rent"] > 0) ? $_POST["rent"] : 0) . ",
    " . ((isset($_POST["otherfees"]) && $_POST["otherfees"] > 0) ? $_POST["otherfees"] : 0) . ",
    '" . ((isset($_POST["otherfeesdescription"]) && $_POST["otherfeesdescription"] !== "") ? htmlentities($_POST["otherfeesdescription"],ENT_QUOTES) : "-" ) . "',
    " . ((isset($_POST["amountpaid"]) && $_POST["amountpaid"] > 0) ? $_POST["amountpaid"] : 0) . ",
    '$ref',
    '" . ((isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : "OPEN" ) . "',
    '" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "'";

    $result = $property->registerRentAProperty($fields, $values);
    if($result){
        
        $pres = $property->getPropertyInfo("id = $propertyid");
        $presunit = $property->getPropertyUnitInfo("id = $unitid");
        
        
        $otherfeesname = "";
        $otherfees = 0;
        for($i=1;$i<=$rowcount;$i++){
            $fields2 = "rentalid,feenameid,amount,status,renewable,unitid,tlog,discount";
            if(!isset($_POST["feenameid".$i])){
                continue;
            }
            $resfeenam = $property->executeByQuerySelector("SELECT feename FROM morefees WHERE id = " . $_POST["feenameid".$i]);
            $annualrent = 0;
            $renewable = ((isset($_POST["renewable" . $i]) && $_POST["renewable" . $i] !== "") ? $_POST["renewable" . $i] : "NO" );
            if (str_contains(strtoupper($resfeenam[0]["feename"]), "RENT")){
            //if($resfeenam[0]["feename"] === "ANNUAL RENT"){
                $annualrent = $_POST["amount".$i];
                $renewable = "YES";
            }else{
                $otherfeesname .= strtoupper($resfeenam[0]["feename"]) . "/";
                $otherfees += $_POST["amount".$i];
            }
            $values2 = "$result,
            " . ((isset($_POST["feenameid".$i]) && $_POST["feenameid".$i] > 0) ? $_POST["feenameid".$i] : 0 ) . ",
            " . ((isset($_POST["amount".$i]) && $_POST["amount".$i] > 0) ? $_POST["amount".$i] : 0 ) . ",
            '" . ((isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : "OPEN" ) . "',
            '$renewable',
            " . $unitid . ",
            '" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "',
            " . ((isset($_POST["discount".$i]) && $_POST["discount".$i] > 0) ? $_POST["discount".$i] : 0 );
            
            $resultrentalfees = $property->registerRentalFees($fields2, $values2);
            
            $description = "Fee: " . $resfeenam[0]["feename"] . " | " . $pres["propertyname"] . " unit: " . $presunit["unitname"];
            $debit = $_POST["amount".$i]; //$annualrent + $otherfees;
            $feenameid = $_POST["feenameid".$i];
            
            $fields2 = "accountnumber,accountname,description,ownerid,debit,credit,transactiondate,reference,feenameid,propertyid,status,tlog,discount,user";
            $values2 = "'$recaccount','" . $glres["accountname"] . "','$description',$tenantid,$debit,
            " . ((isset($_POST["deposit".$i]) && $_POST["deposit".$i] > 0) ? $_POST["deposit".$i] : 0 ) . ",
            '" . ((isset($_POST["paymentdate"]) && $_POST["paymentdate"] !== "") ? $_POST["paymentdate"] : date('Y-m-d H:i:s') ) . "',
            '$ref',
            $feenameid,
            $propertyid,
            '" . ((isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : "OPEN" ) . "',
            '" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "',
            " . ((isset($_POST["discount".$i]) && $_POST["discount".$i] > 0) ? $_POST["discount".$i] : 0 ) . ",
            '" . $_SESSION['wuseremail'] . "'";
             
            $resultaccounts = $property->registerAccount($fields2, $values2);
        }

        $updaterental = $property->executeByQuerySelector("UPDATE rentedproperty SET otherfees=$otherfees,otherfeesdescription='$otherfeesname',rent=$annualrent WHERE id = $result");
        $resproperty = $property->executeByQuerySelector("UPDATE propertyunit SET rented = 'YES' WHERE id = $unitid");
        
        
        /*
        $pres = $property->getPropertyInfo("id = $propertyid");
        $presunit = $property->getPropertyUnitInfo("id = $unitid");
        $description = "Rent: " . $pres["propertyname"] . " unit: " . $presunit["unitname"];
        $fields2 = "accountname,description,ownerid,debit,credit,transactiondate,reference,status,tlog";
        $debit = $annualrent + $otherfees;
        $values2 = "'RECEIVABLES','$description',$tenantid,$debit,$amountpaid,
        '" . ((isset($_POST["paymentdate"]) && $_POST["paymentdate"] !== "") ? $_POST["paymentdate"] : date('Y-m-d H:i:s') ) . "',
        '$ref',
        '" . ((isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : "OPEN" ) . "',
        '" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "'";
        */
        
        
        
        echo success($result, 200, "Successful", "Successful");
    }else{
        echo badRequest(204, "Not successful");
    }
}
