function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($out, "float", 1, 10, "Invalid out amount.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 10, "Invalid amount.");
    $v->isOk($rate, "float", 1, 10, "Invalid exchange rate.");
    $v->isOk($supid, "num", 1, 10, "Invalid supplier number.");
    $v->isOk($out1, "float", 0, 10, "Invalid paid amount(current).");
    $v->isOk($out2, "float", 0, 10, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 10, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 10, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 10, "Invalid paid amount(120).");
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No.");
            $v->isOk($paidamt[$key], "float", 1, 20, "Invalid amount to be paid.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $bank = pg_fetch_array($rslt);
    db_connect();
    # Supplier name
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql);
    $sup = pg_fetch_array($supRslt);
    db_conn("exten");
    # get debtors control account
    $sql = "SELECT credacc FROM departments WHERE deptid ='{$sup['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    # Update xrate
    xrate_update($sup['fcid'], $rate, "suppurch", "id");
    sup_xrate_update($sup['fcid'], $rate);
    bank_xrate_update($sup['fcid'], $rate);
    $lamt = sprint($amt * $rate);
    # date format
    $sdate = explode("-", $date);
    $sdate = $sdate[2] . "-" . $sdate[1] . "-" . $sdate[0];
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    # Paid invoices
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    db_connect();
    if ($all == 0) {
        $ids = "";
        $purids = "";
        $fpamounts = "";
        $pamounts = "";
        $pdates = "";
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                #debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY fbalance LIMIT 1";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class='err'>Invalid Invoice Number.</li>";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - '{$paidamt[$key]}'::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $fpamounts .= "|{$paidamt[$key]}";
                $pamounts .= "|{$lpaidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        if ($out > 0) {
            recordDT($out, $sup['supid']);
        }
        $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
        suppledger($sup['supid'], $bank['accnum'], $sdate, $cheqnum, "Payment for purchases", $lamt, "d");
        db_connect();
        # Update the supplier (make fbalance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Record the payment record
        // $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        //2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, fpamounts, pdates, fcid, currency, location, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$fpamounts}', '{$pdates}', '{$sup['fcid']}', '{$sup['currency']}', '{$sup['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($accdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $lamt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        # Commit updates
        # pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    if ($all == 1) {
        $ids = "";
        $purids = "";
        $fpamounts = "";
        $pamounts = "";
        $pdates = "";
        # Begin updates
        //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY fbalance LIMIT 1";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class='err'>Invalid Invoice Number.</li>";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $fpamounts .= "|{$paidamt[$key]}";
                $pamounts .= "|{$lpaidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        if ($out1 > 0) {
            recordDT($out1, $sup['supid']);
        }
        if ($out2 > 0) {
            recordDT($out2, $sup['supid']);
        }
        if ($out3 > 0) {
            recordDT($out3, $sup['supid']);
        }
        if ($out4 > 0) {
            recordDT($out4, $sup['supid']);
        }
        if ($out5 > 0) {
            recordDT($out5, $sup['supid']);
        }
        $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the supplier (make fbalance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Record the payment record
        // $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        //2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, fpamounts, pdates, fcid, currency, location, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$fpamounts}', '{$pdates}', '{$sup['fcid']}', '{$sup['currency']}', '{$sup['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($accdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $lamt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        # Commit updates
        //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
        suppledger($sup['supid'], $bank['accnum'], $sdate, $cheqnum, "Payment to Supplier", $lamt, "d");
        db_connect();
    }
    if ($all == 2) {
        $ids = "";
        $purids = "";
        $fpamounts = "";
        $pamounts = "";
        $pdates = "";
        # Begin updates
        #pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY fbalance LIMIT 1";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class=err>Invalid Invoice Number.";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - '{$paidamt[$key]}'::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $samount = $paidamt[$key] - $paidamt[$key] * 2;
                $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc,div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment - Purchase: {$invids[$key]}','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
                $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
                suppledger($sup['supid'], $bank['accnum'], $sdate, $invids[$key], "Payment for Purchase No. {$invids[$key]}", $paidamt[$key], "d");
                db_connect();
                # record the payment on the statement
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $fpamounts .= "|{$paidamt[$key]}";
                $pamounts .= "|{$lpaidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        # Update the supplier (make fbalance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Record the payment record
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, fpamounts, pdates, fcid, currency, location, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$fpamounts}', '{$pdates}', '{$sup['fcid']}', '{$sup['currency']}', '{$sup['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($accdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $lamt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        # Commit updates
        #pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    db_conn('cubit');
    $Sl = "DELETE FROM suppurch WHERE fbalance = 0::numeric(13,2) AND balance = 0::numeric(13,2)";
    $Rx = db_exec($Sl);
    # status report
    $write = "\n\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t<tr>\n\t\t\t<th>International Bank Payment</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>International Bank Payment added to cash book.</td>\n\t\t</tr>\n\t</table>";
    # main table (layout with menu)
    $OUTPUT = "<center>\n\t<table width='90%'>\n\t\t<tr valign='top'>\n\t\t\t<td width='50%'>{$write}</td>\n\t\t\t<td align='center'>\n\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='bank-pay-supp.php'>Add supplier payment</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='bank-pay-add.php'>Add Bank Payment</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='cashbook-view.php'>View Cash Book</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t</tr>\n\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (isset($back)) {
        enter($_POST);
    }
    # Validate input
    require_lib("validate");
    $v = new validate();
    if (isset($fcids)) {
        foreach ($fcids as $key => $value) {
            $v->isOk($fcids[$key], "num", 1, 20, "Invalid currency.");
            $v->isOk($rates[$key], "float", 1, 20, "Invalid rate.");
        }
    }
    # Display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class=err>" . $e["msg"];
        }
        $confirmCust .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    foreach ($fcids as $key => $fcid) {
        $cur = getSymbol($fcid);
        $rates[$key] = sprint($rates[$key]);
        xrate_change($fcid, $rates[$key]);
        // Main updates
        sup_xrate_update($fcid, $rates[$key]);
        xrate_update($fcid, $rates[$key], "suppurch", "id");
        cus_xrate_update($fcid, $rates[$key]);
        xrate_update($fcid, $rates[$key], "invoices", "invid");
        xrate_update($fcid, $rates[$key], "custran", "id");
        bank_xrate_update($fcid, $rates[$key]);
    }
    // Layout
    $write = "\r\n\t\t<table border='0' cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\r\n\t\t\t<tr><th>Exchange rates have been updated</th></tr>\r\n\t\t\t<tr class='datacell'><td>Exchange rates have been successfully updated on the system.</td></tr>\r\n\t\t</table>\r\n\t\t<p>\r\n\t\t<table border='0' cellpadding='2' cellspacing='1'>\r\n\t\t\t<tr><th>Quick Links</th></tr>\r\n\t\t\t<tr class='bg-odd'>\r\n\t\t\t\t<td><a href='../main.php'>Main Menu</a></td>\r\n\t\t\t</tr>\r\n\t\t</table>";
    return $write;
}
function write($_POST)
{
    db_connect();
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($fbankid, "num", 1, 30, "Invalid Foreign Bank Account.");
    $date = $v->chkrDate($date, "Invalid date.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amount, "float", 1, 10, "Invalid amount.");
    $v->isOk($rate, "float", 1, 10, "Invalid exchange rate.");
    $v->isOk($ttype, "string", 1, 4, "Invalid Transfer type option.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    # Get bank account name
    db_connect();
    $sql = "SELECT * FROM bankacct WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $bankRslt = db_exec($sql);
    $bank = pg_fetch_array($bankRslt);
    $sql = "SELECT * FROM bankacct WHERE bankid = '{$fbankid}' AND div = '" . USER_DIV . "'";
    $fbankRslt = db_exec($sql);
    $fbank = pg_fetch_array($fbankRslt);
    bank_xrate_update($fbank['fcid'], $rate);
    # date format
    $date = explode("-", $date);
    $date = $date[2] . "-" . $date[1] . "-" . $date[0];
    #refnum
    $refnum = getrefnum();
    /* -- Start Hooks -- */
    # Get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # Check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $banklnk = pg_fetch_array($rslt);
    # Get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$fbankid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # Check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $fbanklnk = pg_fetch_array($rslt);
    /* -- End Hooks -- */
    $cheqnum = 0 + $cheqnum;
    if ($ttype == 'loc') {
        $famount = sprint($amount / $rate);
        # Record the payment record
        db_connect();
        $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, name, descript, cheqnum, amount, \n\t\t\t\tfamount, vat, chrgvat, banked, accinv, reference, div\n\t\t\t) VALUES (\n\t\t\t\t'{$bankid}', 'withdrawal', '{$date}', '{$fbank['accname']} {$fbank['bankname']}', '{$descript}', '{$cheqnum}', '{$amount}', \n\t\t\t\t'{$famount}', '0', 'no', 'no', '{$fbanklnk['accnum']}', '{$reference}', '" . USER_DIV . "'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        $lcashid = pglib_lastid("cashbook", "cashid");
        $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, name, descript, cheqnum, amount, \n\t\t\t\tfamount, vat, chrgvat, banked, accinv, lcashid, reference, div\n\t\t\t) VALUES (\n\t\t\t\t'{$fbankid}', 'deposit', '{$date}', '{$bank['accname']} {$bank['bankname']}', '{$descript}', '{$cheqnum}', '{$amount}', \n\t\t\t\t'{$famount}', '0', 'no', 'no', '{$banklnk['accnum']}',  '{$lcashid}', '{$reference}', '" . USER_DIV . "'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        $lcashid2 = pglib_lastid("cashbook", "cashid");
        #restore link
        $sql = "UPDATE cashbook SET lcashid = '{$lcashid2}' WHERE cashid = '{$lcashid}'";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance + '{$amount}'::numeric(13,2)), fbalance = (fbalance + '{$famount}'::numeric(13,2)) WHERE bankid = '{$fbankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # DT(account involved), CT(bank)
        writetrans($fbanklnk['accnum'], $banklnk['accnum'], $date, $refnum, $amount, $descript);
    } else {
        $lamount = sprint($amount * $rate);
        # Record the payment record
        db_connect();
        $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, name, descript, cheqnum, amount, \n\t\t\t\tfamount, vat, chrgvat, banked, accinv, reference, div\n\t\t\t) VALUES (\n\t\t\t\t'{$bankid}', 'deposit', '{$date}', '{$fbank['accname']} {$fbank['bankname']}', '{$descript}', '{$cheqnum}', '{$lamount}', \n\t\t\t\t'{$amount}' , '0', 'no', 'no', '{$fbanklnk['accnum']}', '{$reference}', '" . USER_DIV . "'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        $lcashid = pglib_lastid("cashbook", "cashid");
        $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, name, descript, cheqnum, amount, \n\t\t\t\tfamount, vat, chrgvat, banked, accinv, lcashid, reference, div\n\t\t\t) VALUES (\n\t\t\t\t'{$fbankid}', 'withdrawal', '{$date}', '{$bank['accname']} {$bank['bankname']}', '{$descript}', '{$cheqnum}', '{$lamount}', \n\t\t\t\t'{$amount}', '0', 'no', 'no', '{$banklnk['accnum']}', '{$lcashid}', '{$reference}', '" . USER_DIV . "'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        $lcashid2 = pglib_lastid("cashbook", "cashid");
        #restore link
        $sql = "UPDATE cashbook SET lcashid = '{$lcashid2}' WHERE cashid = '{$lcashid}'";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance - '{$lamount}'::numeric(13,2)), fbalance = (fbalance - '{$amount}'::numeric(13,2)) WHERE bankid = '{$fbankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # DT(account involved), CT(bank)
        writetrans($banklnk['accnum'], $fbanklnk['accnum'], $date, $refnum, $lamount, $descript);
    }
    # Status report
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>Bank Payment</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>Bank Transfer added to cash book.</td>\n\t\t\t</tr>\n\t\t</table>";
    # Main table (layout with menu)
    $OUTPUT = "\n\t\t<center>\n\t\t<table width='90%'>\n\t\t\t<tr valign='top'>\n\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t<td align='center'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='bank-pay-add.php'>Add Bank Payment</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='cashbook-view.php'>View Cash Book</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($out, "float", 1, 10, "Invalid out amount.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 10, "Invalid amount.");
    $v->isOk($cusid, "num", 1, 10, "Invalid customer number.");
    $v->isOk($out1, "float", 0, 10, "Invalid paid amount(currant).");
    $v->isOk($out2, "float", 0, 10, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 10, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 10, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 10, "Invalid paid amount(120).");
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No.");
            $v->isOk($paidamt[$key], "float", 1, 20, "Invalid amount to be paid.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        $Sl = "SELECT * FROM accounts WHERE accname='Cash on Hand'";
        $Rg = db_exec($Sl);
        if (pg_num_rows($Rg) < 1) {
            if ($bankid == 0) {
                return "There is no 'Cash on Hand' account, there was one, but its not there now, you must have deleted it, if you want to use cash functionality please create a 'Cash on Hand' account.";
            } else {
                return "Invalid bank acc.";
            }
        }
        $add = pg_fetch_array($Rg);
        $bank['accnum'] = $add['accid'];
    } else {
        $bank = pg_fetch_array($rslt);
    }
    db_connect();
    # Customer name
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusid}' AND div = '" . USER_DIV . "'";
    $cusRslt = db_exec($sql);
    $cus = pg_fetch_array($cusRslt);
    db_conn("exten");
    # get debtors control account
    $sql = "SELECT debtacc FROM departments WHERE deptid ='{$cus['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    # Update xrate
    cus_xrate_update($cus['fcid'], $rate);
    xrate_update($cus['fcid'], $rate, "invoices", "invid");
    xrate_update($cus['fcid'], $rate, "custran", "id");
    bank_xrate_update($cus['fcid'], $rate);
    $lamt = sprint($amt * $rate);
    # date format
    $sdate = explode("-", $date);
    $sdate = $sdate[2] . "-" . $sdate[1] . "-" . $sdate[0];
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = date("Y-m-d");
    # Paid invoices
    $invidsers = "";
    $rinvids = "";
    $famounts = "";
    $amounts = "";
    $invprds = "";
    $rages = "";
    db_connect();
    if ($all == 0) {
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                if (!isset($itype[$ii])) {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,odate FROM invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE invoices SET balance = (balance - {$lpaidamt[$key]}::numeric(13,2)),fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $lpaidamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $famounts .= "|{$paidamt[$key]}";
                    $amounts .= "|{$lpaidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                } else {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,descrip,age,odate FROM nons_invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE nons_invoices SET balance = (balance - {$lpaidamt[$key]}::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $lpaidamt[$key], "c");
                    db_connect();
                    frecordCT($paidamt[$key], $cus['cusnum'], $rate, $cus['fcid']);
                    $rinvids .= "|{$invids[$key]}";
                    $famounts .= "|{$paidamt[$key]}";
                    $amounts .= "|{$lpaidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                }
            }
        }
        # update the customer (make fbalance less)
        $sql = "UPDATE customers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # record the payment record
        // $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$invprds', '$rages', '".USER_DIV."')";
        // 2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$invprds', '$rages', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, famounts, invprds, rages, fcid, currency, location, div) VALUES ('{$bankid}', 'deposit', '{$sdate}', '{$cus['cusname']} {$cus['surname']}', 'Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$famounts}', '{$invprds}', '{$rages}', '{$cus['fcid']}', '{$cus['currency']}', '{$cus['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance + '{$lamt}'::numeric(13,2)), fbalance = (fbalance + '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($sdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}' AND accid!=0";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            $Sl = "SELECT * FROM accounts WHERE accname='Cash on Hand'";
            $Rg = db_exec($Sl);
            if (pg_num_rows($Rg) < 1) {
                if ($bankid == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but its not there now, if you want to use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $add = pg_fetch_array($Rg);
            $link['accnum'] = $add['accid'];
        } else {
            $link = pg_fetch_array($Rx);
        }
        writetrans($link['accnum'], $dept['debtacc'], $sdate, $refnum, $lamt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        db_conn('cubit');
        if ($out > 0) {
            frecordCT($out, $cus['cusnum'], $rate, $cus['fcid']);
            $Sl = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$cus['cusnum']}','0','" . $out * -1 . "','{$sdate}', 'Payment Received.', '" . USER_DIV . "', '{$sdate}')";
            $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
            custledger($cus['cusnum'], $bank['accnum'], $sdate, "PAYMENT", "Payment received.", $out * $rate, "c");
            db_connect();
        }
        # Commit updates
        # pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    if ($all == 1) {
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                if (!isset($itype[$ii])) {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,odate FROM invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class=err>Invalid Invoice Number.";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE invoices SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $lpaidamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $famounts .= "|{$paidamt[$key]}";
                    $amounts .= "|{$lpaidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                } else {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,descrip,age,odate FROM nons_invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class=err>Invalid Invoice Number.";
                    }
                    $inv = pg_fetch_array($invRslt);
                    # reduce the money that has been paid
                    $sql = "UPDATE nons_invoices SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $inv['invnum'] += 0;
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $lpaidamt[$key], "c");
                    db_connect();
                    frecordCT($paidamt[$key], $cus['cusnum'], $rate, $cus['fcid']);
                    $rinvids .= "|{$invids[$key]}";
                    $famounts .= "|{$paidamt[$key]}";
                    $amounts .= "|{$lpaidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                }
            }
        }
        # update the customer (make fbalance less)
        $sql = "UPDATE customers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # record the payment record
        // $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$invprds', '$rages', '".USER_DIV."')";
        // 2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$invprds', '$rages', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, famounts, invprds, rages, fcid, currency, location, div) VALUES ('{$bankid}', 'deposit', '{$sdate}', '{$cus['cusname']} {$cus['surname']}', 'Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$famounts}', '{$invprds}', '{$rages}', '{$cus['fcid']}', '{$cus['currency']}', '{$cus['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance + '{$lamt}'::numeric(13,2)), fbalance = (fbalance + '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($sdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}' AND accid!=0";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            $Sl = "SELECT * FROM accounts WHERE accname='Cash on Hand'";
            $Rg = db_exec($Sl);
            if (pg_num_rows($Rg) < 1) {
                if ($bankid == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but its not there now, if you want to use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $add = pg_fetch_array($Rg);
            $link['accnum'] = $add['accid'];
        } else {
            $link = pg_fetch_array($Rx);
        }
        writetrans($link['accnum'], $dept['debtacc'], $sdate, $refnum, $lamt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        db_conn('cubit');
        if ($out1 + $out2 + $out3 + $out4 + $out5 > 0) {
            $Sl = "\n\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$cus['cusnum']}','0','" . ($out1 + $out2 + $out3 + $out4 + $out5) * -1 . "','{$sdate}', 'Payment Received.', '" . USER_DIV . "', '{$sdate}')";
            $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
            custledger($cus['cusnum'], $bank['accnum'], $sdate, "PAYMENT", "Payment received.", ($out1 + $out2 + $out3 + $out4 + $out5) * $rate, "c");
            db_connect();
        }
        if ($out1 > 0) {
            frecordCT($out1, $cus['cusnum'], $rate, $cus['fcid']);
        }
        if ($out2 > 0) {
            frecordCT($out2, $cus['cusnum'], $rate, $cus['fcid']);
        }
        if ($out3 > 0) {
            frecordCT($out3, $cus['cusnum'], $rate, $cus['fcid']);
        }
        if ($out4 > 0) {
            frecordCT($out4, $cus['cusnum'], $rate, $cus['fcid']);
        }
        if ($out5 > 0) {
            frecordCT($out5, $cus['cusnum'], $rate, $cus['fcid']);
        }
        # Commit updates
        # pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    if ($all == 2) {
        # Begin updates
        //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        # Debtors
        foreach ($invids as $key => $value) {
            $ii = $invids[$key];
            $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
            if (!isset($itype[$ii])) {
                # Get debt invoice info
                $sql = "SELECT prd,invnum,odate FROM invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class=err>Invalid Invoice Number.";
                }
                $inv = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE invoices SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $lpaidamt[$key], "c");
                db_connect();
                $rinvids .= "|{$invids[$key]}";
                $famounts .= "|{$paidamt[$key]}";
                $amounts .= "|{$lpaidamt[$key]}";
                $invprds .= "|{$inv['prd']}";
                $rages .= "|0";
                $invidsers .= " - {$inv['invnum']}";
            } else {
                # Get debt invoice info
                $sql = "SELECT prd,invnum,descrip,age,odate FROM nons_invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class=err>Invalid Invoice Number.";
                }
                $inv = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE nons_invoices SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $lpaidamt[$key], "c");
                db_connect();
                frecordCT($paidamt[$key], $cus['cusnum'], $rate, $cus['fcid']);
                $rinvids .= "|{$invids[$key]}";
                $famounts .= "|{$paidamt[$key]}";
                $amounts .= "|{$lpaidamt[$key]}";
                $invprds .= "|0";
                $rages .= "|{$inv['age']}";
                $invidsers .= " - {$inv['invnum']}";
            }
        }
        # update the customer (make fbalance less)
        $sql = "UPDATE customers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # record the payment record
        //2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, famounts, invprds, rages, div) VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]', 'Payment for Invoices $invidsers from customer $cus[cusname] $cus[surname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]', '$rinvids', '$amounts', '$famounts', '$invprds', '$rages', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, cusnum, rinvids, amounts, famounts, invprds, rages, fcid, currency, location, div) VALUES ('{$bankid}', 'deposit', '{$sdate}', '{$cus['cusname']} {$cus['surname']}', 'Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$famounts}', '{$invprds}', '{$rages}', '{$cus['fcid']}', '{$cus['currency']}', '{$cus['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance + '{$lamt}'::numeric(13,2)), fbalance = (fbalance + '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($accdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}' AND accid!=0";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            $Sl = "SELECT * FROM accounts WHERE accname='Cash on Hand'";
            $Rg = db_exec($Sl);
            if (pg_num_rows($Rg) < 1) {
                if ($bankid == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but its not there now, if you want to use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $add = pg_fetch_array($Rg);
            $link['accnum'] = $add['accid'];
        } else {
            $link = pg_fetch_array($Rx);
        }
        writetrans($link['accnum'], $dept['debtacc'], $sdate, $refnum, $lamt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        # Commit updates
        //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    db_conn('cubit');
    /* start moving invoices */
    # move invoices that are fully paid
    $sql = "SELECT * FROM invoices WHERE fbalance = 0 AND balance = 0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    while ($invb = pg_fetch_array($invbRslt)) {
        if ($invb['prd'] == 0) {
            $invb['prd'] = PRD_DB;
        }
        db_conn($invb['prd']);
        # Insert invoice to period DB
        $sql = "INSERT INTO invoices(invid, invnum, deptid, cusnum, deptname, cusacc, cusname, surname, cusaddr, cusvatno, cordno, ordno, chrgvat, fcid, currency, xrate, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, fbalance, location, age, comm, discount, delivery, printed, done, div)";
        $sql .= " VALUES('{$invb['invid']}','{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', '{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['fcid']}', '{$invb['currency']}', '{$invb['xrate']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '0', '{$invb['location']}', '{$invb['age']}', '{$invb['comm']}', '{$invb['discount']}', '{$invb['delivery']}', 'y', 'y', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.", SELF);
        # get selected stock in this invoice
        db_connect();
        $sql = "SELECT * FROM inv_items WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        while ($stkd = pg_fetch_array($stkdRslt)) {
            db_conn($invb['prd']);
            # insert invoice items
            $sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, div) VALUES('{$invb['invid']}', '{$stkd['whid']}', '{$stkd['stkid']}', '{$stkd['qty']}', '{$stkd['unitcost']}', '{$stkd['amt']}', '{$stkd['disc']}', '{$stkd['discp']}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
        }
        db_connect();
        # Remove those invoices from running DB
        $sql = "DELETE FROM invoices WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        # Remove those invoice items from running DB
        $sql = "DELETE FROM inv_items WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    }
    /* end moving invoices */
    # status report
    $write = "\n\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<tr><th>Bank Receipt</th></tr>\n\t\t\t\t<tr class='datacell'><td>Bank Receipt added to cash book.</td></tr>\n\t\t\t</table>";
    # main table (layout with menu)
    $OUTPUT = "\n\t\t\t<center>\n\t\t\t<table width='90%'>\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td width=50%>{$write}</td>\n\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t<tr><th>Quick Links</th></tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'><td><a href='bank-pay-add.php'>Add Bank Payment</a></td></tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'><td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td></tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'><td><a href='bank-recpt-inv.php'>Add Customer Payment</a></td></tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'><td><a href='cashbook-view.php'>View Cash Book</a></td></tr>\n\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    return $OUTPUT;
}
function bank($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cashid, "num", 1, 4, "Invalid Reference number.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get cash book record
    Db_Connect();
    $sql = "SELECT * FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.", SELF);
    if (pg_numrows($accntRslt) < 1) {
        $OUTPUT = "<li class='err'>The entry with reference number, <b>{$cashid}</b> was not found in Cubit.</li>";
        return $OUTPUT;
    }
    $accnt = pg_fetch_array($accntRslt);
    $rate = sprint($accnt['amount'] / $accnt['famount']);
    # Update xrate
    if ($accnt['fcid'] != 0) {
        cus_xrate_update($accnt['fcid'], $rate);
        xrate_update($accnt['fcid'], $rate, "invoices", "invid");
        xrate_update($accnt['fcid'], $rate, "custran", "id");
        bank_xrate_update($accnt['fcid'], $rate);
    }
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.";
    }
    $bank = pg_fetch_array($rslt);
    # Date
    $sdate = date("Y-m-d");
    $date = $accnt["date"];
    # If tis customer payment
    if ($accnt['cusnum'] > 0) {
        db_connect();
        # Get invoice Ids and Amounts
        $invids = explode("|", $accnt['rinvids']);
        $famounts = explode("|", $accnt['famounts']);
        $amounts = explode("|", $accnt['amounts']);
        $invprds = explode("|", $accnt['invprds']);
        $rages = explode("|", $accnt['rages']);
        # Return the amount that was surppose to be paid to invoices
        foreach ($invids as $key => $invid) {
            db_connect();
            # Skip all nulls and check existance
            if ($invids[$key] > 0 && ext_ex("invoices", "invid", $invids[$key]) && $invprds[$key] != 0) {
                db_connect();
                $sql = "UPDATE invoices SET balance = (balance + '{$amounts[$key]}'::numeric(13,2)), fbalance = (fbalance + '{$famounts[$key]}'::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
            } elseif ($invids[$key] > 0 && ext_ex("nons_invoices", "invid", $invids[$key]) && $invprds[$key] == 0) {
                db_connect();
                $sql = "UPDATE nons_invoices SET balance = (balance + '{$amounts[$key]}'::numeric(13,2)), fbalance = (fbalance + '{$famounts[$key]}'::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                frecordDTA($famounts[$key], $accnt['cusnum'], $rate, $rages[$key], $accnt['fcid']);
                // custDTA($amounts[$key], $accnt['cusnum'], $rages[$key]);
            } elseif ($invids[$key] > 0) {
                db_conn($invprds[$key]);
                # check if invoice exitsts on prd
                if (ext_ex("invoices", "invid", $invids[$key])) {
                    # if found, Move the invoice back
                    if (moveback($invids[$key], $invprds[$key], $famounts[$key], $amounts[$key])) {
                    }
                }
            }
        }
        # Begin updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        db_connect();
        # Update the customer (make balance more)
        $sql = "UPDATE customers SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE cusnum = '{$accnt['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$accnt['famount']}'::numeric(13,2)), balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Record the transaction on the statement
        $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$accnt['cusnum']}', '0', '{$accnt['famount']}','{$sdate}', 'Cheque/Payment for Invoices Cancelled.', '" . USER_DIV . "', '{$accnt['date']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        if ($accnt['lcashid'] > 0) {
            // Connect to database
            db_Connect();
            $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.", SELF);
            $laccnt = pg_fetch_array($laccntRslt);
            $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            // Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        # Make ledge record
        custledger($accnt['cusnum'], $bank['accnum'], $sdate, "cancel", "Payment for Invoices Cancelled.", $accnt['amount'], "d");
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = $accnt["date"];
        # debit customer account, credit bank account (customer takes money back)
        writetrans($accnt['accinv'], $bank['accnum'], $date, $refnum, $accnt['amount'], $descript);
    } elseif ($accnt['supid'] > 0) {
        db_connect();
        # Begin updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        $ids = explode("|", $accnt['ids']);
        $purids = explode("|", $accnt['purids']);
        $fpamounts = explode("|", $accnt['fpamounts']);
        $pamounts = explode("|", $accnt['pamounts']);
        $pdates = explode("|", $accnt['pdates']);
        if (count($ids) > 0) {
            foreach ($ids as $key => $vale) {
                if ($ids[$key] > 0) {
                    rerecord($ids[$key], $accnt['supid'], $purids[$key], $fpamounts[$key], $pamounts[$key], $pdates[$key]);
                }
            }
        }
        # if the amount was overpaid
        if (array_sum($fpamounts) < $accnt['famount']) {
            # get and record amount that was overpaid to balance the equation
            $rem = $accnt['famount'] - array_sum($fpamounts);
            rerecord('0', $accnt['supid'], '0', $rem, 0, $accnt['date']);
        }
        # Update the supplier (make balance more)
        $sql = "UPDATE suppliers SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE supid = '{$accnt['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Record the payment on the statement
        $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, ref, descript, amount, div) VALUES('{$accnt['supid']}', '{$sdate}', '{$bank['accnum']}', '{$accnt['cheqnum']}', 'Cheque/Payment to Supplier Cancelled.', '{$accnt['famount']}', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        if ($accnt['lcashid'] > 0) {
            // Connect to database
            db_Connect();
            $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.", SELF);
            $laccnt = pg_fetch_array($laccntRslt);
            $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            // Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        suppledger($accnt['supid'], $bank['accnum'], $sdate, $accnt['cheqnum'], "Payment to Supplier Cancelled", $accnt['amount'], "c");
        db_connect();
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = $accnt["date"];
        # debit bank, credit supplier account
        writetrans($bank['accnum'], $accnt['accinv'], $date, $refnum, $accnt['amount'], $descript);
    } elseif ($accnt['suprec'] > 0) {
        db_connect();
        $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$accnt['suprec']}','-{$accnt['amount']}','{$accnt['date']}', 'Receipt Cancelled','{$accnt['cheqnum']}','0', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the supplier (make balance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE supid = '{$accnt['suprec']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        suppDT($accnt['amount'], $accnt['suprec']);
        db_connect();
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        if ($accnt['lcashid'] > 0) {
            # Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = $accnt["date"];
        # debit bank, credit supplier account
        writetrans($bank['accnum'], $accnt['accinv'], $date, $refnum, $accnt['amount'], $descript);
    } elseif (strlen($accnt['accids']) > 0) {
        /* -- Start Hooks -- */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
        /* -- End Hooks -- */
        multican($accnt, $bank, $vatacc);
    } else {
        $amount = $accnt['amount'];
        $vat = $accnt['vat'];
        $chrgvat = $accnt['chrgvat'];
        $amount -= $vat;
        /* -- Start Hooks -- */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
        /* -- End Hooks -- */
        db_connect();
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        if ($accnt['trantype'] == "deposit") {
            $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$accnt['famount']}'::numeric(13,2)), balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        } else {
            $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        }
        /* ---- the Others ---- */
        if ($accnt['lcashid'] > 0) {
            //Connect to database
            db_Connect();
            $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.", SELF);
            $laccnt = pg_fetch_array($laccntRslt);
            if ($laccnt['trantype'] == "deposit") {
                $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$laccnt['famount']}'::numeric(13,2)), balance = (balance - '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            } else {
                $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            }
            # Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        /* ---- End the Others ---- */
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = $accnt["date"];
        if ($accnt['trantype'] == "deposit") {
            # DT(account involved), CT(bank)
            writetrans($accnt['accinv'], $bank['accnum'], $date, $refnum, $amount, $descript);
            if ($vat != 0) {
                # DT(Vat), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $date, $refnum, $vat, $descript);
            }
            $cc_trantype = cc_TranTypeAcc($accnt['accinv'], $bank['accnum']);
        } else {
            # DT(bank), CT(account invoilved)
            writetrans($bank['accnum'], $accnt['accinv'], $date, $refnum, $amount, $descript);
            if ($vat != 0) {
                # DT(Vat), CT(Bank)
                writetrans($bank['accnum'], $vatacc, $date, $refnum, $vat, $descript);
            }
            $cc_trantype = cc_TranTypeAcc($bank['accnum'], $accnt['accinv']);
        }
    }
    if (isset($cc_trantype) && $cc_trantype != false) {
        $cc = "<script> CostCenter('{$cc_trantype}', 'Cancelled Bank Transaction', '{$date}', '{$descript}', '" . ($accnt['amount'] - $accnt['vat']) . "', '../'); </script>";
    } else {
        $cc = "";
    }
    # Status report
    $bank = "\n\t\t{$cc}\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>Cash Book</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Cash Book Entry was successfully canceled .</td>\n\t\t\t</tr>\n\t\t</table>";
    # Main table (layout with menu)
    $OUTPUT = "\n\t\t\t\t<center>\n\t\t\t\t<table width='90%'>\n\t\t\t\t\t<tr valign='top'>\n\t\t\t\t\t\t<td width='60%'>{$bank}</td>\n\t\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th>Quick Navigation</th>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td align='center'><a href='cashbook-view.php'>View Cash Book</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td align='center'><a href='../reporting/not-banked.php'>View Outstanding Cash Book Entries</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td align='center'><a href='bank-pay-add.php'>Add bank Payment</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td align='center'><a href='bank-recpt-add.php'>Add Bank Receipt</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    return $OUTPUT;
}