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

date_default_timezone_set('Africa/Lagos');

if ($_SESSION['wuseremail'] === null || !isset($_SESSION['wuseremail'])) {
     exit(badRequest(204,'Invalid session data. Proceed to login'));
}
$permissions = explode("|",$_SESSION["permissions"]);
if(in_array("NO POSTING",$permissions)){
    exit(badRequest(204,'No posting enabled'));
}

//validate authorisation
$user = new User();

$password = ((isset($_POST["approvingofficer"]) && $_POST["approvingofficer"] !== "") ? hash('sha256',escape($_POST["approvingofficer"])) : "-" );
if($password === "-"){
    //exit(badRequest('Authorisation is invalid'));
}
if($_SESSION['role'] === "SUPERADMIN"){
    $userresult = $user->retrieveByQuerySelector("SELECT * FROM users WHERE upw = '$password'");
}else{
    $userresult = $user->retrieveByQuerySelector("SELECT * FROM users WHERE upw = '$password' AND email NOT LIKE '" . $_SESSION['hemsemail'] . "'");
}
if(!$userresult){
    //exit(badRequest('Authorisation is invalid'));
}

$transaction = new Transaction();
//$tresult = $transaction->executeTransactionByQuerySelector("SELECT * FROM tdetail ORDER BY id DESC");
//$currentid = $tresult[0]["id"] + 1;
$cdate = date('Y-m-d H:i:s');
$ref = strtotime($cdate) . "|" . mt_rand(1000000000,9999999999);

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


$glaccount = new GLAccount();
$glres = $glaccount->getGLAccountInfo("accountnumber = '" . $_POST['accountnumber'] . "'");

//$accountname = $glres["accountname"];
$debittotal = ((isset($_REQUEST["debittotal"]) && $_REQUEST["debittotal"] > 0) ? $_REQUEST["debittotal"] : 0 );
$credittotal = ((isset($_REQUEST["credittotal"]) && $_REQUEST["credittotal"] > 0) ? $_REQUEST["credittotal"] : 0 );
$customertotal = ((isset($_REQUEST["customertotal"]) && $_REQUEST["customertotal"] > 0) ? $_REQUEST["customertotal"] : 0 );
if($debittotal !== $credittotal || $credittotal === 0 || $debittotal === 0){
    exit(badRequest(204, "Not successful. Totals are not equal"));
}

//$fields = "accountnumber,transactiondate,location,credit,debit,valuedate,description,marketer,accountofficer,approvedby,
//user,status,ttype,servicecharge,debittotal,credittotal,reference,bankpaywith100,whichaccount,ownerid,paymentmethod,tlog";

$debitgridsize = (isset($_POST["debitgridsize"]) && $_POST["debitgridsize"] > 0) ? $_POST["debitgridsize"] : 0;
$creditgridsize = (isset($_POST["creditgridsize"]) && $_POST["creditgridsize"] > 0) ? $_POST["creditgridsize"] : 0;
$customergridsize = (isset($_POST["customergridsize"]) && $_POST["customergridsize"] > 0) ? $_POST["customergridsize"] : 0;

if($creditgridsize == 0 || $debitgridsize == 0){
    exit(badRequest(204, "Not successful. The gridsizes are zero"));
}
if($customergridsize > 0 && ($creditgridsize < 1 || $debitgridsize < 1)){
    //exit(badRequest(204, "Not successful. The contra entries do not match"));
}

$fields = "accountnumber,accountname,description,ownerid,credit,debit,transactiondate,reference,feenameid,propertyid,
status,tlog,discount,user,ttype,otherdetail,paymentmethod";

if($debitgridsize > 0){
    $acctss = "";
    for($i=0;$i<$debitgridsize;$i++){
        $accountnumber = ((isset($_REQUEST["debitaccount" . $i]) && $_REQUEST["debitaccount" . $i] !== "") ? $_REQUEST["debitaccount" . $i] : "-" );
        $glres = $glaccount->getGLAccountInfo("accountnumber = '$accountnumber'");
        $accountname = $glres["accountname"];
        
        $acctss .= $accountnumber . " ";
        if($accountnumber === "-"){
            exit(badRequest(204, "Not successful. Bad debit account info"));
        }        
        $values = "'" . $accountnumber . "','$accountname',
        '" . ((isset($_REQUEST["description"]) && $_REQUEST["description"] !== "") ? strtoupper(htmlentities($_REQUEST["description"],ENT_QUOTES)) : "GL Posting" ) . "',
        " . ((isset($_POST["ownerid"]) && $_POST["ownerid"] > 0) ? $_POST["ownerid"] : -1 ) . ",
        0,
        " . ((isset($_POST["debitamount" . $i]) && $_POST["debitamount" . $i] > 0) ? $_POST["debitamount" . $i] : 0 ) . ",
        '" . ((isset($_REQUEST["transactiondate"]) && $_REQUEST["transactiondate"] !== "") ? $_REQUEST["transactiondate"] : date('Y-m-d') ) . "',
        '" . $ref . "',
        0,
        0,'POSTED',
        '" . $_SESSION['wuseremail'] . " " . date('Y-m-d H:i:s') . "',
        0,
        '" . $_SESSION['wuseremail'] . "',
        'GLACCOUNT',
        '-',
        '" . ((isset($_REQUEST["paymentmethod"]) && $_REQUEST["paymentmethod"] !== "") ? strtoupper(htmlentities($_REQUEST["paymentmethod"],ENT_QUOTES)) : "NONCASH" ) . "'";
        
        //exit("Values: " . $values);
        $result = $transaction->registerTransaction($fields, $values);
        $userres = $user->addUserActivity($_SESSION["hemsemail"], $_SESSION["hemsemail"] . " posted GL transactions: $acctss at " . date("Y-m-d H:i:s"), date("Y-m-d H:i:s"), "GL");
    }
}

if($creditgridsize > 0){
    $acctss = "";
    for($i=0;$i<$creditgridsize;$i++){
        
        $accountnumber = ((isset($_REQUEST["creditaccount" . $i]) && $_REQUEST["creditaccount" . $i] !== "") ? $_REQUEST["creditaccount" . $i] : "-" );
        $glres = $glaccount->getGLAccountInfo("accountnumber = '$accountnumber'");
        $accountname = $glres["accountname"];
        
        $acctss .= $accountnumber . " ";
        if($accountnumber === "-"){
            exit(badRequest(204, "Not successful. Bad credit account info"));
        }        
        $values = "'" . $accountnumber . "','$accountname',
        '" . ((isset($_REQUEST["description"]) && $_REQUEST["description"] !== "") ? strtoupper(htmlentities($_REQUEST["description"],ENT_QUOTES)) : "GL Posting" ) . "',
        " . ((isset($_POST["ownerid"]) && $_POST["groupid"] > 0) ? $_POST["ownerid"] : -1 ) . ",
        " . ((isset($_POST["creditamount" . $i]) && $_POST["creditamount" . $i] > 0) ? $_POST["creditamount" . $i] : 0 ) . ",
        0,
        '" . ((isset($_REQUEST["transactiondate"]) && $_REQUEST["transactiondate"] !== "") ? $_REQUEST["transactiondate"] : date('Y-m-d') ) . "',
        '" . $ref . "',
        0,0,'POSTED',
        '" . $_SESSION['wuseremail'] . " " . date('Y-m-d H:i:s') . "',
        0,
        '" . $_SESSION['wuseremail'] . "',
        'GLACCOUNT',
        '-',
        '" . ((isset($_REQUEST["paymentmethod"]) && $_REQUEST["paymentmethod"] !== "") ? strtoupper(htmlentities($_REQUEST["paymentmethod"],ENT_QUOTES)) : "NONCASH" ) . "'";        
        
        //exit("Values: " . $values);
        $result = $transaction->registerTransaction($fields, $values);
        $userres = $user->addUserActivity($_SESSION["hemsemail"], $_SESSION["hemsemail"] . " posted GL transactions: $acctss at " . date("Y-m-d H:i:s"), date("Y-m-d H:i:s"), "GL");
    }
}

$transactiontype = ((isset($_REQUEST["transactiontype"]) && $_REQUEST["transactiontype"] !== "") ? $_REQUEST["transactiontype"] : "-" );
if($customergridsize > 0){
    $acctss = "";
    for($i=0;$i<$customergridsize;$i++){
        
        $accountnumber = ((isset($_REQUEST["customeraccount" . $i]) && $_REQUEST["customeraccount" . $i] !== "") ? $_REQUEST["customeraccount" . $i] : "-" );
        $acctss .= $accountnumber . " ";
        if($accountnumber === "-" || $transactiontype === "-"){
            exit(badRequest(204, "Not successful. Bad customer account or transaction type info"));
        }        
        $values = "'" . $accountnumber . "',
        '" . ((isset($_REQUEST["transactiondate"]) && $_REQUEST["transactiondate"] !== "") ? $_REQUEST["transactiondate"] : date('Y-m-d') ) . "',
        " . $_SESSION["location_id"] . ",
        " . ((isset($_POST["customeramount" . $i]) && $_POST["transactiontype"] === "CREDIT") ? $_POST["customeramount" . $i] : 0 ) . ",
        " . ((isset($_POST["customeramount" . $i]) && $_pOST["transactiontype"] === "DEBIT") ? $_POST["customeramount" . $i] : 0 ) . ",
        '" . ((isset($_REQUEST["transactiondate"]) && $_REQUEST["transactiondate"] !== "") ? $_REQUEST["transactiondate"] : date('Y-m-d') ) . "',
        '" . ((isset($_REQUEST["description"]) && $_REQUEST["description"] !== "") ? strtoupper(htmlentities($_REQUEST["description"],ENT_QUOTES)) : "GL Posting" ) . "',
        " . ((isset($_POST["marketer"]) && $_POST["marketer"] > 0) ? $_POST["marketer"] : -1 ) . ",
        '" . ((isset($_POST["accountofficer"]) && $_POST["accountofficer"] > 0) ? $_POST["accountofficer"] : "-" ) . "',
        '" . $_SESSION['hemsemail'] . "',
        '" . $_SESSION["hemsemail"] . "',
        'POSTED',
        '" . ((isset($_REQUEST["ttype"]) && $_REQUEST["ttype"] !== "") ? strtoupper($_REQUEST["ttype"]) : "GLTRANSACTIONS" ) . "',
        " . ((isset($_POST["servicecharge"]) && $_POST["servicecharge"] > 0) ? $_POST["servicecharge"] : 0 ) . ",
        " . $debittotal . ",
        0,
        '" . $ref . "',
        '" . ((isset($_REQUEST["bankpaywith100"]) && $_REQUEST["bankpaywith100"] !== "") ? strtoupper($_REQUEST["bankpaywith100"]) : "NO" ) . "',
        'CUSTOMERACCOUNT',
        " . ((isset($_POST["ownerid"]) && $_POST["ownerid"] > 0) ? $_POST["ownerid"] : -1 ) . ",
        '" . ((isset($_REQUEST["paymentmethod"]) && $_REQUEST["paymentmethod"] !== "") ? strtoupper(htmlentities($_REQUEST["paymentmethod"],ENT_QUOTES)) : "NONCASH" ) . "',
        '" . date('Y-m-d H:i:s') . "'";
        
        $result = $transaction->registerTransaction($fields, $values);
        $userres = $user->addUserActivity($_SESSION["hemsemail"], $_SESSION["hemsemail"] . " posted customer to GL transactions: $acctss at " . date("Y-m-d H:i:s"), date("Y-m-d H:i:s"), "GL");
    }
}

if ($result) {
    echo success($result, 200, "Successful", "Successful");
}else {
    echo badRequest(204, "Not successful");
}

?>