<?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->getMoreFeesInfo("id = " . $_POST['id']);
}
if($res){
    $id = $res['id'];

    //$resultdelete = $property->executeByQuerySelector("DELETE FROM morefees WHERE id = $id");
    $fields2 = "feename,amount,status";
    $values2 = "
    feename = '" . ((isset($_POST["feename"]) && $_POST["feename"] !== "") ? htmlentities(strtoupper($_POST["feename"]),ENT_QUOTES) : $res["feename"] ) . "',
    mode = '" . ((isset($_POST["mode"]) && $_POST["mode"] !== "") ? $_POST["mode"] : $res["mode"]  ) . "',
    amount = " . ((isset($_POST["amount"]) && $_POST["amount"] > 0) ? $_POST["amount"] : 0 );
    
    $resultunit = $property->updateMoreFeesDetails($values2, $id);
    if($resultunit){        
        echo success($result, 200, "Successful", "Successful");
    }else {
        echo badRequest(204, "Not successful");
    }
    
}else{
    
    $fields2 = "feename,amount,mode,status";
    //$lastid = $property->getLastID();
    //for($i=1;$i<=$rowcount;$i++){
        $values2 = "
        '" . ((isset($_POST["feename"]) && $_POST["feename"] !== "") ? htmlentities(strtoupper($_POST["feename"]),ENT_QUOTES) : "AGREEMENT FEE" ) . "',
        " . ((isset($_POST["amount"]) && $_POST["amount"] > 0) ? $_POST["amount"] : 0 ) . ",
        '" . ((isset($_POST["mode"]) && $_POST["mode"] !== "") ? $_POST["mode"] : "FLAT" ) . "',
        '" . ((isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : "OPEN" ) . "'";
        
        $resultunit = $property->registerMoreFees($fields2, $values2);
    //}
     
    if($resultunit){   
        echo success($result, 200, "Successful", "Successful");
    }else{
        echo badRequest(204, "Not successful");
    }
}
