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

$rowcount = ((isset($_POST["rowcount"]) && $_POST["rowcount"] > 0) ? intval($_POST["rowcount"]) : 0);
if($rowcount == 0){
    exit(badRequest(204, "Not successful. Property units not added. Rowcount for property units is zero"));
}

$property = new Property();
if(isset($_POST['id'])){
    $res = $property->getPropertyInfo("id = " . $_POST['id']);
}

if($res){
    $id = $res['id'];
    $query = "
        propertyname = '" . ((isset($_POST["propertyname"]) && $_POST["propertyname"] !== "") ? htmlentities(strtoupper($_POST["propertyname"]),ENT_QUOTES) : $res['propertyname'] ) . "',
        address = '" . ((isset($_POST["address"]) && $_POST["address"] !== "") ? htmlentities($_POST["address"],ENT_QUOTES) : $res['address'] ) . "',
        location = '" . ((isset($_POST["location"]) && $_POST["location"] !== "") ? htmlentities($_POST["location"],ENT_QUOTES) : $res['location'] ) . "',
        city = '" . ((isset($_POST["city"]) && $_POST["city"] !== "") ? htmlentities($_POST["city"],ENT_QUOTES) : $res['city'] ) . "',
        state = '" . ((isset($_POST["state"]) && $_POST["state"] !== "") ? htmlentities($_POST["state"],ENT_QUOTES) : $res['state'] ) . "',
        typeofunits = '" . ((isset($_POST["typeofunits"]) && $_POST["typeofunits"] !== "") ? htmlentities($_POST["typeofunits"],ENT_QUOTES) : $res['typeofunits'] ) . "',
        propertymanager = '" . ((isset($_POST["propertymanager"]) && $_POST["propertymanager"] !== "") ? htmlentities($_POST["propertymanager"],ENT_QUOTES) : $res['propertymanager'] ) . "',
        numberofunits = " . ((isset($_POST["numberofunits"]) && $_POST["numberofunits"] > 0) ? $_POST["numberofunits"] : $res['numberofunits'] ) . ",
        status = '" . ((isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : $res['status'] ) . "'";

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

    if ($result) {
        //$resultdelete = $property->executeByQuerySelector("DELETE FROM propertyunit WHERE propertyid = $id");
        
        $fields2 = "propertyid,unitname,rent,rented,feenameid,amount,status,renewable,tlog,rentalperiod";
        
        for($i=1;$i<=$rowcount;$i++){
            
            if(isset($_POST["unitid" . $i]) && $_POST["unitid" . $i] > 0){
                $resultunitres = $property->getPropertyUnitInfo("id = " . $_POST["unitid" . $i]);
                if($resultunitres["rented"] === "NO"){
                    $queryunits = "feenameid = " . ((isset($_POST["feenameid".$i]) && $_POST["feenameid".$i] > 0) ? $_POST["feenameid".$i] : $resultunitres["feenameid"] ) . ",
                    unitname = '" . ((isset($_POST["unitname" . $i]) && $_POST["unitname".$i] !== "") ? htmlentities(strtoupper($_POST["unitname".$i]),ENT_QUOTES) : $resultunitres["unitname"] ) . "',
                    amount = " . ((isset($_POST["amount".$i]) && $_POST["amount".$i] > 0) ? $_POST["amount".$i] : $resultunitres["amount"]) . ",
                    rentalperiod = " . ((isset($_POST["rentalperiod".$i]) && $_POST["rentalperiod".$i] > 0) ? $_POST["rentalperiod".$i] : $resultunitres["rentalperiod"]);
                    
                    $resultunitresup = $property->updatePropertyUnitDetails($queryunits, $_POST["unitid" . $i]);
                }
            }else{
                //$avalas = "";
                $resfeenam = $property->executeByQuerySelector("SELECT feename FROM morefees WHERE id = " . $_POST["feenameid".$i]);
                $annualrent = 0;
                $renewable = ((isset($_POST["renewable"]) && $_POST["renewable"] !== "") ? $_POST["renewable"] : "NO" );
                if (str_contains(strtoupper($resfeenam[0]["feename"]), "RENT")) {
                //if($resfeenam[0]["feename"] === "ANNUAL RENT"){
                    $annualrent = $_POST["amount".$i];
                    $renewable = "YES";
                }
                $values2 = "$id,
                '" . ((isset($_POST["unitname" . $i]) && $_POST["unitname".$i] !== "") ? htmlentities(strtoupper($_POST["unitname".$i]),ENT_QUOTES) : "FLAT" ) . "',
                $annualrent,
                'NO',
                " . ((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',
                '" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "',
                " . ((isset($_POST["rentalperiod".$i]) && $_POST["rentalperiod".$i] > 0) ? $_POST["rentalperiod".$i] : 0 );
                
                //$avalas .= $values2;
                $resultunit = $property->registerPropertyUnit($fields2, $values2);
            }
        }
        //exit("Values: $avalas");
        echo success($result, 200, "Successful", "Successful");
    }else {
        echo badRequest(204, "Not successful");
    }
    
}else{
    
    $flag = true;
    do{
        $propertyidno = mt_rand(100000,999999);
        $resprp = $property->executeByQuerySelector("SELECT propertyidno FROM property WHERE propertyidno = '$propertyidno' LIMIT 1");
        if($resprp){
            if(!empty($resprp[0]["propertyidno"])){
                $flag = false;
            }
        }
    }while($flag == false);
    
    // fields names
    $fields = "propertyname,address,city,state,numberofunits,typeofunits,propertymanager,status,propertyidno,location,tlog";
    $values = "
    '" . ((isset($_POST["propertyname"]) && $_POST["propertyname"] !== "") ? htmlentities(strtoupper($_POST["propertyname"]),ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["address"]) && $_POST["address"] !== "") ? htmlentities($_POST["address"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["city"]) && $_POST["city"] !== "") ? htmlentities($_POST["city"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["state"]) && $_POST["state"] !== "") ? htmlentities($_POST["state"],ENT_QUOTES) : "-" ) . "',
    " . ((isset($_POST["numberofunits"]) && $_POST["numberofunits"] > 0) ? $_POST["numberofunits"] : 0 ) . ",
    '" . ((isset($_POST["typeofunits"]) && $_POST["typeofunits"] !== "") ? htmlentities($_POST["typeofunits"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["propertymanager"]) && $_POST["propertymanager"] !== "") ? htmlentities($_POST["propertymanager"],ENT_QUOTES) : "-" ) . "',
    '" . ((isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : "OPEN" ) . "',
    '$propertyidno',
    '" . ((isset($_POST["location"]) && $_POST["location"] !== "") ? htmlentities($_POST["location"],ENT_QUOTES) : "-" ) . "',
    '" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "'";

    $result = $property->registerProperty($fields, $values);
    if($result){
        $fields2 = "propertyid,unitname,rent,rented,feenameid,amount,status,renewable,tlog,rentalperiod";
        $lastid = $property->getLastID();
        
        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" );
            //if($resfeenam[0]["feename"] === "ANNUAL RENT"){
            if (str_contains(strtoupper($resfeenam[0]["feename"]), "RENT")){
                $annualrent = $_POST["amount".$i];
                $renewable = "YES";
            }
            $values2 = "$lastid,
            '" . ((isset($_POST["unitname" . $i]) && $_POST["unitname".$i] !== "") ? htmlentities(strtoupper($_POST["unitname".$i]),ENT_QUOTES) : "FLAT" ) . "',
            $annualrent,
            'NO',
            " . ((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',
            '" . $_SESSION["wuseremail"] . " | " . date("Y-m-d H:i:s") . "',
            " . ((isset($_POST["rentalperiod".$i]) && $_POST["rentalperiod".$i] > 0) ? $_POST["rentalperiod".$i] : 0 );
            
            $resultunit = $property->registerPropertyUnit($fields2, $values2);
        }
        
        echo success($result, 200, "Successful", "Successful");
    }else{
        echo badRequest(204, "Not successful");
    }
}
