function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($from_day, "num", 1, 2, "Invalid Day for the 'From' date.");
    $v->isOk($from_month, "num", 1, 2, "Invalid month for the 'From' date..");
    $v->isOk($from_year, "num", 1, 4, "Invalid year for the 'From' date..");
    $v->isOk($to_day, "num", 1, 2, "Invalid Day for the 'To' date.");
    $v->isOk($to_month, "num", 1, 2, "Invalid month for the 'To' date..");
    $v->isOk($to_year, "num", 1, 4, "Invalid year for the 'To' date..");
    # lets mix the date
    $from = $from_day . "-" . $from_month . "-" . $from_year;
    $to = $to_day . "-" . $to_month . "-" . $to_year;
    # 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;
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # Get bank details
    $bankRslt = get("cubit", "accname,bankname,fcid", "bankacct", "bankid", $bankid);
    $bank = pg_fetch_array($bankRslt);
    $Sl = "SELECT * FROM currency WHERE fcid='{$bank['fcid']}'";
    $Ry = db_exec($Sl) or errDie("Unable to get currency");
    if (pg_numrows($Ry) > 0) {
        $curdata = pg_fetch_array($Ry);
        $fc = $curdata['symbol'];
    }
    $s1 = "";
    $s2 = "";
    $s3 = "";
    $s4 = "";
    $s5 = "";
    $order = "order by date desc, cheqnum asc";
    if (isset($order)) {
        if ($order == "order by date desc, cheqnum asc") {
            $s2 = "selected";
        } elseif ($order == "order by date desc, cheqnum desc") {
            $s3 = "selected";
        } elseif ($order == "order by cheqnum asc") {
            $s4 = "selected";
        } elseif ($order == "order by cheqnum desc") {
            $s5 = "selected";
        } else {
            $s1 = "selected";
        }
    } else {
        $s1 = "selected";
    }
    // Set up table to display in
    # Receipts
    $OUTPUT = "\n\t<center>\n\t<h3>Batch Cash Book Entries<br><br>Account : {$bank['accname']} - {$bank['bankname']}<br>Period : {$from} to {$to}</h3>\n\t<table " . TMPL_tblDflts . ">\n\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t<input type='hidden' name='key' value='viewcash'>\n\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t<input type='hidden' name='from_day' value='{$from_day}'>\n\t\t<input type='hidden' name='from_month' value='{$from_month}'>\n\t\t<input type='hidden' name='from_year' value='{$from_year}'>\n\t\t<input type='hidden' name='to_day' value='{$to_day}'>\n\t\t<input type='hidden' name='to_month' value='{$to_month}'>\n\t\t<input type='hidden' name='to_year' value='{$to_year}'>\n\t</table>\n\t<p>\n\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t<tr>\n\t\t\t<td colspan='7'><h4>Receipts</h4></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th> Date</th>\n\t\t\t<th>Bank Account Name</th>\n\t\t\t<th>Cheque Number</th>\n\t\t\t<th>Received From : </th>\n\t\t\t<th>Description</th>\n\t\t\t<th>Ledger Account</th>\n\t\t\t<th>Amount</th>\n\t\t</tr>";
    $rtotal = 0;
    // Received total amount
    // Connect to database
    db_Connect();
    # date format
    $from = explode("-", $from);
    $from = $from[2] . "-" . $from[1] . "-" . $from[0];
    $to = explode("-", $to);
    $to = $to[2] . "-" . $to[1] . "-" . $to[0];
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    # 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.";
    }
    $banklnk = pg_fetch_array($rslt);
    db_Connect();
    $sql = "SELECT * FROM batch_cashbook WHERE  date >= '{$from}' AND date <= '{$to}' AND trantype='deposit' AND bankid='{$bankid}' AND div = '" . USER_DIV . "' {$order}";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank deposits details from database.", SELF);
    $numrows = pg_numrows($accntRslt);
    if ($numrows < 1) {
        //$OUTPUT .= "<tr><td colspan='7' align='center'><li class='err'>There are no batch Payments/cheques received for the selected period.</td></tr>";
    } else {
        for ($i = 0; $i < $numrows; $i++) {
            $accnt = pg_fetch_array($accntRslt, $i);
            if (!isset($pro[$accnt['cashid']])) {
                continue;
            }
            //	if($accnt['bt']=="receipt") {
            $refnum = getrefnum();
            if (strlen($accnt['accids']) > 0) {
                $accids = explode("|", $accnt['accids']);
                $vatcodes = explode("|", $accnt['vatcodes']);
                $amounts = explode("|", $accnt['amounts']);
                $vats = explode("|", $accnt['vats']);
                $chrgvats = explode("|", $accnt['chrgvats']);
                $refnum = getrefnum();
                $descript = $accnt['descript'];
                //$date = date("Y-m-d");
                $date = $accnt['date'];
                foreach ($amounts as $key => $amount) {
                    # SQL Array Rule: Thou shalt skip Zero Reference
                    if ($key < 1) {
                        continue;
                    }
                    $accid = $accids[$key];
                    $vat = $vats[$key];
                    $chrgvat = $chrgvats[$key];
                    $amount -= $vat;
                    $vatcode = $vatcodes[$key];
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}'";
                    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                    $vd = pg_fetch_array($Ri);
                    if ($accnt['trantype'] != "deposit") {
                        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "a");
                        # DT(account involved), CT(bank)
                        //							writetrans($accid, $banklnk['accnum'], $date, $refnum, ($amount-$vat), $descript);
                        writetrans($accid, $banklnk['accnum'], $date, $refnum, $amount, $descript);
                        if ($vat != 0) {
                            # DT(Vat), CT(Bank)
                            writetrans($vatacc, $banklnk['accnum'], $date, $refnum, $vat, $descript);
                            vatr($vd['id'], $accnt['date'], "INPUT", $vd['code'], $refnum, $accnt['descript'], -$amount, -$vat);
                        }
                    } else {
                        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                        # DT(bank), CT(account invoilved)
                        //							writetrans($banklnk['accnum'], $accid, $date, $refnum, ($amount-$vat), $descript);
                        writetrans($banklnk['accnum'], $accid, $date, $refnum, $amount, $descript);
                        if ($vat != 0) {
                            # DT(Vat), CT(Bank)
                            vatr($vd['id'], $accnt['date'], "OUTPUT", $vd['code'], $refnum, $accnt['descript'], $amount, $vat);
                            writetrans($banklnk['accnum'], $vatacc, $date, $refnum, $vat, $descript);
                        }
                    }
                }
                db_connect();
                $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accids, amounts, chrgvats, vats, reference, div) VALUES ('{$accnt['bankid']}', 'deposit', '{$accnt['date']}', '{$accnt['name']}', '{$accnt['descript']}', '{$accnt['cheqnum']}', '{$accnt['amount']}', 'no', '{$accnt['accids']}', '{$accnt['amounts']}', '{$accnt['chrgvats']}', '{$accnt['vats']}', '{$accnt['reference']}', '" . USER_DIV . "')";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                db_connect();
                $Sl = "DELETE FROM batch_cashbook WHERE cashid='{$accnt['cashid']}'";
                $Ri = db_exec($Sl);
            } else {
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes WHERE id='{$accnt['vatcode']}'";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $vd = pg_fetch_array($Ri);
                # record the payment record
                db_connect();
                $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div, vatcode, reference) VALUES ('{$bankid}', 'deposit', '{$accnt['date']}', '{$accnt['name']}', '{$accnt['descript']}', '{$accnt['cheqnum']}', '{$accnt['amount']}', '{$accnt['vat']}', '{$accnt['chrgvat']}', 'no', '{$accnt['accinv']}', '" . USER_DIV . "', '{$accnt['vatcode']}', '{$accnt['reference']}')";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                vatr($vd['id'], $accnt['date'], "OUTPUT", $vd['code'], $refnum, $accnt['descript'], $accnt['amount'], $accnt['vat']);
                # DT(account involved), CT(bank)
                writetrans($banklnk['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $accnt['amount'] - $accnt['vat'], $accnt['descript']);
                if ($accnt['vat'] != 0) {
                    # DT(Vat), CT(Bank)
                    writetrans($banklnk['accnum'], $vatacc, $accnt['date'], $refnum, $accnt['vat'], $accnt['descript']);
                }
                //		}
                db_connect();
                $Sl = "DELETE FROM batch_cashbook WHERE cashid='{$accnt['cashid']}'";
                $Ri = db_exec($Sl);
                continue;
                if (strlen($accnt['accids']) > 0) {
                    $acc['accname'] = "<a href=# onClick=openSmallWindow('multi-acc-popup.php?cashid={$accnt['cashid']}')>Multiple Accounts</a>";
                    $acc['accname'] = "";
                    $acc['accno'] = "";
                } else {
                    # Get account name for the account involved
                    $AccRslt = get("core", "accname, topacc, accnum", "accounts", "accid", $accnt['accinv']);
                    $acc = pg_fetch_array($AccRslt);
                    $acc['accno'] = "{$acc['topacc']}/{$acc['accnum']}";
                }
                # Get account name for bank account
                db_connect();
                $sql = "SELECT accname,btype FROM bankacct WHERE bankid= '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
                $bnameRslt = db_exec($sql);
                $bname = pg_fetch_array($bnameRslt);
                $rtotal += $accnt['amount'];
                // add to rtotal
                $accnt['amount'] = sprint($accnt['amount']);
                $accnt['date'] = ext_rdate($accnt['date']);
                if ($bname['btype'] != "loc") {
                    $ex = "/ {$fc} {$accnt['famount']}";
                } else {
                    $ex = "";
                }
                $OUTPUT .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>{$accnt['date']}</td>\n\t\t\t\t\t\t\t\t<td align='center'>{$bname['accname']}</td>\n\t\t\t\t\t\t\t\t<td align='center'>{$accnt['cheqnum']}</td>\n\t\t\t\t\t\t\t\t<td align='center'>{$accnt['name']}</td>\n\t\t\t\t\t\t\t\t<td>{$accnt['descript']}</td>\n\t\t\t\t\t\t\t\t<td>{$acc['accno']}  {$acc['accname']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$accnt['amount']} {$ex}</td>";
                if ($accnt['banked'] == "no" && $accnt['opt'] != 'n') {
                    //$OUTPUT .= "<td><a href='batch-enytry-delete.php?id=$accnt[cashid]'>Delete</td>";
                    $OUTPUT .= "<input type='hidden' name='pro[" . $accnt['cashid'] . "]' value='1'>";
                    // $OUTPUT .= "<td><a href='../bank/cheq-cancel.php?cashid=$accnt[cashid]'>Cancel</td>";
                }
                $OUTPUT .= "</tr>";
            }
        }
        # print the total
        $OUTPUT .= "\n\t\t\t<tr class='" . bg_class() . "''>\n\t\t\t\t<td colspan='6'><b>Total Receipts</b></td>\n\t\t\t\t<td><b>" . CUR . " " . sprintf("%01.2f", $rtotal) . "</b></td>\n\t\t\t</tr>";
    }
    # Seperate the tables with two rows
    $OUTPUT .= "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='7'><br></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='7'><br></td>\n\t\t\t\t\t</tr>";
    # Payments
    $OUTPUT .= "\n\t\t<tr>\n\t\t\t<td colspan='7'><h4>Payments</h4></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th>Date</th>\n\t\t\t<th>Bank Account Name</th>\n\t\t\t<th>Cheque Number</th>\n\t\t\t<th>Paid to: </th>\n\t\t\t<th>Description</th>\n\t\t\t<th>Ledger Account</th>\n\t\t\t<th>Amount</th>\n\t\t</tr>";
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    # 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.";
    }
    $banklnk = pg_fetch_array($rslt);
    $ptotal = 0;
    // payments total
    // Connect to database
    db_Connect();
    $sql = "SELECT * FROM batch_cashbook WHERE date >= '{$from}' AND date <= '{$to}' AND trantype='withdrawal' AND bankid='{$bankid}' AND div = '" . USER_DIV . "' {$order}";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank deposits details from database.", SELF);
    if (pg_numrows($accntRslt) < 1) {
        //$OUTPUT .= "<tr><td colspan=7 align=center><li class=err>There are batch no Payments made for the selected period.</td></tr>";
    } else {
        # Display all bank payments
        for ($i = 0; $accnt = pg_fetch_array($accntRslt); $i++) {
            if (!isset($pro[$accnt['cashid']])) {
                continue;
            }
            if ($accnt['bt'] == "payment") {
                $refnum = getrefnum();
                if (strlen($accnt['accids']) > 0) {
                    $accids = explode("|", $accnt['accids']);
                    $vatcodes = explode("|", $accnt['vatcodes']);
                    $amounts = explode("|", $accnt['amounts']);
                    $vats = explode("|", $accnt['vats']);
                    $chrgvats = explode("|", $accnt['chrgvats']);
                    $refnum = getrefnum();
                    $descript = $accnt['descript'];
                    //$date = date("Y-m-d");
                    $date = $accnt['date'];
                    foreach ($amounts as $key => $amount) {
                        # SQL Array Rule: Thou shalt skip Zero Reference
                        if ($key < 1) {
                            continue;
                        }
                        $accid = $accids[$key];
                        $vat = $vats[$key];
                        $chrgvat = $chrgvats[$key];
                        $amount -= $vat;
                        $vatcode = $vatcodes[$key];
                        db_conn('cubit');
                        $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}'";
                        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                        $vd = pg_fetch_array($Ri);
                        if ($accnt['trantype'] != "deposit") {
                            $vatacc = gethook("accnum", "salesacc", "name", "VAT", "a");
                            # DT(account involved), CT(bank)
                            //							writetrans($accid, $banklnk['accnum'], $date, $refnum, $amount-$vat, $descript);
                            writetrans($accid, $banklnk['accnum'], $date, $refnum, $amount, $descript);
                            if ($vat != 0) {
                                # DT(Vat), CT(Bank)
                                writetrans($vatacc, $banklnk['accnum'], $date, $refnum, $vat, $descript);
                                vatr($vd['id'], $accnt['date'], "INPUT", $vd['code'], $refnum, $accnt['descript'], -$amount, -$vat);
                            }
                        } else {
                            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                            # DT(bank), CT(account invoilved)
                            writetrans($banklnk['accnum'], $accid, $date, $refnum, $amount, $descript);
                            if ($vat != 0) {
                                # DT(Vat), CT(Bank)
                                writetrans($banklnk['accnum'], $vatacc, $date, $refnum, $vat, $descript);
                                vatr($vd['id'], $accnt['date'], "OUTPUT", $vd['code'], $refnum, $accnt['descript'], $amount, $vat);
                            }
                        }
                    }
                    db_connect();
                    $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accids, amounts, chrgvats, vats, div, vatcode, reference) VALUES ('{$accnt['bankid']}', 'withdrawal', '{$accnt['date']}', '{$accnt['name']}', '{$accnt['descript']}', '{$accnt['cheqnum']}', '{$accnt['amount']}', 'no', '{$accnt['accids']}', '{$accnt['amounts']}', '{$accnt['chrgvats']}', '{$accnt['vats']}', '" . USER_DIV . "','{$accnt['vatcode']}', '{$accnt['reference']}')";
                    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                } else {
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$accnt['vatcode']}'";
                    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                    $vd = pg_fetch_array($Ri);
                    # Record the payment record
                    db_connect();
                    $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div, vatcode, reference) VALUES ('{$bankid}', 'withdrawal', '{$accnt['date']}', '{$accnt['name']}', '{$accnt['descript']}', '{$accnt['cheqnum']}', '{$accnt['amount']}', '{$accnt['vat']}', '{$accnt['chrgvat']}', 'no', '{$accnt['accinv']}', '" . USER_DIV . "','{$accnt['vatcode']}', '{$accnt['reference']}')";
                    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                    vatr($vd['id'], $accnt['date'], "INPUT", $vd['code'], $refnum, $accnt['descript'], -$accnt['amount'], -$accnt['vat']);
                    # DT(account involved), CT(bank)
                    writetrans($accnt['accinv'], $banklnk['accnum'], $accnt['date'], $refnum, $accnt['amount'] - $accnt['vat'], $accnt['descript']);
                    if ($accnt['vat'] != 0) {
                        # DT(Vat), CT(Bank)
                        writetrans($vatacc, $banklnk['accnum'], $accnt['date'], $refnum, $accnt['vat'], $accnt['descript']);
                    }
                }
                db_connect();
                $Sl = "DELETE FROM batch_cashbook WHERE cashid='{$accnt['cashid']}'";
                $Ri = db_exec($Sl);
                continue;
                if (strlen($accnt['accids']) > 0) {
                    $acc['accname'] = "<a href=# onClick=openSmallWindow('multi-acc-popup.php?cashid={$accnt['cashid']}')>Multiple Accounts</a>";
                    $acc['accno'] = "";
                } else {
                    # get account name for the account involved
                    $AccRslt = get("core", "accname, topacc, accnum", "accounts", "accid", $accnt['accinv']);
                    $acc = pg_fetch_array($AccRslt);
                    $acc['accno'] = "{$acc['topacc']}/{$acc['accnum']}";
                }
                # get account name for bank account
                db_connect();
                $sql = "SELECT accname,btype FROM bankacct WHERE bankid= '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
                $bnameRslt = db_exec($sql);
                $bname = pg_fetch_array($bnameRslt);
                $ptotal += $accnt['amount'];
                //add to total
                $accnt['amount'] = sprint($accnt['amount']);
                $accnt['date'] = ext_rdate($accnt['date']);
                if ($bname['btype'] != "loc") {
                    $ex = "/ {$fc} {$accnt['famount']}";
                } else {
                    $ex = "";
                }
                $OUTPUT .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>{$accnt['date']}</td>\n\t\t\t\t\t\t\t<td align='center'>{$bname['accname']}</td>\n\t\t\t\t\t\t\t<td align='center'>{$accnt['cheqnum']}</td>\n\t\t\t\t\t\t\t<td align='center'>{$accnt['name']}</td>\n\t\t\t\t\t\t\t<td>{$accnt['descript']}</td>\n\t\t\t\t\t\t\t<td>{$acc['accno']}  {$acc['accname']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$accnt['amount']} {$ex}</td>";
                if ($accnt['banked'] == "no" && $accnt['opt'] != 'n') {
                    //$OUTPUT .= "<td><a href='batch-enytry-delete.php?id=$accnt[cashid]'>Delete</td>";
                    $OUTPUT .= "<input type='hidden' name='pro[" . $accnt['cashid'] . "]' value='1'>";
                    //$OUTPUT .= "<td><a href='../bank/cheq-return.php?cashid=$accnt[cashid]'>Returned/Unpaid</td>";
                    // $OUTPUT .= "<td><a href='../bank/cheq-cancel.php?cashid=$accnt[cashid]'>Cancel</td>";
                }
                $OUTPUT .= "</tr>";
            } elseif ($accnt['bt'] == "transfer") {
                $refnum = getrefnum();
                extract($accnt);
                db_connect();
                $sql = "SELECT accname, bankname FROM bankacct WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
                $fbankRslt = db_exec($sql);
                $fbank = pg_fetch_array($fbankRslt);
                $sql = "SELECT accname, bankname FROM bankacct WHERE bankid = '{$rid}' AND div = '" . USER_DIV . "'";
                $tbankRslt = db_exec($sql);
                $tbank = pg_fetch_array($tbankRslt);
                $faccid = getbankaccid($bankid);
                $taccid = getbankaccid($rid);
                # write trans
                writetrans($taccid, $faccid, $date, $refnum, $amount, $descript);
                # Record the payment record
                db_connect();
                $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, div, reference) VALUES ('{$bankid}', 'withdrawal', '{$date}', '{$tbank['accname']} - {$tbank['bankname']}', '{$descript}', '{$cheqnum}', '{$amount}', 'no', '{$taccid}', '" . USER_DIV . "', '{$reference}')";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                $lcashid = pglib_lastid("cashbook", "cashid");
                $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, div, reference) VALUES ('{$rid}', 'deposit', '{$date}', '{$fbank['accname']} - {$fbank['bankname']}', '{$descript}', '{$cheqnum}', '{$amount}', 'no', '{$faccid}', '" . USER_DIV . "', '{$reference}')";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                $lcashid2 = pglib_lastid("cashbook", "cashid");
                # restore link
                $sql = "UPDATE cashbook SET lcashid = '{$lcashid2}' WHERE cashid = '{$lcashid}'";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                $sql = "UPDATE cashbook SET lcashid = '{$lcashid}' WHERE cashid = '{$lcashid2}'";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                db_connect();
                $Sl = "DELETE FROM batch_cashbook WHERE cashid='{$accnt['cashid']}'";
                $Ri = db_exec($Sl);
            } else {
                $refnum = getrefnum();
                if (strlen($accnt['accids']) > 0) {
                    $accids = explode("|", $accnt['accids']);
                    $vatcodes = explode("|", $accnt['vatcodes']);
                    $amounts = explode("|", $accnt['amounts']);
                    $vats = explode("|", $accnt['vats']);
                    $chrgvats = explode("|", $accnt['chrgvats']);
                    $refnum = getrefnum();
                    $descript = $accnt['descript'];
                    $date = $accnt["date"];
                    foreach ($amounts as $key => $amount) {
                        # SQL Array Rule: Thou shalt skip Zero Reference
                        if ($key < 1) {
                            continue;
                        }
                        $accid = $accids[$key];
                        $vat = $vats[$key];
                        $chrgvat = $chrgvats[$key];
                        //$amount -= $vat;
                        $vatcode = $vatcodes[$key];
                        db_conn('cubit');
                        $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}'";
                        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                        $vd = pg_fetch_array($Ri);
                        if ($accnt['trantype'] != "deposit") {
                            $vatacc = gethook("accnum", "salesacc", "name", "VAT", "a");
                            # DT(account involved), CT(bank)
                            writetrans($accid, $banklnk['accnum'], $date, $refnum, $amount - $vat, $descript);
                            if ($vat != 0) {
                                # DT(Vat), CT(Bank)
                                writetrans($vatacc, $banklnk['accnum'], $date, $refnum, $vat, "{$descript}");
                                vatr($vd['id'], $accnt['date'], "INPUT", $vd['code'], $refnum, $accnt['descript'], -$amount, -$vat);
                            }
                        } else {
                            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                            # DT(bank), CT(account invoilved)
                            writetrans($banklnk['accnum'], $accid, $date, $refnum, $amount - $vat, $descript);
                            if ($vat != 0) {
                                # DT(Vat), CT(Bank)
                                writetrans($banklnk['accnum'], $vatacc, $date, $refnum, $vat, "{$descript}");
                                vatr($vd['id'], $accnt['date'], "OUTPUT", $vd['code'], $refnum, $accnt['descript'], $amount, $vat);
                            }
                        }
                    }
                    db_connect();
                    $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accids, amounts, chrgvats, vats, div, vatcode, reference) VALUES ('{$accnt['bankid']}', 'withdrawal', '{$accnt['date']}', '{$accnt['name']}', '{$accnt['descript']}', '{$accnt['cheqnum']}', '{$accnt['amount']}', 'no', '{$accnt['accids']}', '{$accnt['amounts']}', '{$accnt['chrgvats']}', '{$accnt['vats']}', '" . USER_DIV . "','{$accnt['vatcode']}', '{$accnt['reference']}')";
                    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                } else {
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$accnt['vatcode']}'";
                    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                    $vd = pg_fetch_array($Ri);
                    # Record the payment record
                    db_connect();
                    $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div, vatcode, reference) VALUES ('{$bankid}', 'withdrawal', '{$accnt['date']}', '{$accnt['name']}', '{$accnt['descript']}', '{$accnt['cheqnum']}', '{$accnt['amount']}', '{$accnt['vat']}', '{$accnt['chrgvat']}', 'no', '{$accnt['accinv']}', '" . USER_DIV . "','{$accnt['vatcode']}', '{$accnt['reference']}')";
                    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                    vatr($vd['id'], $accnt['date'], "INPUT", $vd['code'], $refnum, $accnt['descript'], -$accnt['amount'], -$accnt['vat']);
                    # DT(account involved), CT(bank)
                    writetrans($accnt['accinv'], $banklnk['accnum'], $accnt['date'], $refnum, $accnt['amount'] - $accnt['vat'], $accnt['descript']);
                    if ($accnt['vat'] != 0) {
                        # DT(Vat), CT(Bank)
                        writetrans($vatacc, $banklnk['accnum'], $accnt['date'], $refnum, $accnt['vat'], $accnt['descript']);
                    }
                }
                db_connect();
                $Sl = "DELETE FROM batch_cashbook WHERE cashid='{$accnt['cashid']}'";
                $Ri = db_exec($Sl);
                continue;
                if (strlen($accnt['accids']) > 0) {
                    $acc['accname'] = "<a href=# onClick=openSmallWindow('multi-acc-popup.php?cashid={$accnt['cashid']}')>Multiple Accounts</a>";
                    $acc['accno'] = "";
                } else {
                    # get account name for the account involved
                    $AccRslt = get("core", "accname, topacc, accnum", "accounts", "accid", $accnt['accinv']);
                    $acc = pg_fetch_array($AccRslt);
                    $acc['accno'] = "{$acc['topacc']}/{$acc['accnum']}";
                }
                # get account name for bank account
                db_connect();
                $sql = "SELECT accname,btype FROM bankacct WHERE bankid= '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
                $bnameRslt = db_exec($sql);
                $bname = pg_fetch_array($bnameRslt);
                $ptotal += $accnt['amount'];
                //add to total
                $accnt['amount'] = sprint($accnt['amount']);
                $accnt['date'] = ext_rdate($accnt['date']);
                if ($bname['btype'] != "loc") {
                    $ex = "/ {$fc} {$accnt['famount']}";
                } else {
                    $ex = "";
                }
                $OUTPUT .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>{$accnt['date']}</td>\n\t\t\t\t\t\t\t<td align='center'>{$bname['accname']}</td>\n\t\t\t\t\t\t\t<td align='center'>{$accnt['cheqnum']}</td>\n\t\t\t\t\t\t\t<td align='center'>{$accnt['name']}</td>\n\t\t\t\t\t\t\t<td>{$accnt['descript']}</td>\n\t\t\t\t\t\t\t<td>{$acc['accno']}  {$acc['accname']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$accnt['amount']} {$ex}</td>";
                if ($accnt['banked'] == "no" && $accnt['opt'] != 'n') {
                    //$OUTPUT .= "<td><a href='batch-enytry-delete.php?id=$accnt[cashid]'>Delete</td>";
                    $OUTPUT .= "<input type='hidden' name='pro[" . $accnt['cashid'] . "]' value='1'>";
                    //$OUTPUT .= "<td><a href='../bank/cheq-return.php?cashid=$accnt[cashid]'>Returned/Unpaid</td>";
                    // $OUTPUT .= "<td><a href='../bank/cheq-cancel.php?cashid=$accnt[cashid]'>Cancel</td>";
                }
                $OUTPUT .= "</tr>";
            }
        }
        # print the total
        $OUTPUT .= "\n\t\t\t<tr class='" . bg_class() . "''>\n\t\t\t\t<td colspan='6'><b>Total Payments</b></td>\n\t\t\t\t<td><b>" . CUR . " " . sprintf("%01.2f", $ptotal) . "</b></td>\n\t\t\t</tr>";
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $OUTPUT = "\n\t\t\t\t<table " . TMPL_tblDflts . " width='25%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Done</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t<td>Batch entries have been processed.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table><br>" . mkQuickLinks(ql("../core/acc-new2.php", "Add New Account"));
    return $OUTPUT;
}
function write()
{
    extract($_REQUEST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $sndate = "{$ninv_year}-{$ninv_month}-{$ninv_day}";
    if (!checkdate($ninv_month, $ninv_day, $ninv_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    pglib_transaction("BEGIN");
    // Get invoice info
    $sql = "SELECT * FROM cubit.nons_invoices WHERE invid='{$invid}' AND div='" . USER_DIV . "'";
    $inv_rslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($inv_rslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($inv_rslt);
    $TOTAL = $inv["subtot"] + $inv["vat"];
    $notenum = pglib_lastid("cubit.nons_inv_notes", "noteid");
    $notenum++;
    // Add to the non stock credit notes
    $sql = "\r\n\t\tINSERT INTO cubit.nons_inv_notes (\r\n\t\t\tinvid, invnum, cusname, cusaddr, cusvatno, chrgvat, \r\n\t\t\tdate, subtot, vat, total, username, prd, notenum, ctyp, \r\n\t\t\tremarks, div\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['chrgvat']}', \r\n\t\t\t'{$sndate}', '{$inv['subtot']}', '{$inv['vat']}', '{$TOTAL}', '" . USER_NAME . "', '" . PRD_DB . "', '{$notenum}', '{$inv['ctyp']}', \r\n\t\t\t'{$inv['remarks']}', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to save credit note.");
    $noteid = pglib_lastid("cubit.nons_inv_notes", "noteid");
    $sql = "SELECT count(id) FROM cubit.nons_inv_items WHERE invid='{$invid}'";
    $count_rslt = db_exec($sql) or errDie("Unable to retrieve amount of items.");
    $item_count = pg_fetch_result($count_rslt, 0);
    $i = 0;
    $page = 0;
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM cubit.nons_inv_items WHERE invid='{$invid}' AND id='{$id}'";
        $item_rslt = db_exec($sql) or errDie("Unable to retrieve item.");
        $item_data = pg_fetch_array($item_rslt);
        if ($item_data['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        // Time for a new page ??
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $products[$page][] = "\r\n\t\t\t<tr valign='top'>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>\r\n\t\t\t\t\t{$ex} {$item_data['description']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>\r\n\t\t\t\t\t{$item_data['qty']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000' align='right' nowrap>\r\n\t\t\t\t\t" . CUR . " {$item_data['unitcost']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$item_data['amt']}&nbsp;</td>\r\n\t\t\t</tr>";
        $i++;
        // Create credit note item
        $sql = "\r\n\t\t\tINSERT INTO cubit.nons_note_items (\r\n\t\t\t\tnoteid, qty, description, amt, unitcost, \r\n\t\t\t\tvatcode\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$noteid}', '{$qtys[$key]}', '{$item_data['description']}', '{$amts[$key]}', '{$item_data['unitcost']}', \r\n\t\t\t\t'{$item_data['vatex']}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to create credit note item.");
        $sql = "SELECT grpid FROM cubit.assets WHERE id='{$item_data['asset_id']}'";
        $group_rslt = db_exec($sql) or errDie("Unable to retrieve group.");
        $group_id = pg_fetch_result($group_rslt, 0);
        $discount = $inv["discount"] / $item_count;
        $amt = $item_data["amt"];
        // Update royalty report and detail report
        $sql = "\r\n\t\t\tINSERT INTO hire.revenue (\r\n\t\t\t\tgroup_id, asset_id, total, discount, credit\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$group_id}', '{$item_data['asset_id']}', '-{$amt}', '-{$discount}', '1'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to update revenue.");
        $i++;
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t</tr>";
        }
    }
    // Retrieve customer debt account
    $sql = "\r\n\t\tSELECT debtacc FROM exten.departments \r\n\t\t\tLEFT JOIN cubit.customers ON departments.deptid=customers.deptid\r\n\t\tWHERE cusnum='{$inv['cusid']}'";
    $dept_rslt = db_exec($sql) or errDie("Unable to retrieve departments.");
    $debtacc = pg_fetch_result($dept_rslt, 0);
    $hireacc = $inv["accid"];
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "vat");
    $refnum = getrefnum();
    writetrans($hireacc, $debtacc, $sndate, $refnum, $inv["subtot"], "Non-Stock Invoice No. {$inv['invnum']} Credit Note No. {$noteid} Customer\r\n\t\t{$inv['cusname']}");
    if ($inv["vat"] != 0) {
        writetrans($vatacc, $debtacc, $sndate, $refnum, $inv["vat"], "Non-Stock Invoice No. {$inv['invnum']} Credit Note No. {$noteid} VAT.\r\n\t\tCustomer {$inv['cusname']}");
    }
    // Record on the statement
    $sql = "\r\n\t\tINSERT INTO cubit.stmnt (\r\n\t\t\tcusnum, invid, amount, date, type, \r\n\t\t\tdiv\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['cusid']}', '{$noteid}', '-{$TOTAL}', '{$sndate}', 'Non-Stock Credit Note, for invoice {$inv['invnum']}', \r\n\t\t\t'" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to insert to customer statement.");
    // Update the customer (Make the balance less)
    $sql = "UPDATE cubit.customers SET balance=(balance-'{$TOTAL}') WHERE cusnum='{$inv['cusid']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Update the customer (Make the balance less)
    $sql = "UPDATE cubit.open_stmnt SET balance=(balance-'{$TOTAL}') WHERE cusnum='{$inv['cusid']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Create ledger record
    custledger($inv["cusid"], $hireacc, $sndate, $noteid, "Non-Stock Credit Note {$noteid}", $TOTAL, "c");
    custCT($inv["total"], $inv["cusid"], $inv["odate"]);
    // Update non-stock invoice
    $sql = "UPDATE cubit.nons_invoices SET balance=(balance-'{$TOTAL}') WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to update non-stock invoice.");
    $sql = "\r\n\t\tINSERT INTO cubit.salesrec (\r\n\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\r\n\t\t) VALUES (\r\n\t\t\t'{$sndate}', '{$noteid}', '{$notenum}', '0', '{$inv['vat']}', '{$TOTAL}', 'nnon', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to record in sales.");
    $sql = "\r\n\t\tINSERT INTO cubit.sj (\r\n\t\t\tcid, name, des, date, \r\n\t\t\texl, vat, inc, div\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['cusid']}', '{$inv['cusname']}', 'Credit Note: {$noteid} Invoice {$inv['invnum']}', '{$sndate}', \r\n\t\t\t'-" . ($TOTAL - $inv["vat"]) . "', '{$inv['vat']}', '" . -sprint($TOTAL) . "', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to record in sj.");
    $sql = "UPDATE cubit.nons_invoices SET accepted='note' WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to update invoice.");
    com_invoice($inv["salespn"], -($TOTAL - $inv["vat"]), 0, $inv["invnum"], $sndate);
    $cc = "\r\n\t\t<script>\r\n\t\t\tCostCenter('ct', 'Credit Note', '{$sndate}',\r\n\t\t\t'Non Stock Credit Note No.{$noteid}', '" . ($TOTAL - $inv["vat"]) . "', '');\r\n\t   </script>";
    // Reverse the amounts on the coastal reports -----------------------------
    $sql = "UPDATE hire.assets_hired SET value=0 WHERE invid='{$inv['hire_invid']}'";
    db_exec($sql) or errDie("Unable to update asset hired records.");
    // Vat
    $sql = "SELECT id FROM cubit.vatcodes WHERE code='01'";
    $vd_rslt = db_exec($sql) or errDie("Unable to retrieve vatcodes.");
    $vd_id = pg_fetch_result($vd_rslt, 0);
    vatr($vd_id, $sndate, "OUTPUT", "01", $refnum, "Non-Stock Sales, invoice No.{$inv['invnum']}", $TOTAL, $inv["vat"]);
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank.");
    $bank_data = pg_fetch_array($bank_rslt);
    // Retrieve customer information
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
    $cust_data = pg_fetch_array($cust_rslt);
    if ($inv['cusid'] == "0") {
        $cust_data['surname'] = $inv['cusname'];
        $cust_data['addr1'] = $inv['cusaddr'];
        $cust_data['paddr1'] = $inv['cusaddr'];
    }
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $details .= "\r\n\t\t\t<center>\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td align='left' rowspan='2'><img src='../compinfo/getimg.php' width='230' height='47'></td>\r\n\t\t\t\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t\t\t\t<td align='right'><font size='5'><b>Tax Credit Note</b></font></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Credit Note No:</b> {$noteid}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$inv['invnum']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td align='center'><font size='4'><b>Credit Note To:</b></font></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cust_data['surname']}</b></td>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\r\n\t\t\t\t\t\t\t\t<td>&nbsp</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000' align='right'><b>Unit Price</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t{$products_out}\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td>{$remarks}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t\t\t\t<td><b>Trade Discount:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['discount']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['subtot']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['vat']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " " . sprint($TOTAL) . "</b></td>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>";
    }
    pglib_transaction("COMMIT");
    $OUTPUT = $details;
    require "../tmpl-print.php";
}
function con_data($_POST)
{
    # get vars
    extract($_POST);
    if (isset($back)) {
        return view_data($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($id, "num", 0, 100, "Invalid number.");
    $v->isOk($depamt, "float", 0, 14, "Invalid Depreciation Amount.");
    $v->isOk($depmonths, "num", 0, 3, "Invalid auto depreciation period.");
    $v->isOk("{$depmonths}{$depamt}", "float", 1, 14, "Enter one of Depreciation amount or period.");
    if (!empty($depamt) && $netval < $depamt) {
        $v->isOk("###", "float", 1, 1, "Error : Depreciation amount must not be more than the Net Value.");
    } else {
        if (!empty($depmonths) && $depperc <= 0) {
            $v->addError("###", "Depriaction percentage has to be more than 0 if depreciating by period.");
        }
    }
    $v->isOk($date, "date", 1, 14, "Invalid account open date.");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class=err>" . $e["msg"];
        }
        $confirmCust .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    db_conn('cubit');
    $user = USER_NAME;
    $Sql = "SELECT * FROM assets WHERE (id='{$id}' AND div = '" . USER_DIV . "')";
    $Rslt = db_exec($Sql) or errDie("Unable to access database.");
    if (pg_numrows($Rslt) < 1) {
        return "Asset not Found";
    }
    $led = pg_fetch_array($Rslt);
    # Get group
    $sql = "SELECT * FROM assetgrp WHERE grpid = '{$led['grpid']}' AND div = '" . USER_DIV . "'";
    $grpRslt = db_exec($sql);
    $grp = pg_fetch_array($grpRslt);
    # get last ref number
    $refnum = getrefnum($date);
    if ($led["dep_acc"]) {
        $dep_acc = $led["dep_acc"];
    } else {
        // Maintain backwards compatibiltiy
        $sql = "\r\n\t\tSELECT accid FROM core.accounts\r\n\t\tWHERE topacc='2200' AND accnum='000'";
        $acc_rslt = db_exec($sql) or errDie("Unable to retrieve account.");
        $dep_acc = pg_fetch_result($acc_rslt, 0);
    }
    if ($led["accdep_acc"]) {
        $accdep_acc = $led["accdep_acc"];
    } else {
        // Maintain backwards compatibiltiy
        $accdep_acc = $grp["accdacc"];
    }
    pglib_transaction("BEGIN");
    # dt(depacc) ct(accdep)
    writetrans($dep_acc, $accdep_acc, $date, $refnum, $depamt, "{$led['des']} Depreciation");
    db_connect();
    $sql = "UPDATE assets SET accdep = (accdep + '{$depamt}') WHERE (id='{$id}' AND div = '" . USER_DIV . "')";
    $up = db_exec($sql) or errdie("Could not update assets table.");
    $snetval = $netval - $depamt;
    $sdate = date("Y-m-d");
    $sql = "INSERT INTO assetledger(assetid, asset, date, depamt, netval, div) \r\n\t\t\tVALUES ('{$id}', '{$led['des']}', '{$date}', '{$depamt}', '{$snetval}', '" . USER_DIV . "')";
    $rec = db_exec($sql) or errdie("Could not write to asset ledger.");
    $cc = "<script> CostCenter('ct', 'Asset Depreciation', '{$date}', '{$led['des']} Depreciation', '{$depamt}', ''); </script>";
    pglib_transaction("COMMIT");
    $write = "\r\n\t\t\t\t{$cc}\r\n\t\t\t\t<table " . TMPL_tblDflts . " width='50%'>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Asset Depreciation</th>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='datacell'>\r\n\t\t\t\t\t\t<td>Asset Depreciation has been recorded</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</table>\r\n\t\t\t\t<p>\r\n\t\t\t\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Quick Links</th>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td><a href='asset-new.php'>New Asset</a></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td><a href='asset-view.php'>View Assets</a></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t\t</table>";
    return $write;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($supid, "num", 1, 50, "Invalid Supplier number.");
    $v->isOk($accid, "num", 1, 50, "Invalid Contra Account.");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    $v->isOk($amount, "float", 1, 20, "Invalid Amount.");
    $v->isOk($details, "string", 0, 255, "Invalid Details.");
    $v->isOk($author, "string", 1, 30, "Invalid Authorising person name.");
    $datea = explode("-", $date);
    if (count($datea) == 3) {
        if (!checkdate($datea[1], $datea[2], $datea[0])) {
            $v->isOk($date, "num", 1, 1, "Invalid date.");
        }
    } else {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class=err>" . $e["msg"];
        }
        $write .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    $td = $date;
    # Accounts details
    $accRs = get("core", "*", "accounts", "accid", $accid);
    $acc = pg_fetch_array($accRs);
    # Select supplier
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $suppRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($suppRslt) < 1) {
        return "<li> Invalid Supplier ID.";
    } else {
        $supp = pg_fetch_array($suppRslt);
    }
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$supp['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        return "<i class=err>Department Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    $famt = sprint($amount);
    $amount = sprint($amount * $rate);
    # update all supplies xchange rate first
    xrate_update($supp['fcid'], $rate, "suppurch", "id");
    sup_xrate_update($supp['fcid'], $rate);
    $supp['supname'] = remval($supp['supname']);
    # Probe tran type
    if ($entry == "CT") {
        # Write transaction  (debit contra account, credit debtors control)
        writetrans($accid, $dept['credacc'], $td, $refnum, $amount, $details . " - Supplier {$supp['supname']}");
        $tran = "<tr class='bg-odd'><td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td><td>{$supp['supno']} - {$supp['supname']}</td></tr>";
        $samount = $amount;
        $sfamt = $famt;
        // recordCT(-$amount, $supp['supid']);
        frecordCT($famt, $amount, $supp['supid'], $supp['fcid'], $td);
        $type = 'c';
    } else {
        # Write transaction  (debit debtors control, credit contra account)
        writetrans($dept['credacc'], $accid, $td, $refnum, $amount, $details . " - Supplier {$supp['supname']}");
        $tran = "<tr class='bg-odd'><td>{$supp['supno']} - {$supp['supname']}</td><td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td></tr>";
        $samount = sprint($amount - $amount * 2);
        $sfamt = sprint($famt - $famt * 2);
        // recordDT($amount, $supp['supid']);
        frecordDT($famt, $amount, $supp['supid'], $supp['fcid'], $td);
        $type = 'd';
    }
    db_connect();
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $edate = date("Y-m-d");
    # record the payment on the statement
    $sql = "INSERT INTO sup_stmnt(supid, edate, ref, cacc, descript, amount, div) VALUES('{$supp['supid']}', '{$td}', '0', '{$accid}', '{$details}', '{$sfamt}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$samount}'),fbalance = (fbalance + '{$sfamt}') WHERE supid = '{$supp['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update supplier in Cubit.", SELF);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Ledger Records
    suppledger($supp['supid'], $accid, $td, $refnum, $details, $amount, $type);
    db_connect();
    // Start layout
    $write = "<h3>Journal transaction has been recorded</h3>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><td width=50%><h3>Debit</h3></td><td width=50%><h3>Credit</h3></td></tr>\n\t\t{$tran}\n\t\t<tr><td><br></td></tr>\n\t\t<tr colspan=2><td><h4>Amount</h4></td></tr>\n\t\t<tr class='bg-even'><td colspan=2><b>" . CUR . " {$famt}</b></td></tr>\n\t</table>\n\t<P>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=25%>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class=datacell><td align=center><a href='trans-new.php'>Journal Transactions</td></tr>\n\t\t<tr class='bg-odd'><td align=center><a href='../supp-view.php'>View Suppliers</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $ddate = $dyear . "-" . $dmon . "-" . $dday;
    if (!checkdate($dmon, $dday, $dyear)) {
        $v->isOk($ddate, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qtys[$keys], "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitamts[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($stkacc[$keys], "num", 1, 10, "Invalid Item Account number : <b>" . ($keys + 1) . "</b>");
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : no products selected.");
    }
    $prd += 0;
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get Order info
    db_conn($prd);
    $sql = "SELECT * FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get supplier");
    if (pg_numrows($supRslt) < 1) {
        $error = "<li class='err'> Supplier not Found.</li>";
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    } else {
        $sup = pg_fetch_array($supRslt);
        $pur['supplier'] = $sup['supname'];
        $pur['supaddr'] = $sup['supaddr'];
        # Get department info
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$sup['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            return "<i class='err'>Department Not Found</i>";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $supacc = $dept['credacc'];
    }
    # Insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_connect();
    # Update all supplies xchange rate first
    xrate_update($pur['fcid'], $pur['xrate'], "suppurch", "id");
    sup_xrate_update($pur['fcid'], $pur['xrate']);
    db_connect();
    $retax = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            db_conn($prd);
            $sql = "SELECT * FROM nons_purint_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # the unitcost + delivery charges * qty
            $famt[$keys] = sprint($unitamts[$keys] * $qtys[$keys]);
            # calculate tax
            $ftaxes[$keys] = svat($famt[$keys], $pur['subtot'], $pur['tax']);
            $amt[$keys] = sprint($unitamts[$keys] * $pur['xrate'] * $qtys[$keys]);
            # calculate tax
            $retax += sprint($ftaxes[$keys] * $pur['xrate']);
            # Update Order items
            $sql = "UPDATE nons_purint_items SET rqty = (rqty + '{$qtys[$keys]}'), accid = '{$stkacc[$keys]}' WHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            # keep records for transactions
            if (isset($totstkamt[$stkacc[$keys]])) {
                $totstkamt[$stkacc[$keys]] += $amt[$keys];
            } else {
                $totstkamt[$stkacc[$keys]] = $amt[$keys];
            }
        }
    }
    /* Transactions */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $refnum = getrefnum();
    $sdate = $pur["pdate"];
    //$ddate;
    /* - End Hooks - */
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        # Debit Stock and Credit Suppliers control
        writetrans($supacc, $stkacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. {$pur['purnum']} Returned to Supplier {$sup['supname']}.");
    }
    db_connect();
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['cusid']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        return "Please select the vatcode for all your stock.";
    }
    $vd = pg_fetch_array($Ri);
    if ($retax > 0) {
        writetrans($supacc, $vatacc, date("d-m-Y"), $refnum, $retax, "Returned, Non-Stock Purchase Vat paid on Non-Stock Order No. {$pur['purnum']}.");
    }
    $retot = sprint(array_sum($amt) + $retax);
    vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Returned, Non-Stock Purchase Vat paid on Non-Stock Order No. {$pur['purnum']}.", $retot, $retax);
    $fretot = sprint(array_sum($famt) + array_sum($ftaxes));
    suppledger($sup['supid'], $stkacc, $sdate, $pur['purid'], "Returned, Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'd');
    db_connect();
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance - '{$retot}'), fbalance = (fbalance - '{$fretot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$sup['supid']}','{$sdate}', '{$dept['credacc']}', '-{$fretot}','Returned, Non Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}','" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    db_connect();
    # make transaction record for age analysis
    $sql = "INSERT INTO suppurch(supid, purid, pdate, fcid, balance, fbalance, div) VALUES('{$sup['supid']}', '{$pur['purnum']}', '{$sdate}', '{$pur['fcid']}', '-{$retot}', '-{$fretot}', '" . USER_DIV . "')";
    $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    db_conn($prd);
    # check if there are any outstanding items
    $sql = "SELECT * FROM nons_purint_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # if none the set to received
    if (pg_numrows($stkdRslt) < 1) {
        # update surch_int(received = 'y')
        $sql = "UPDATE nons_purch_int SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        //$rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.",SELF);
    }
    # Update Order on the DB
    $sql = "UPDATE nons_purch_int SET refno = '{$refno}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.",SELF);
    /* End Transactions */
    /* Start moving if Order received */
    db_conn($prd);
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $sql = "SELECT * FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $rdate = date("Y-m-d");
    # copy Order
    db_conn($prd);
    $sql = "INSERT INTO rnons_purch_int(purid, deptid, supid, supplier, supaddr, terms, pdate, ddate, shipchrg, xrate, fcid, curr, currency, shipping, subtot, total, balance, tax, remarks, refno, received, done, div, purnum, rdate)";
    $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['xrate']}', '{$pur['fcid']}', '{$pur['curr']}', '{$pur['currency']}', '{$pur['shipping']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['tax']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}', '{$rdate}')";
    $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Order to Cubit.", SELF);
    db_connect();
    db_conn($prd);
    # get selected stock
    $sql = "SELECT * FROM nons_purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stktcRslt = db_exec($sql);
    while ($stktc = pg_fetch_array($stktcRslt)) {
        # Insert Order items
        db_conn($prd);
        $sql = "INSERT INTO rnons_purint_items(purid, cod, des, qty, unitcost, cunitcost, duty, dutyp, amt, accid, div) VALUES('{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['cunitcost']}', '{$stktc['duty']}', '{$stktc['dutyp']}', '{$stktc['amt']}', '{$stktc['accid']}', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
    }
    db_connect();
    # Remove the Order from running DB
    $sql = "DELETE FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.",SELF);
    # Remove those Order items from running DB
    $sql = "DELETE FROM nons_purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.",SELF);
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving Order received */
    $cc = "<script> CostCenter('dt', 'Returned, International Non-Stock Purchase', '{$pur['pdate']}', 'Returned, Non Stock Purchase No.{$pur['purnum']}', '" . sprint($retot - $retax) . "', ''); </script>";
    // Final Layout
    $write = "{$cc}\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>International Non-Stock Order received</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>International Non-Stock Order receipt has been recorded.</td>\n\t\t</tr>\n\t</table>\n\t<p>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='nons-purch-int-view.php'>View International Orders</a></td>\n\t\t</tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function decrease_stock($stkid, $qty)
{
    $sysdate = date("Y-m-d");
    $sql = "\n\t\tSELECT stkcod, stkdes, csprice FROM cubit.stock\n\t\t\tWHERE stkid='{$stkid}'";
    $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
    list($stkcod, $stkdes, $csprice) = pg_fetch_array($stock_rslt);
    $price = $csprice * $qty;
    $sql = "\n\t\tUPDATE cubit.stock SET units=(units-'{$qty}'), csamt=(csamt-'{$price}')\n\t\t\tWHERE stkid='{$stkid}'";
    db_exec($sql) or errDie("Unable to decrease stock.");
    $inventory_acc = qryAccountsName("Inventory");
    $inventory_acc = $inventory_acc["accid"];
    // Stock take suspense
    $inventory_suspense_acc = qryAccountsName("Stock Take Suspense Account");
    $inventory_suspense_acc = $inventory_suspense_acc["accid"];
    $refnum = getRefnum();
    stockrec($stkid, $stkcod, $stkdes, "ct", $sysdate, $qty, $price, "Stock Take Adjustment");
    writetrans($inventory_suspense_acc, $inventory_acc, $sysdate, $refnum, $price, "Stock Take Adjustment for ({$stkcod}) {$stkdes} - {$qty} Units");
    return;
}
function recvpayment_write()
{
    if (isset($_POST["btn_back"])) {
        return details($_POST);
    }
    extract($_POST);
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 10, "Invalid customer id.");
    $v->isOk($bank_acc, "num", 1, 10, "Invalid cash account selected.");
    $v->isOk($pcc, "float", 1, 40, "Invalid credit card amount.");
    $v->isOk($pcash, "float", 1, 40, "Invalid cash amount.");
    $v->isOk($pcheque, "float", 1, 40, "Invalid cheque amount.");
    $v->isOk($amt, "float", 1, 40, "Invalid total received amount.");
    $v->isOk($out, "float", 1, 40, "Invalid unallocated amount.");
    $v->isOk($descript, "string", 1, 255, "Invalid description.");
    $v->isOk($date, "date", 1, 1, "Invalid invoice date.");
    if ($v->isError()) {
        return details($_POST, $v->genErrors());
    }
    $sdate = $date;
    $cus = qryCustomer($cusnum);
    $dept = qryDepartment($cus["deptid"], "debtacc");
    $refnum = getrefnum();
    pglib_transaction("BEGIN");
    /* do the calculations/recordings */
    # update the customer (make balance less)
    $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt}'::numeric(13,2))\n\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)) {
        foreach ($invids as $key => $value) {
            $ii = $invids[$key];
            /* OPTION 1: STOCK INVOICES */
            if (!isset($itype[$ii]) && !isset($ptype[$ii])) {
                $sql = "SELECT prd,invnum,odate FROM 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.";
                }
                $inv = pg_fetch_array($invRslt);
                $inv['invnum'] += 0;
                // reduce invoice balance
                $sql = "UPDATE cubit.invoices\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,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 = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,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\tINSERT INTO cubit.stmnt \n\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}', '" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank_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 = "SELECT prd,invnum,descrip,age,odate FROM 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\tSET balance = (balance - {$paidamt[$key]}::numeric(13,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 = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,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\tINSERT INTO cubit.stmnt \n\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}', '" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                    recordCT($paidamt[$key], $cus['cusnum'], $inv['age'], $sdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                } else {
                    /* pos invoices */
                    $sql = "SELECT * FROM cubit.prd_pinvoices\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 = "UPDATE \"{$inv['iprd']}\".pinvoices\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,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 = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,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\tINSERT INTO cubit.stmnt\n\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}', '" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                    recordCT($paidamt[$key], $cus['cusnum'], 0, $sdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    //$rages .= "|$inv[age]";
                    $invidsers .= " - {$inv['invnum']}";
                }
            }
        }
    }
    writetrans($bank_acc, $dept['debtacc'], $sdate, $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='{$cusnum}'"), 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 .= "<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>";
                $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 .= "<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<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>";
                $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, $sdate);
        $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", $sdate));
        $dbobj = new dbUpdate("stmnt", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        custledger($cus['cusnum'], $bank_acc, $sdate, "PAYMENT", "Payment received.", $out, "c");
    }
    $sql = "INSERT INTO cubit.payrec(date,by,multiinv,amount,method,prd,note)\n\t\t\tVALUES('{$sdate}','" . USER_NAME . "', '{$invidsers}', '{$pcash}','Cash','" . PRD_DB . "','0')";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.payrec(date,by,multiinv,amount,method,prd,note)\n\t\t\tVALUES('{$sdate}','" . USER_NAME . "', '{$invidsers}', '{$pcc}','Credit Card','" . PRD_DB . "','0')";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.payrec(date,by,multiinv,amount,method,prd,note)\n\t\t\tVALUES('{$sdate}','" . USER_NAME . "', '{$invidsers}', '{$pcheque}','Cheque','" . PRD_DB . "','0')";
    db_exec($sql) or errDie("Unable to insert data.");
    pglib_transaction("COMMIT");
    $_POST["pcc"] = $_POST["pcheque"] = $_POST["pcash"] = "0.00";
    return details($_POST, "<li class='err'>Payment received successfully</li>");
}
function pay($_POST)
{
    //processes
    db_connect();
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purchid, "num", 1, 20, "Invalid Purchase ID.");
    $v->isOk($paidamt, "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;
    }
    // Connect to database
    core_Connect();
    # get purchase info
    $sql = "SELECT * FROM purchases WHERE purchid = '{$purchid}'";
    $purchRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve purchase details from database.", SELF);
    $numrows = pg_numrows($purchRslt);
    if ($numrows < 1) {
        $OUTPUT = "<li clss=err>Invalid purchase ID.";
        require "template.php";
    }
    $purch = pg_fetch_array($purchRslt);
    # reduce the money that has been paid
    $sql = "UPDATE credit_purch SET amount = (amount - cast(float8 '{$paidamt}' as numeric)) WHERE purchid = '{$purchid}'";
    $payRslt = db_exec($sql) or errDie("Unable to update credit purchases table.", SELF);
    # get creditors account
    $creditacc = gethook("accnum", "pchsacc", "name", "Creditors");
    $refnum = getrefnum(date('d-m-Y'));
    writetrans($creditacc, $purch['usedacc'], date('d-m-Y'), $refnum, $paidamt, 'Pay Purchase Credit.');
    # status report
    $pay = "\r\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='100%'>\r\n        <tr><th>Credit Paid</th></tr>\r\n        <tr class=datacell><td>Credit for,<b> {$purch['itemname']}</b> bought From <b>{$purch['retailer']}</b>, was successfully paid.</td></tr>\r\n        </table>";
    # main table (layout with menu)
    $OUTPUT = "<center>\r\n        <table width = 90%>\r\n        <tr valign=top><td width=60%>{$pay}</td>\r\n        <td align=center>\r\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=80%>\r\n        <tr><th>Quick Navigation</th></tr>\r\n        <tr class=datacell><td align=center><a href='purchase-view.php'>View Other Purchases</td></tr>\r\n        <tr class=datacell><td align=center><a href='purchase-new.php'>Add New Purchase</td></tr>\r\n        </table>\r\n        </td></tr></table>";
    return $OUTPUT;
}
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return enter($_POST);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 20, "Invalid Bank ID.");
    foreach ($amount as $key => $value) {
        # check all vars
        $v->isOk($to[$key], "string", 1, 255, "Invalid receipient/depositor.");
        $v->isOk($trantype[$key], "string", 1, 20, "Invalid transaction type.");
        $v->isOk($descript[$key], "string", 0, 255, "Invalid description.");
        $v->isOk($ref[$key], "string", 0, 255, "Invalid reference <b>[{$key}]</b>.");
        $v->isOk($cheqnum[$key], "num", 0, 20, "Invalid cheque number <b>[{$key}]</b>.");
        $v->isOk($amount[$key], "float", 1, 8, "Invalid amount <b>[{$key}]</b>.");
        $v->isOk($accinv[$key], "num", 1, 20, "Invalid account involved <b>[{$key}]</b>.");
        $v->isOk($date[$key], "date", 1, 15, "Invalid date <b>[{$key}]</b>.");
        if (strtotime($date[$key]) >= strtotime($blocked_date_from) and strtotime($date[$key]) <= 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>";
        }
    }
    # 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;
    }
    # Processes
    db_connect();
    # Begin Transaction
    pglib_transaction("BEGIN");
    # Some info
    $bankacc = getbankaccid($bankid);
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    foreach ($amount as $key => $amt) {
        $totamt = $amount[$key];
        if ($chrgvat[$key] == "exc") {
            $totamt += $vat[$key];
        } elseif ($chrgvat[$key] == "inc") {
            $amount[$key] -= $vat[$key];
        } else {
            $vat[$key] = "No VAT";
        }
        if ($cheqnum[$key] == '') {
            $cheqnum[$key] = 0;
        }
        if (!isset($batch)) {
            $refnum = getrefnum();
            if (strtolower($trantype[$key]) == 'deposit') {
                $vatacc = gethook("accnum", "salesacc", "name", "VAT", "1");
                writetrans($bankacc, $accinv[$key], $date[$key], $refnum, $amount[$key], $descript[$key]);
                if ($vat[$key] != 0) {
                    # DT(Bank), CT(VAT)
                    $vat[$key] += 0;
                    writetrans($bankacc, $vatacc, $date[$key], $refnum, $vat[$key], $descript[$key] . " VAT");
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode[$key]}'";
                    $Rt = db_exec($Sl) or errDie("Unable to get data.");
                    $vd = pg_fetch_array($Rt);
                    vatr($vatcode[$key], $date[$key], "OUTPUT", $vd['code'], $refnum, $descript[$key] . " VAT", $totamt, $vat[$key]);
                }
            } else {
                $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                writetrans($accinv[$key], $bankacc, $date[$key], $refnum, $amount[$key], $descript[$key]);
                if ($vat[$key] != 0) {
                    # DT(Bank), CT(VAT)
                    $vat[$key] += 0;
                    writetrans($vatacc, $bankacc, $date[$key], $refnum, $vat[$key], $descript[$key] . " VAT");
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode[$key]}'";
                    $Rt = db_exec($Sl) or errDie("Unable to get data.");
                    $vd = pg_fetch_array($Rt);
                    vatr($vatcode[$key], $date[$key], "INPUT", $vd['code'], $refnum, $descript[$key] . " VAT", -$totamt, -$vat[$key]);
                }
            }
            $vat[$key] += 0;
            db_connect();
            $sql = "\n\t\t\t\tINSERT INTO cashbook (\n\t\t\t\t\tbankid, trantype, date, name, descript, cheqnum, \n\t\t\t\t\tamount, banked, accinv, div,chrgvat,vat,reference\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$bankid}', lower('{$trantype[$key]}'), '{$date[$key]}', '{$to[$key]}', '{$descript[$key]}', '{$cheqnum[$key]}', \n\t\t\t\t\t'{$totamt}', 'no', '{$accinv[$key]}', '" . USER_DIV . "','{$chrgvat[$key]}', '{$vat[$key]}','{$ref[$key]}'\n\t\t\t\t)";
            $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        } else {
            db_connect();
            $vat[$key] += 0;
            $sql = "\n\t\t\t\tINSERT INTO batch_cashbook (\n\t\t\t\t\tbankid, trantype, date, name, descript, cheqnum, \n\t\t\t\t\tamount, banked, accinv, div, chrgvat, vat, vatcode, \n\t\t\t\t\treference\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$bankid}', lower('{$trantype[$key]}'), '{$date[$key]}', '{$to[$key]}', '{$descript[$key]}', '{$cheqnum[$key]}', \n\t\t\t\t\t'{$totamt}', 'no', '{$accinv[$key]}', '" . USER_DIV . "','{$chrgvat[$key]}','{$vat[$key]}','{$vatcode[$key]}', \n\t\t\t\t\t'{$ref[$key]}'\n\t\t\t\t)";
            $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        }
    }
    # Get bank details
    $bankAccRslt = get("cubit", "*", "bankacct", "bankid", $bankid);
    $bankacc = pg_fetch_array($bankAccRslt);
    pglib_transaction("COMMIT");
    if (!isset($batch)) {
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Statement Recorded</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>New Statement Details for account, <b>{$bankacc['accname']} ({$bankacc['accnum']})</b><br>held at <b>{$bankacc['bankname']}</b>, was successfully added to Cubit.</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    } else {
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Batch entries recorded</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>New batch items for account, <b>{$bankacc['accname']} ({$bankacc['accnum']})</b><br>held at <b>{$bankacc['bankname']}</b>, was successfully added to Cubit.</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    # Main table (layout with menu)
    $OUTPUT = "\n\t\t<center>\n\t\t<table width='90%'>\n\t\t\t<tr valign='top'>\n\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t<td align='center'>" . mkQuickLinks(ql("bank-pay-add.php", "Add Bank Payment"), ql("bank-recpt-add.php", "Add Bank Receipt"), ql("cashbook-view.php", "View Cash Book"), ql("batch-cashbook-view.php", "View Batch Cashbook")) . "\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (!isset($proc_trans) or !is_array($proc_trans)) {
        return slctacc($_POST, "<li class='err'>Please Select Transaction(s) To Process</li>");
    }
    db_connect();
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($proc_trans as $procid => $value) {
        $get_trans = "SELECT * FROM cust_trans_batch WHERE id = '{$procid}' LIMIT 1";
        $run_trans = db_exec($get_trans) or errDie("Unable to get transaction information.");
        if (pg_numrows($run_trans) < 1) {
            return slctacc($_POST, "<li class='err'>Transaction Not Found: (ID:{$procid})</li>");
        }
        $parr = pg_fetch_array($run_trans);
        $v->isOk($parr['cusnum'], "num", 1, 50, "Invalid Customer number.");
        $v->isOk($parr['contra_account'], "num", 1, 50, "Invalid Contra Account.");
        $v->isOk($parr['ref_num'], "num", 1, 10, "Invalid Reference number.");
        $v->isOk($parr['amount'], "float", 1, 20, "Invalid Amount.");
        $v->isOk($parr['description'], "string", 0, 255, "Invalid Details.");
        // 		$v->isOk ($author, "string", 1, 30, "Invalid Authorising person name.");
        $datea = explode("-", $parr['proc_date']);
        if (count($datea) == 3) {
            if (!checkdate($datea[1], $datea[2], $datea[0])) {
                $v->isOk($parr['proc_date'], "num", 1, 1, "Invalid date. (1)");
            }
        } else {
            $v->isOk($parr['proc_date'], "num", 1, 1, "Invalid date. (2)");
        }
        $v->isOk($parr['chrg_vat'], "string", 1, 10, "Invalid Charge VAT Option.");
        // 	$v->isOk ($vatinc, "string", 1, 10, "Invalid VAT Inclusive Exclusive Option.");
        $v->isOk($parr['vatcode'], "num", 1, 5, "Invalid Vat Code Option.");
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    foreach ($proc_trans as $procid => $value) {
        db_connect();
        $get_trans = "SELECT * FROM cust_trans_batch WHERE id = '{$procid}' LIMIT 1";
        $run_trans = db_exec($get_trans) or errDie("Unable to get transaction information.");
        if (pg_numrows($run_trans) < 1) {
            return slctacc($_POST, "<li class='err'>Transaction Not Found: (ID:{$procid})</li>");
        }
        $parr = pg_fetch_array($run_trans);
        $cusnum = $parr['cusnum'];
        $vatinc = $parr['chrg_vat'];
        if (isset($vatinc) and $vatinc != "0") {
            $chrgvat = "yes";
        } else {
            $chrgvat = "no";
        }
        // 		$chrgvat = $parr['chrg_vat'];
        $vatcode = $parr['vatcode'];
        $amount = $parr['amount'];
        $type = 1;
        $entry = $parr['entry_type'];
        $date = $parr['proc_date'];
        $datea = explode("-", $parr['proc_date']);
        $accid = $parr['contra_account'];
        $refnum = $parr['ref_num'];
        $details = $parr['description'];
        if (isset($chrgvat) and $chrgvat == "yes") {
            db_connect();
            #get selected vatcode
            $get_vatcode = "SELECT * FROM vatcodes WHERE id = '{$vatcode}' LIMIT 1";
            $run_vatcode = db_exec($get_vatcode) or errDie("Unable to get vat code information.");
            if (pg_numrows($run_vatcode) < 1) {
                #vatcode not found ....
                return "<li class='err'>Unable to get vat code information.</li>";
            }
            $vd = pg_fetch_array($run_vatcode);
            if ($vatinc == "inc") {
                #vat inc ...  recalc value
                $vatamt = sprint($amount * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
                $amount = sprint($amount - $vatamt);
            } else {
                #vat excl
                $amount = sprint($amount);
                $vatamt = sprint($amount / 100 * $vd['vat_amount']);
            }
        } else {
            #vat not set
            $amount = sprint($amount);
            $vatamt = sprint(0);
        }
        // 		$date = "$datea[2]-$datea[1]-$datea[0]";
        # Accounts details
        $accRs = get("core", "*", "accounts", "accid", $accid);
        $acc = pg_fetch_array($accRs);
        # Select customer
        db_connect();
        $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
        if (pg_numrows($custRslt) < 1) {
            return slctacc($_POST, "<li class='err'>Invalid customer ID, or customer has been blocked.</li>");
        } else {
            $cust = pg_fetch_array($custRslt);
        }
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            return slctacc($_POST, "<i class='err'>Department Not Found</i>");
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        #get vat acc ...
        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
        # Begin updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        # Probe tran type
        if ($entry == "CT") {
            # Write transaction  (debit contra account, credit debtors control)
            writetrans($accid, $dept['debtacc'], $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
            $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t      <td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t      <td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t      </tr>";
            $samount = $amount - $amount * 2;
            $svatamt = $vatamt - $vatamt * 2;
            recordCT($samount, $cust['cusnum'], $date);
            $type = 'c';
            if (isset($chrgvat) and $chrgvat == "yes") {
                writetrans($vatacc, $dept['debtacc'], $date, $refnum, $vatamt, "VAT for Transaction: {$refnum} for Customer : {$cust['cusname']} {$cust['surname']}");
                vatr($vd['id'], $date, "OUTPUT", $vd['code'], $refnum, "VAT for Transaction: {$refnum} for Customer : {$cust['cusname']} {$cust['surname']}", $samount + $svatamt, $svatamt);
            }
        } else {
            # Write transaction  (debit debtors control, credit contra account)
            writetrans($dept['debtacc'], $accid, $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
            $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t</tr>";
            $samount = $amount;
            $svatamt = $vatamt;
            recordDT($samount, $cust['cusnum'], $date);
            $type = 'd';
            if (isset($chrgvat) and $chrgvat == "yes") {
                writetrans($dept['debtacc'], $vatacc, $date, $refnum, $vatamt, "VAT for Transaction: {$refnum} for Customer : {$cust['cusname']} {$cust['surname']}");
                vatr($vd['id'], $date, "OUTPUT", $vd['code'], $refnum, "VAT for Transaction: {$refnum} for Customer : {$cust['cusname']} {$cust['surname']}", $amount + $vatamt, $vatamt);
            }
        }
        db_connect();
        $sdate = date("Y-m-d");
        # record the payment on the statement
        $sql = "\n\t\t\tINSERT INTO stmnt (\n\t\t\t\tcusnum, invid, amount, date, type, st, div, allocation_date\n\t\t\t) VALUES (\n\t\t\t\t'{$cust['cusnum']}', '0', '" . sprint($samount + $svatamt) . "', '{$date}', '{$details}', 'n', '" . USER_DIV . "', '{$date}'\n\t\t\t)";
        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
        $sql = "\n\t\t\tINSERT INTO open_stmnt (\n\t\t\t\tcusnum, invid, amount, balance, date, type, st, div\n\t\t\t) VALUES (\n\t\t\t\t'{$cust['cusnum']}', '0', '" . sprint($samount + $svatamt) . "', '" . sprint($samount + $svatamt) . "', '{$date}', '{$details}', 'n', '" . USER_DIV . "'\n\t\t\t)";
        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
        # update the customer (make balance more)
        $sql = "UPDATE customers SET balance = (balance + '{$samount}') WHERE cusnum = '{$cust['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
        # Make ledge record
        //	custledger($cust['cusnum'], $accid, $date, $refnum, $details, $amount, $type);
        custledger($cust['cusnum'], $accid, $date, $refnum, $details, sprint($amount + $vatamt), $type);
        db_connect();
        $rem_batch = "DELETE FROM cust_trans_batch WHERE id = '{$procid}'";
        $run_batch = db_exec($rem_batch) or errDie("Unable to remove customer batch transaction information.");
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    }
    return slctacc($_POST, "<li class='yay'>Transaction(s) Have Been Processed.</li><br>");
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($pay as $key => $value) {
        $v->isOk($pay[$key], "num", 1, 50, "Invalid purchase No.");
        $v->isOk($paidamt[$key], "float", 1, 20, "Invalid amount to be paid. [{$key}]");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get creditors account
    $creditacc = gethook("accnum", "pchsacc", "name", "Creditors");
    $tot = 0;
    # Creditors
    $pays = "";
    foreach ($pay as $key => $value) {
        core_connect();
        # get purchase info
        $sql = "SELECT * FROM purchases WHERE purchid = '{$pay[$key]}'";
        $purchRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve purchase details from database.", SELF);
        if (pg_numrows($purchRslt) < 1) {
            $OUTPUT = "<li clss=err>Invalid purchase ID.";
            return $OUTPUT;
        }
        $purch = pg_fetch_array($purchRslt);
        # get credit purchase info
        $sql = "SELECT amount FROM credit_purch WHERE purchid = '{$pay[$key]}'";
        $ctpRslt = db_exec($sql);
        $ctp = pg_fetch_array($ctpRslt);
        # get account name for account paid
        $accRslt = get("core", "accname", "accounts", "accid", $purch['paidacc']);
        $acc = pg_fetch_array($accRslt);
        $paidacc = $acc['accname'];
        # get account name for account used
        $accRslt = get("core", "accname", "accounts", "accid", $purch['usedacc']);
        $acc = pg_fetch_array($accRslt);
        $usedacc = $acc['accname'];
        $pays .= "<tr class='bg-odd'>\n                                <input type=hidden name=pay[] value='{$pay[$key]}'>\n                                <td>{$purch['retailer']}</td>\n                                <td>{$purch['itemname']}</td>\n                                <td>{$purch['descript']}</td>\n                                <td>{$purch['quantity']}</td>\n                                <td>" . CUR . " {$ctp['amount']}</td>\n                                <td>" . CUR . " {$paidamt[$key]}</td>\n                                <td>{$usedacc}</td>\n                                <td>{$paidacc}</td>\n                        </tr>";
        # reduce the money that has been paid
        $sql = "UPDATE credit_purch SET amount = (amount - cast(float8 '{$paidamt[$key]}' as numeric)) WHERE purchid = '{$pay[$key]}'";
        $payRslt = db_exec($sql) or errDie("Unable to update credit purchases table.", SELF);
        $refnum = getrefnum(date('d-m-Y'));
        writetrans($creditacc, $purch['usedacc'], date('d-m-Y'), $refnum, $paidamt[$key], 'Pay Purchase Credit.');
        $tot += $paidamt[$key];
    }
    $write = "<center>\n        <h3>Multiple Credits Payments Processed</h3>\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n                <tr><th>Retailer</th><th>Item Name</th><th>Description</th><th>Quantity</th><th>Outstanding amount</th><th>Amount Paid</th><th>Account used</th><th>Account paid</th></tr>\n                {$pays}\n                <tr><td><br></td></tr>\n                <tr class='bg-even'><td colspan=5><b>Total Amount Paid</b></td><td colspan=2><b>" . CUR . " " . sprintf("%01.2f", round($tot, 2)) . "</b></td></tr>\n        </table>\n        <br><br><br>\n        <table border=0 cellpadding='2' cellspacing='1' width=15%>\n                <tr><th>Quick Links</th></tr>\n                <tr bgcolor='#88BBFF'><td><a href='creditors-view.php'>View Creditors</a></td></tr>\n                <script>document.write(getQuicklinkSpecial());</script>\n        </table>";
    return $write;
}
function write($_POST)
{
    //processes
    db_connect();
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusname, "string", 1, 50, "Invalid Customer name.");
    $v->isOk($addr1, "string", 1, 255, "Invalid customer address(Line 1).");
    $v->isOk($addr2, "string", 0, 255, "Invalid customer address(Line 2).");
    $v->isOk($addr3, "string", 0, 255, "Invalid customer address(Line 3).");
    $v->isOk($paddr1, "string", 0, 255, "Invalid customer postal address(Line 1).");
    $v->isOk($paddr2, "string", 0, 255, "Invalid customer postal address(Line 2).");
    $v->isOk($paddr3, "string", 0, 255, "Invalid customer postal address(Line 3).");
    $v->isOk($tel, "num", 1, 14, "Invalid telephone number.");
    $v->isOk($fax, "num", 0, 14, "Invalid fax number.");
    $v->isOk($email, "email", 0, 255, "Invalid E-mail address.");
    $v->isOk($orddate, "date", 1, 14, "Invalid order Date.");
    $v->isOk($invdate, "date", 1, 14, "Invalid invoice Date.");
    $v->isOk($stockacc, "num", 1, 255, "Invalid stock account.");
    $v->isOk($accpaid, "num", 1, 255, "Invalid account paid to.");
    # 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;
    }
    # caclulate sub totals
    $SUBTOT = 0;
    //total of subtotals
    $COSTOT = 0;
    // Cost of stock sold
    foreach ($qty as $key => $value) {
        $SUB[$key] = sprintf("%01.2f", $qty[$key] * $unitcost[$key]);
        $COST[$key] = sprintf("%01.2f", $qty[$key] * $cost[$key]);
        $COSTOT += $COST[$key];
        $SUBTOT += $SUB[$key];
    }
    #calculate vat and grand total
    $vat = sprintf("%01.2f", TAX_VAT / 100);
    $VAT = sprintf("%01.2f", $vat * $SUBTOT);
    $GRDTOT = sprintf("%01.2f", $SUBTOT + $VAT);
    # Join each item into a string and put them into an array
    foreach ($qty as $key => $value) {
        $items[$key] = "{$descript[$key]} [|] {$qty[$key]} [|] {$unitcost[$key]} [|] {$SUB[$key]}";
    }
    # Implode items into one order
    $orddes = implode("\n", $items);
    # write customer to DB
    db_connect();
    $sql = "INSERT INTO customers(cusname, addr1, addr2, addr3, paddr1, paddr2, paddr3, tel, fax, email) ";
    $sql .= "VALUES('{$cusname}', '{$addr1}', '{$addr2}', '{$addr3}',  '{$paddr1}', '{$paddr2}', '{$paddr3}', '{$tel}', '{$fax}', '{$email}')";
    $rslt = db_exec($sql) or errDie("Unable to insert customer to Cubit.", SELF);
    # write invoice to DB
    db_connect();
    $sql = "INSERT INTO invoices(cusname, addr1, addr2, addr3, tel, fax, email, orddate, invdate, orddes, grdtot, salesrep, accpaid) ";
    $sql .= "VALUES('{$cusname}', '{$addr1}', '{$addr2}', '{$addr3}', '{$tel}', '{$fax}', '{$email}', '{$orddate}', '{$invdate}', '{$orddes}', '{$GRDTOT}', '" . USER_NAME . "', '{$accpaid}')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice to Cubit.", SELF);
    # get next ordnum
    $ordnum = pglib_lastid("invoices", "ordnum");
    # get cost of sales account
    $cosacc = gethook("accnum", "salesacc", "name", "Cost Of Sales");
    # get income account
    $incomeacc = gethook("accnum", "salesacc", "name", "Income");
    $refnum = getrefnum($invdate);
    # credit income debit acc paid
    writetrans($accpaid, $incomeacc, $invdate, $refnum, $GRDTOT, "Sales Income received.");
    # credit income debit acc paid
    # writetrans( $accpaid, $incomeacc, $GRDTOT, "income received.");
    # credit stock acc and cos acc
    writetrans($cosacc, $stockacc, $invdate, $refnum, $COSTOT, "Cost of Sales.");
    # credit stock acc and cos acc
    # writetrans( $cosacc, $stockacc, $COSTOT, "income received.");
    // invoice design
    $printInv = "<center><table border=0 cellpadding=5 cellspacing=0 width='91%'>\r\n        <tr><td width='35%' align=center>\r\n\t        <img src='" . COMP_LOGO . "' width=230 height=47 alt='" . COMP_NAME . "'>\r\n        </td><td align=right>\r\n\t        " . COMP_ADDRESS . "\r\n\t        <br>Tel : " . COMP_TEL . "\r\n\t        <br>Fax : " . COMP_FAX . "\r\n        </td><tr>\r\n        <tr><td width='35%' valign=top>\r\n\t        <table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='100%' border=1>\r\n\t        <tr><th class=h4>CUSTOMER ADDRESS</th></tr>\r\n\t        <tr><td align=center>\r\n        \t\t<table border=0 cellpadding=10 cellspacing=0>\r\n\t\t        <tr><td>\r\n\t\t\t        <b>{$cusname}</b>\r\n\t\t\t        <p>{$addr1}<br>{$addr2}<br>{$addr3}\r\n                                <p>{$tel}<br>{$fax}<br>{$email}<br>\r\n\t\t        </td></tr>\r\n\t\t        </table>\r\n\t        </td></tr>\r\n\t        </table>\r\n        </td><td>\r\n        \t<!-- commeted out\r\n                <table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='100%' border=1>\r\n        \t<tr><th class=h4>DELIVERY ADDRESS</th></tr>\r\n        \t<tr><td align=center>\r\n\t\t        <table border=0 cellpadding=10 cellspacing=0>\r\n\t\t        <tr><td>\r\n        \t\t\t<b>-Customer name-</b>\r\n\t\t                <p>-Customer's Delivery Address-\r\n\t\t        </td></tr>\r\n\t\t</table>\r\n\t        </td></tr>\r\n\t        </table>\r\n                /commente out -->\r\n\r\n        </td></tr>\r\n        <tr><td colspan=2>\r\n        \t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='100%' border=1>\r\n        \t<tr><th>INVOICE No.</th><th>SALESPERSON</th><th>ORDER DATE</th><th>INVOICE DATE</th></tr>\r\n        \t<tr><td align=center>{$ordnum}</td><td align=center>" . USER_NAME . "</td><td align=center>{$orddate}</td><td align=center>{$invdate}</td></tr>\r\n        \t</table>\r\n        </td></tr>\r\n        </table>\r\n        <br>\r\n        <table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='90%' border=1>\r\n        <tr><th>CODE</th><th>DESCRIPTION</th><th>QTY</th><th>UNIT COST</th><th width=20%>SUBTOTAL</th></tr>";
    foreach ($qty as $key => $value) {
        $printInv .= "<tr><td>0000{$key}</td><td>" . stripslashes($descript[$key]) . "</td><td>{$qty[$key]}</td><td>{$unitcost[$key]}</td><td align=right>" . CUR . " {$SUB[$key]}</td></tr>";
    }
    $printInv .= "<tr><td colspan=4 align=right><b>SUBtotal</b></td><td align=right>{$SUBTOT}</td></tr>\r\n        <tr><td colspan=4 align=right><b>VAT @ " . TAX_VAT . "%</b></td><td align=right>{$VAT}</td></tr>\r\n        <tr><td colspan=4 align=right><b>GRAND total</b></td><td align=right><b>{$GRDTOT}</b></td></tr>\r\n        </table></center>\r\n        <blockquote> <table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=1>\r\n        <tr><th>VAT No.</th><td align=center>" . COMP_VATNO . "</td></tr>\r\n        </table>";
    $OUTPUT = $printInv;
    #  Print the invoice and exit
    require "tmpl-print.php";
}
function bwrite($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($prd, "num", 1, 20, "Invalid period Database number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            if ($qty > $qts[$keys]) {
                $v->isOk($qty, "num", 0, 0, "Error : Quantity for product number : <b>" . ($keys + 1) . "</b> is more that Qty Orderd");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get Order info
    db_conn($prd);
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # Get selected supplier info
    db_connect();
    if ($pur['ctyp'] == 's') {
        $supid = $pur['typeid'];
        $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql) or errDie("Unable to get supplier");
        if (pg_numrows($supRslt) < 1) {
            $error = "<li class='err'> Supplier not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $sup = pg_fetch_array($supRslt);
            $pur['supplier'] = $sup['supname'];
            $pur['supaddr'] = $sup['supaddr'];
            # Get department info
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$sup['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $supacc = $dept['credacc'];
        }
    } elseif ($pur['ctyp'] == 'c') {
        $deptid = $pur['typeid'];
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Department not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = $dept['pca'];
        }
    }
    # Insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    if (isset($qtys)) {
        # amount of stock in
        $totstkamt = array();
        $resub = 0;
        # Get subtotal
        foreach ($qtys as $keys => $value) {
            # Skip zeros
            if ($qtys[$keys] < 1) {
                continue;
            }
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        }
        $SUBTOTAL = array_sum($amt);
        $revat = 0;
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            $sql = "SELECT * FROM nons_pur_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # Calculate cost amount bought
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
            /* delivery charge */
            # Calculate percentage from subtotal
            $perc[$keys] = $amt[$keys] / $SUBTOTAL * 100;
            # Get percentage from shipping charges
            $shipc[$keys] = $perc[$keys] / 100 * $shipchrg;
            # add delivery charges
            $amt[$keys] += $shipc[$keys];
            /* end delivery charge */
            # the subtotal + delivery charges
            $resub += $amt[$keys];
            # calculate vat
            $svat[$keys] = svat($amt[$keys], $stkd['amt'], $stkd['svat']);
            # received vat
            $revat += $svat[$keys];
            # make amount vat free
            if ($pur['vatinc'] == "yes") {
                $amt[$keys] = $amt[$keys] - $svat[$keys];
            }
            # Update Order items
            $sql = "\n\t\t\t\t\tUPDATE nons_pur_items \n\t\t\t\t\tSET rqty = (rqty + '{$qtys[$keys]}'), accid = '{$stkacc[$keys]}' \n\t\t\t\t\tWHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            # keep records for transactions
            if (isset($totstkamt[$stkacc[$keys]])) {
                $totstkamt[$stkacc[$keys]] += $amt[$keys];
            } else {
                $totstkamt[$stkacc[$keys]] = $amt[$keys];
            }
            # check if there are any outstanding items
            $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            # if none the set to received
            if (pg_numrows($stkdRslt) < 1) {
                # update surch_int(received = 'y')
                $sql = "\n\t\t\t\t\t\tUPDATE nons_purchases \n\t\t\t\t\t\tSET received = 'y', supplier = '{$pur['supplier']}', supaddr = '{$pur['supaddr']}' \n\t\t\t\t\t\tWHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF);
            }
        }
    }
    # Update Order on the DB
    if ($pur['part'] == 'y') {
        # Update Order on the DB
        $sql = "\n\t\t\t\tUPDATE nons_purchases \n\t\t\t\tSET ctyp = '{$ctyp}', typeid = '{$typeid}', refno = '{$refno}', remarks = '{$remarks}' \n\t\t\t\tWHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    } else {
        # Update Order on the DB
        $sql = "\n\t\t\t\tUPDATE nons_purchases \n\t\t\t\tSET ctyp = '{$ctyp}', typeid = '{$typeid}', refno = '{$refno}', remarks = '{$remarks}' \n\t\t\t\tWHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    }
    /* Transactions */
    $refnum = getrefnum(date("d-m-Y"));
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    $detadd = "";
    if (isset($supid)) {
        $detadd = " from Supplier {$sup['supname']}";
    }
    $sdate = $pur['pdate'];
    $tpp = 0;
    $ccamt = 0;
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        # Debit Stock and Credit Suppliers control
        writetrans($stkacc, $supacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $wamt, "Cash Order");
    }
    # vat
    $vatamt = $revat;
    # Add vat if not included
    if ($pur['vatinc'] == 'no') {
        $retot = $resub + $vatamt;
    } elseif ($pur['vatinc'] == "novat") {
        $retot = $resub;
        $vatamt = 0;
    } else {
        $retot = $resub;
    }
    if (isset($supid)) {
        # Ledger Records
        $DAte = $pur['pdate'];
        suppledger($sup['supid'], $stkacc, $DAte, $pur['purid'], "Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'c');
    }
    if ($vatamt != 0) {
        # Debit bank and credit the account involved
        writetrans($vatacc, $supacc, date("d-m-Y"), $refnum, $vatamt, "Non-Stock Purchase VAT paid on Non-Stock Order No. {$pur['purnum']} {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $vatamt, "Cash Order VAT");
        # Record the payment on the statement
        db_connect();
        $sdate = $pur['pdate'];
    }
    if (isset($supid)) {
        $DAte = $pur['pdate'];
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$retot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "\n\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\tsupid, edate, cacc, amount, descript, ref, ex, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$sup['supid']}','{$DAte}', '{$dept['credacc']}', '{$retot}', 'Non Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t\t)";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        db_connect();
        # update the supplier age analysis (make balance less)
        /* Make transaction record for age analysis */
        $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']}', '{$pur['purnum']}', '{$DAte}', '{$retot}', '" . USER_DIV . "'\n\t\t\t\t)";
        $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    }
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End Transactions */
    /* Start moving if Order received */
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        # copy Order
        db_conn($pur['prd']);
        $sql = "\n\t\t\t\tINSERT INTO nons_purchases (\n\t\t\t\t\tpurid, deptid, supplier, supaddr, terms, pdate, ddate, \n\t\t\t\t\tshipchrg, shipping, subtot, total, balance, vatinc, vat, \n\t\t\t\t\tremarks, refno, received, done, ctyp, typeid, div, purnum\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', \n\t\t\t\t\t'{$pur['shipchrg']}', '{$pur['shipping']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', \n\t\t\t\t\t'{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '{$pur['ctyp']}', '{$pur['typeid']}', '" . USER_DIV . "', '{$pur['purnum']}'\n\t\t\t\t)";
        $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Order to Cubit.", SELF);
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert Order items
            db_conn($pur['prd']);
            $sql = "\n\t\t\t\t\tINSERT INTO nons_pur_items (\n\t\t\t\t\t\tpurid, cod, des, qty, unitcost, amt, \n\t\t\t\t\t\tsvat, ddate, accid, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', \n\t\t\t\t\t\t'{$stktc['svat']}', '{$stktc['ddate']}', '{$stktc['accid']}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        db_connect();
        # Remove the Order from running DB
        $sql = "DELETE FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Remove those Order items from running DB
        $sql = "DELETE FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    }
    /* End moving Order received */
    $cc = "<script> CostCenter('ct', 'Non-Stock Purchase', '{$pur['pdate']}', 'Non Stock Purchase No.{$pur['purnum']}', '" . ($retot - $vatamt) . "', ''); </script>";
    // Final Layout
    $write = "\n\t\t{$cc}\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Non-Stock Order received</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Non-Stock Order receipt has been recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='nons-purchase-view.php'>View Orders</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($supinv, "string", 0, 255, "Invalid supp inv.");
    # used to generate errors
    $error = "asa@";
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return details($_POST, $err);
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $td = $pur['pdate'];
    # check if purchase has been received
    if ($pur['invcd'] == "y") {
        $error = "<li class=err> Error : purchase number <b>{$pur['purnum']}</b> has already been invoiced.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($supRslt) < 1) {
        // code here
    } else {
        $sup = pg_fetch_array($supRslt);
    }
    # Get department info
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class=err> - Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $Ri = db_exec($sql);
    $refnum = getrefnum();
    while ($id = pg_fetch_array($Ri)) {
        db_connect();
        # get selamt from selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$id['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        if ($id['svat'] == 0) {
            $exvat = "y";
        } else {
            $exvat = "";
        }
        $vr = pvatcalc($id['amt'], $pur['vatinc'], $exvat);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Purchase {$pur['purnum']} Supplier : {$pur['supname']}.", $iamount, $ivat);
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    # Record the payment on the statement
    db_connect();
    $sdate = date("Y-m-d");
    $DAte = date("Y-m-d");
    db_connect();
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$pur['total']}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$pur['supid']}','{$pur['pdate']}', '{$dept['credacc']}', '{$pur['total']}', 'Stock Received - Purchase {$pur['purnum']}', '{$refnum}','{$pur['purnum']}','" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Debit Stock Control and Credit Creditors control
    writetrans($wh['conacc'], $dept['credacc'], $td, $refnum, $pur['total'] - $pur['vat'], "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Transfer vat
    writetrans($vatacc, $dept['credacc'], $td, $refnum, $pur['vat'], "Vat Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Ledger Records
    suppledger($pur['supid'], $wh['conacc'], $td, $pur['purid'], "Purchase No. {$pur['purnum']} received.", $pur['total'], 'c');
    db_connect();
    /* End Transactions */
    /* Make transaction record  for age analysis */
    db_connect();
    # update the supplier age analysis (make balance less)
    if (ext_ex2("suppurch", "purid", $pur['purnum'], "supid", $pur['supid'])) {
        # Found? Make amount less
        $sql = "UPDATE suppurch SET balance = (balance + '{$pur['total']}') WHERE supid = '{$pur['supid']}' AND purid = '{$pur['purnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    } else {
        /* Make transaction record for age analysis */
        $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, div) VALUES('{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$pur['total']}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
    }
    /* Make transaction record  for age analysis */
    # commit updating
    //1 ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    /* Start moving if purchase */
    if ($pur['received'] == "y") {
        if (strlen($pur['appdate']) < 8) {
            $pur['appdate'] = date("Y-m-d");
        }
        # copy purchase
        db_conn(PRD_DB);
        $sql = "INSERT INTO purchases(purid, deptid, supid, supname, supaddr, supno, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, shipping, remarks, refno, received, done, div, purnum, supinv,ordernum,appname,appdate)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}','{$supinv}','{$pur['ordernum']}','{$pur['appname']}','{$pur['appdate']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
        /*-- Cost varience -- */
        $nsubtot = sprint($pur['total'] - $pur['vat']);
        if ($pur['rsubtot'] > $nsubtot) {
            $diff = sprint($pur['rsubtot'] - $nsubtot);
            # Debit Stock Control and Credit Creditors control
            writetrans($wh['conacc'], $cvacc, $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        } elseif ($nsubtot > $pur['rsubtot']) {
            $diff = sprint($nsubtot - $pur['rsubtot']);
            # Debit Stock Control and Credit Creditors control
            writetrans($cvacc, $wh['conacc'], $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        }
        /*-- End Cost varience -- */
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert purchase items
            db_conn(PRD_DB);
            $sql = "INSERT INTO pur_items(purid, whid, stkid, qty, rqty, unitcost, amt, svat, ddate, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        # begin updating
        db_connect();
        # Remove the purchase from running DB
        $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Record where purchase is
        $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
        $movRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Remove those purchase items from running DB
        $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        /* End moving purchase received */
        # commit updating
    } else {
        # insert Order to DB
        $sql = "UPDATE purchases SET invcd = 'y',supinv='{$supinv}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Layout
    $write = "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>Purchase Invoiced</th></tr>\n\t\t<tr class='bg-even'><td>Purchase Invoice from Supplier <b>{$pur['supname']}</b> has been recorded.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class='bg-odd'><td><a href='purchase-view.php'>View purchases</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function writeLoan($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    $v->isOk($loanid, "num", 1, 20, "Invalid loan ID.");
    $v->isOk($loanamt, "float", 1, 10, "Invalid loan amount.");
    $v->isOk($loanint, "float", 1, 5, "Invalid loan interest.");
    $v->isOk($loanperiod, "num", 1, 3, "Invalid payback period.");
    $v->isOk($loaninstall, "float", 1, 10, "Invalid monthly installment.");
    $v->isOk($fringebenefit, "float", 1, 10, "Invalid fringe benefit amount.");
    $v->isOk($accid, "num", 1, 9, "Invalid bank account selected.");
    $v->isOk($account, "num", 1, 9, "Invalid contra account selected.");
    $v->isOk($loan_account, "num", 1, 9, "Invalid loan account selected.");
    $v->isOk($loan_type, "num", 1, 9, "Invalid loan type selected.");
    $ldate = mkdate($lyear, $lmonth, $lday);
    $v->isOk($ldate, "date", 1, 1, "Invalid loan date.");
    $archdate = mkdate($arch_year, $arch_month, $arch_day);
    $v->isOk($archdate, "date", 1, 1, "Invalid approval/denial date.");
    if (!checkdate($lmonth, $lday, $lyear)) {
        $v->addError("", "Invalid date.");
    }
    if ($account > 0 && isb($account) || isb($loan_account)) {
        $v->addError("", "Main accounts blocked. Please select sub accounts.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return enterLoan($confirmCust);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($ldate) >= strtotime($blocked_date_from) and strtotime($ldate) <= 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>";
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($archdate) >= strtotime($blocked_date_from) and strtotime($archdate) <= 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 employee details
    db_connect();
    $sql = "SELECT * FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "'";
    $empRslt = db_exec($sql) or errDie("Unable to select employees from database.");
    if (pg_numrows($empRslt) < 1) {
        return "Invalid employee ID.";
    }
    $myEmp = pg_fetch_array($empRslt);
    if (!isset($deny)) {
        # check for previous loan
        $sql = "SELECT empnum FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "' AND gotloan='t'::bool";
        $chkRslt = db_exec($sql) or errDie("Unable to check existing loans for employee.");
        if (pg_numrows($chkRslt) > 0) {
            return "<li class='err'>Loan already exists for employee number: {$empnum}.</li>";
        }
    }
    $date = date("Y-m-d");
    pglib_transaction("BEGIN");
    $totamount = sprint($loanperiod * $loaninstall);
    $loanint_amt = $totamount - $loanamt;
    $sql = "\n\t\tINSERT INTO emp_loanarchive (\n\t\t\tempnum, loanamt, loaninstall, loanint, loanperiod, loandate, archdate, loan_type, \n\t\t\tdiv, status\n\t\t) VALUES (\n\t\t\t'{$empnum}', '{$totamount}', '{$loaninstall}', '{$loanint}', '{$loanperiod}', '{$ldate}', '{$archdate}', '{$loan_type}', \n\t\t\t'" . USER_DIV . "', '" . (isset($deny) ? "D" : "A") . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to pre archive loan.");
    $loanaid = pglib_lastid('emp_loanarchive', 'id');
    $rem_sql = "DELETE FROM loan_requests WHERE id = '{$loanid}'";
    $run_rem = db_exec($rem_sql) or errDie("Unable to get loan requests information.");
    if (!isset($deny)) {
        $refnum = getrefnum();
        if ($accid > 0) {
            $bankacc = getbankaccid($accid);
        }
        if ($account > 0) {
            $bankacc = $account;
        }
        writetrans($loan_account, $bankacc, $archdate, $refnum, $loanamt, "Loan granted to employee {$myEmp['fnames']} {$myEmp['sname']}.");
        if ($accid > 0) {
            banktrans($accid, "withdrawal", $archdate, "{$myEmp['fnames']} {$myEmp['sname']}", "Loan granted to employee {$myEmp['fnames']} {$myEmp['sname']}.", 0, $loanamt, $loan_account);
        }
        # write to db
        $sql = "\n\t\t\tUPDATE cubit.employees \n\t\t\tSET loanamt = '{$totamount}', loanint = '{$loanint}', loanint_amt = '{$loanint_amt}', loanint_unpaid = '{$loanint_amt}', \n\t\t\t\tloanperiod = '{$loanperiod}', loaninstall = '{$loaninstall}', gotloan = 't'::bool, loanpayslip = '{$loanamt}', \n\t\t\t\tloanfringe = '{$fringebenefit}', loandate = '{$archdate}', expacc_loan = '{$loan_account}', \n\t\t\t\tloanamt_tot = '{$totamount}', loanid = '{$loanaid}' \n\t\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
        $loanRslt = db_exec($sql) or errDie("Unable to add loan to system.", SELF);
        if (pg_cmdtuples($loanRslt) < 1) {
            return "Unable to add loan to system.";
        }
    }
    pglib_transaction("COMMIT");
    $OUT = "<table " . TMPL_tblDflts . ">";
    if (isset($deny)) {
        $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<th>Loan Denied And Request Archived.</th>\n\t\t\t</tr>";
    } else {
        $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<th>Loan Granted And Added To System</th>\n\t\t\t</tr>";
    }
    $OUT .= "\n\t\t<tr class='datacell'>\n\t\t\t<td>Loan information successfully updated.</td>\n\t\t</tr>\n\t\t" . TBL_BR;
    if (!isset($deny)) {
        $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<td><input type='button' onclick=\"document.location='../reporting/loan_approval.php?id={$loanaid}'\" value='Generate Approval Report'></td>\n\t\t\t</tr>";
    }
    $OUT .= "\n\t\t</table><br>" . mkQuickLinks(ql("loan_apply.php", "Add Loan Application"), ql("loan_apply_view.php", "View Loan Applications"), ql("../admin-employee-add.php", "Add Employee"), ql("../admin-employee-view.php", "View Employees"));
    return $OUT;
}
function write($frm)
{
    extract($_REQUEST);
    if ($frm->validate("write")) {
        return confirm($frm);
    }
    pglib_transaction("BEGIN");
    db_conn('cubit');
    $user = USER_NAME;
    $Sql = "SELECT * FROM assets WHERE (dep_month='yes' AND remaction IS NULL)";
    $Rslt = db_exec($Sql) or errDie("Unable to access database.");
    $cc = "";
    $todate = mkdate($date_year, $date_month, $date_day);
    $ttime = mktimefd($todate);
    $refnum = getrefnum($todate);
    while ($led = pg_fetch_array($Rslt)) {
        if (empty($led["autodepr_date"])) {
            $led["autodepr_date"] = $led["date"];
        }
        explodeDate($led["autodepr_date"], $date_year, $date_month, $date_day);
        $ftime = mktime(0, 0, 0, $date_month, $date_day, $date_year);
        $depmonths = 0;
        while ($ftime < $ttime) {
            ++$depmonths;
            $ftime = mktime(0, 0, 0, $date_month + $depmonths, $date_day, $date_year);
        }
        if ($depmonths == 0) {
            continue;
        }
        $depperc = $led["dep_perc"];
        $ml_perc = $depperc * ($depmonths % 12 / 12);
        $years = ($depmonths - $depmonths % 12) / 12;
        $baseamt = $led["amount"] - $led["accdep"];
        $depamt = 0;
        /* yearly depreciations */
        for ($i = 1; $i <= $years; ++$i) {
            $depamt += ($baseamt - $depamt) * ($depperc / 100);
        }
        /* monthly depreciation */
        $depamt += ($baseamt - $depamt) * ($ml_perc / 100);
        $sql = "SELECT * FROM assetgrp WHERE grpid = '{$led['grpid']}' AND div = '" . USER_DIV . "'";
        $grpRslt = db_exec($sql);
        $grp = pg_fetch_array($grpRslt);
        writetrans($grp['depacc'], $grp['accdacc'], $todate, $refnum, $depamt, "{$led['des']} Depreciation");
        db_connect();
        $sql = "UPDATE assets SET accdep = (accdep + '{$depamt}'), autodepr_date='{$todate}'\r\n\t\t\t\tWHERE (id='{$led['id']}' AND div = '" . USER_DIV . "')";
        db_exec($sql) or errdie("Could not update assets table.");
        $snetval = $baseamt - $depamt;
        $sdate = date("Y-m-d");
        $sql = "INSERT INTO assetledger(assetid, asset, date, depamt, netval, div) \r\n\t\t\t\tVALUES ('{$led['id']}', '{$led['des']}', '{$todate}', '{$depamt}', '{$snetval}', '" . USER_DIV . "')";
        db_exec($sql) or errdie("Could not write to asset ledger.");
        $cc .= "CostCenter('ct', 'Asset Depreciation', '{$todate}', '{$led['des']} Depreciation', '{$depamt}', '');";
    }
    pglib_transaction("COMMIT");
    $write = "\r\n\t<script> \r\n\t{$cc}\r\n\t</script>\r\n\t<table " . TMPL_tblDflts . " width='50%'>\r\n\t\t<tr>\r\n\t\t\t<th>Auto Asset Depreciation</th>\r\n\t\t</tr>\r\n\t\t<tr class='datacell'>\r\n\t\t\t<td>Asset Depreciation has calculated and recorded.</td>\r\n\t\t</tr>\r\n\t</table>";
    return $write;
}
function write($_POST)
{
    //processes
    db_connect();
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($stkid, "num", 1, 50, "Invalid Stock ID.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($csamt, "float", 1, 20, "Invalid cost amount.");
    $v->isOk($buom, "num", 0, 20, "Invalid buying units.");
    $v->isOk($suom, "num", 0, 20, "Invalid selling units.");
    $v->isOk($bankacc, "num", 1, 50, "Invalid Bank Account.");
    # 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;
    }
    # Select Stock
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}'";
    $stkRslt = db_exec($sql) or errDie("Unable to access stock database.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    # Calculate total units bought
    $units = 0;
    if ($buom > 0) {
        $units += $buom * $stk['rate'];
    }
    if ($suom > 0) {
        $units += $suom;
    }
    $refnum = getrefnum($date);
    // Get Bank account [the traditional way re: hook of hook]
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankacc}'";
    $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);
    $bankaccid = $bank["accnum"];
    // Update stock
    db_connect();
    $sql = "UPDATE stock SET units = (units + '{$units}'), csamt = (csamt + '{$csamt}') WHERE stkid = '{$stkid}'";
    $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
    $sdate = explode("-", $date);
    $sdate = $sdate[2] . "-" . $sdate[1] . "-" . $sdate[0];
    // insert into stockk purchased
    $Sql = "INSERT INTO stock_purch(stkid, date, units, cost) VALUES('{$stkid}', '{$sdate}', '{$units}', '{$csamt}')";
    $Rslt = db_exec($Sql) or errDie("Unable to insert stock to Cubit.", SELF);
    # Write Trans(debit_account_id, credit_account_id, date, refnum, amount_[11111.00], details)
    writetrans($stk['accid'], $bankaccid, $date, $refnum, $csamt, "bought {$units} x {$stk['stkdes']}");
    $write = "\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\n\t\t\t<tr><th>Bought Stock Recorded</th></tr>\n\t\t\t<tr class=datacell><td>Bought Stock, {$stk['stkdes']} ({$stk['stkcod']}) has been successfully added to Cubit.</td></tr>\n\t\t</table>\n\t\t<p>\n\t\t<table border=0 cellpadding='2' cellspacing='1'>\n\t\t\t<tr><th>Quick Links</th></tr>\n\t\t\t<tr class='bg-odd'><td><a href='stock-add.php'>Add Stock</a></td></tr>\n\t\t\t<tr class='bg-even'><td><a href='stock-view.php'>View Stock</a></td></tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
function multican($accnt, $bank, $vatacc)
{
    $accids = explode("|", $accnt['accids']);
    $amounts = explode("|", $accnt['amounts']);
    $vats = explode("|", $accnt['vats']);
    $chrgvats = explode("|", $accnt['chrgvats']);
    $refnum = getrefnum();
    $descript = $accnt['descript'] . " Returned, Unpaid";
    $date = date("Y-m-d");
    foreach ($amounts as $key => $amount) {
        # SQL Array Rule: Thou shalt skip Zero Reference
        if ($key < 1) {
            continue;
        }
        $accid = $accids[$key];
        $vat = $vats[$key];
        $chrgvat = $chrgvats[$key];
        $amount -= $vat;
        if ($accnt['trantype'] == "deposit") {
            # DT(account involved), CT(bank)
            writetrans($accid, $bank['accnum'], $date, $refnum, $amount, $descript);
            if ($vat != 0) {
                # DT(Vat), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $date, $refnum, $vat, $descript);
            }
        } else {
            # DT(bank), CT(account invoilved)
            writetrans($bank['accnum'], $accid, $date, $refnum, $amount, $descript);
            if ($vat != 0) {
                # DT(Vat), CT(Bank)
                writetrans($bank['accnum'], $vatacc, $date, $refnum, $vat, $descript);
            }
        }
    }
    db_connect();
    # Delete cashbook ID
    $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['cashid']}' AND div = '" . USER_DIV . "'";
    $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
    if ($accnt['lcashid'] > 0) {
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
    }
}
function bank($_POST)
{
    //processes
    db_connect();
    # get var ( bank[] )
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($bank as $key => $value) {
        $v->isOk($refnum[$key], "num", 1, 10, "Invalid Reference number.");
        $v->isOk($day[$key], "num", 1, 2, "Invalid Date day.");
        $v->isOk($mon[$key], "num", 1, 2, "Invalid Date month.");
        $v->isOk($year[$key], "num", 1, 4, "Invalid Date Year.");
        $date[$key] = $day[$key] . "-" . $mon[$key] . "-" . $year[$key];
        if (!checkdate($mon[$key], $day[$key], $year[$key])) {
            $v->isOk($date[$key], "num", 1, 1, "Invalid date.");
        }
    }
    # 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;
    }
    # status for each deposit
    $status = "";
    # get deposits info
    foreach ($bank as $key => $cashid) {
        // Connect to database
        Db_Connect();
        $sql = "SELECT * FROM cashbook WHERE cashid = '{$cashid}'";
        $cashRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.", SELF);
        if (pg_numrows($cashRslt) < 1) {
            $OUTPUT = "<li clss=err>The cashbook record with reference number, <b>{$cashid}</b> was not found in Cubit.";
            return $OUTPUT;
        }
        $cash = pg_fetch_array($cashRslt);
        # get hook account number
        core_connect();
        $sql = "SELECT * FROM bankacc WHERE accid = '{$cash['bankid']}'";
        $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.";
        }
        $banklnk = pg_fetch_array($rslt);
        # date format
        $date[$key] = explode("-", $date[$key]);
        $date[$key] = $date[$key][2] . "-" . $date[$key][1] . "-" . $date[$key][0];
        # write the transaction
        if ($cash['trantype'] == "deposit") {
            # debit bank and credit the account involved
            writetrans($banklnk['accnum'], $cash['accinv'], $date[$key], $refnum[$key], $cash['amount'], $cash['descript']);
        } else {
            # credit bank and debit the account involved
            writetrans($cash['accinv'], $banklnk['accnum'], $date[$key], $refnum[$key], $cash['amount'], $cash['descript']);
        }
        # set records as banked
        db_connect();
        $sql = "UPDATE cashbook SET banked = 'yes' WHERE cashid='{$cashid}'";
        $Rslt = db_exec($sql) or errDie("Unable to set bank deposit as banked in Cubit.", SELF);
        //status
        $status .= "<tr class=datacell><td>Cash book entry <b>&nbsp;&nbsp;:&nbsp;&nbsp; {$cash['descript']}  - &nbsp;&nbsp;R {$cash['amount']}</b></td></tr>";
    }
    # status report
    $banked = "\r\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='100%'>\r\n        <tr><th>Cash deposit/transfer record Banked</th></tr>\r\n        {$status}\r\n        </table>";
    # main table (layout with menu)
    $OUTPUT = "<center>\r\n        <table width = 90%>\r\n        <tr valign=top><td width=60%>{$banked}</td>\r\n        <td align=center>\r\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=80%>\r\n        <tr><th>Quick Nevigation</th></tr>\r\n        <tr class=datacell><td align=center><a href='deposit-view.php'>Bank Another Deposit</td></tr>\r\n        <tr class=datacell><td align=center><a href='cheq-new.php'>Add Cheque Record</td></tr>\r\n        <tr class=datacell><td align=center><a href='cheq-view.php'>View Cheque Records</td></tr>\r\n        <tr class=datacell><td align=center><a href='deposit-new.php'>Add Deposit Records</td></tr>\r\n        <tr class=datacell><td align=center><a href='deposit-view.php'>View Deposit Records</td></tr>\r\n        </table>\r\n        </td></tr></table>";
    return $OUTPUT;
}
function package($_POST)
{
    $_POST = var_makesafe($_POST);
    extract($_POST);
    $week += 0;
    if (isset($back)) {
        return process($_POST);
    }
    $annual += 0;
    $bonus += 0;
    $paye_salary += 0;
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    $v->isOk($accid, "num", 1, 20, "Invalid bank number.");
    $v->isOk($MON, "num", 1, 2, "Invalid month.");
    $v->isOk($basic_sal, "float", 1, 20, "Invalid basic salary.");
    $v->isOk($overamt, "float", 1, 20, "Invalid overtime amount.");
    $v->isOk($income, "float", 1, 20, "Invalid income.");
    $v->isOk($commission, "float", 0, 20, "Invalid commision.");
    $v->isOk($loaninstall, "float", 0, 20, "Invalid loan installment.");
    $v->isOk($paidamount, "float", 1, 20, "Invalid paid amount.");
    if (isset($allowances)) {
        foreach ($allowances as $key => $value) {
            $v->isOk($allowances[$key], "float", 0, 20, "Invalid allowance amount " . ($key + 1) . ".");
        }
    }
    if (isset($deductid)) {
        foreach ($deductid as $key => $value) {
            $v->isOk($deductid[$key], "num", 1, 20, "Invalid deductions ID.");
        }
    }
    if (isset($deductions)) {
        foreach ($deductions as $key => $value) {
            $v->isOk($deductions[$key], "float", 0, 20, "Invalid deduction amount" . ($key + 1) . ".");
        }
    }
    if (isset($allowid)) {
        foreach ($allowid as $key => $value) {
            $v->isOk($allowid[$key], "num", 1, 20, "Invalid allowance ID.");
        }
    }
    if (isset($allowtax)) {
        foreach ($allowtax as $key => $value) {
            $v->isOk($allowtax[$key], "string", 2, 20, "Invalid allowance tax " . ($key + 1) . ".");
        }
    }
    $ydate = $year . "-" . $mon . "-" . $day;
    $ddate = $day . "-" . $mon . "-" . $year;
    if (!checkdate($mon, $day, $year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    $mon = $MON;
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    db_conn('cubit');
    $nettpay = $income;
    $sql = "SELECT * FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "'";
    $empRslt = db_exec($sql) or errDie("Unable to select employees from database.");
    if (pg_numrows($empRslt) < 1) {
        return "Invalid employee ID.";
    }
    $ecost = 0;
    $myEmp = pg_fetch_array($empRslt);
    // fringe benefits
    $i = 0;
    $fringes = "";
    $fringes_desc = "";
    if (isset($fringebens)) {
        foreach ($fringebens as $key => $value) {
            if ($fringebens[$key] > 0) {
                $fringes_desc .= "\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$fringename[$key]}</td>\r\n\t\t\t\t\t<td>" . CUR . " {$fringebens[$key]}</td>\r\n\t\t\t\t</tr>";
            }
        }
    }
    if (!empty($fringes_desc)) {
        $fringes_desc = "<tr><th colspan=2>Fringe Benefits</th></tr>{$fringes_desc}";
    }
    $all_before = "";
    $all_after = "";
    $all_beforeamount = 0;
    $all_afteramount = 0;
    if (isset($allowtax)) {
        foreach ($allowtax as $key => $perc) {
            if ($perc == "Yes" and $allowances[$key] > 0) {
                $all_before .= "<tr><td>{$allowname[$key]}</td><td align=right>" . CUR . " {$allowances[$key]}</td></tr>";
                $all_beforeamount = $all_beforeamount + $allowances[$key];
            } elseif ($allowances[$key] > 0) {
                $all_after .= "<tr><td>{$allowname[$key]}</td><td align=right>" . CUR . " {$allowances[$key]}</td></tr>";
                $all_afteramount = $all_afteramount + $allowances[$key];
            }
        }
    }
    $de_before = "\r\n\t\t<tr>\r\n\t\t\t<td colspan='2'>\r\n\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Details</th>\r\n\t\t\t\t\t\t<th>Employee Contribution</th>\r\n\t\t\t\t\t\t<!--<th>Employer Contribution</th>//-->\r\n\t\t\t\t\t</tr>";
    $de_after = "\r\n\t\t<tr>\r\n\t\t\t<td colspan='2'>\r\n\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Details</th>\r\n\t\t\t\t\t\t<th>Employee Contribution</th>\r\n\t\t\t\t\t\t<!--<th>Employer Contribution</th>//-->\r\n\t\t\t\t\t</tr>";
    $de_beforeamount = 0;
    $de_afteramount = 0;
    $de_beforeamount_emp = 0;
    $de_afteramount_emp = 0;
    if (isset($deducttax)) {
        foreach ($deducttax as $key => $perc) {
            if ($perc == "Yes" and $deductions[$key] > 0) {
                $de_before .= "\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td>{$deductname[$key]}</td>\r\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$deductions[$key]}</td>\r\n<!--\t\t\t\t\t<td align='right'>" . CUR . " {$employer_deductions[$key]}</td> //-->\r\n\t\t\t\t\t</tr>";
                $de_beforeamount = $de_beforeamount + $deductions[$key] + $employer_deductions[$key];
                $de_beforeamount_emp += $employer_deductions[$key];
            } elseif ($deductions[$key] > 0) {
                $de_after .= "\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td>{$deductname[$key]}</td>\r\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$deductions[$key]}</td>\r\n<!--\t\t\t\t\t<td align='right'>" . CUR . " {$employer_deductions[$key]}</td> //-->\r\n\t\t\t\t\t</tr>";
                $de_afteramount = $de_afteramount + $deductions[$key] + $employer_deductions[$key];
                $de_afteramount_emp += $employer_deductions[$key];
            }
        }
    }
    $de_before .= "</table></td></tr>";
    $de_after .= "</table></td></tr>";
    if ($all_beforeamount > 0) {
        $all_before = "<tr><td colspan='2'>Allowances</td></tr>" . $all_before;
    }
    if ($all_afteramount > 0) {
        $all_after = "<tr><td colspan='2'>Allowances</td></tr>" . $all_after;
    }
    if ($de_beforeamount > 0) {
        $de_before = "<tr><td colspan='2'>Deductions</td></tr>" . $de_before;
    }
    if ($de_afteramount > 0) {
        $de_after = "<tr><td colspan='2'>Deductions</td></tr>" . $de_after;
    }
    $gros_sal = sprint($grossal);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accid}' 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);
    $bankacc = $bank["accnum"];
    $basic_sal = sprint($basic_sal);
    $commission = sprint($commission);
    $overamt = sprint($overamt);
    $paye = sprint($paye);
    $nettpay = sprint($nettpay);
    $date = date("d-m-Y");
    $sdl = sprint($comp_sdl);
    $amount = sprint($gros_sal + $comp_pension + $comp_provident + $comp_medical + $comp_other + $comp_uif + $comp_ret + $sdl);
    $loaninstall = sprint($loaninstall);
    //Original CC
    //$cc = "<script> CostCenter('ct', 'Salaries', '$date', 'Salary Payment for employee,  $myEmp[fnames] $myEmp[sname]', '$amount', '../'); </script>";
    //New CC
    $cc = "CostCenter('ct', 'Salaries', '{$date}', 'Salary Payment for employee,  {$myEmp['fnames']} {$myEmp['sname']}', '{$amount}', '../'); ";
    $ecost = $amount;
    if ($commission > 0) {
        $comDis = "<tr><td>Commission</td><td align='right'>" . CUR . " {$commission}</td></tr>";
    } else {
        $comDis = "";
    }
    if ($overamt > 0) {
        $oveDis = "<tr><td>Overtime</td><td align='right'>" . CUR . " {$overamt}</td></tr>";
    } else {
        $oveDis = "";
    }
    if ($loaninstall > 0) {
        $loaDis = "<tr><td>Loan Instalment</td><td align='right'>" . CUR . " {$loaninstall}</td></tr>";
    } else {
        $loaDis = "";
    }
    if ($basic_sal != $gros_sal) {
        $groDis = "<tr><td>Gross Salary</td><td align='right'>" . CUR . " {$gros_sal}</td></tr>";
    } else {
        $groDis = "";
    }
    if ($all_travel > 0) {
        $talDis = "<tr><td>Travel Allowance</td><td align='right'>" . CUR . " {$all_travel}</td></tr>";
    } else {
        $talDis = "";
    }
    db_connect();
    $Sl = "SELECT * FROM salset";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        $con = true;
    } else {
        $con = false;
    }
    $intrec = gethook("accnum", "salacc", "name", "interestreceived");
    $uifbal = gethook("accnum", "salacc", "name", "uifbal");
    $sdlbal = gethook("accnum", "salacc", "name", "sdlbal");
    $pa = gethook("accnum", "salacc", "name", "pension");
    $ma = gethook("accnum", "salacc", "name", "medical");
    $cash_account = gethook("accnum", "salacc", "name", "cash");
    $retire = gethook("accnum", "salacc", "name", "retire");
    $provident = gethook("accnum", "salacc", "name", "provident");
    $salconacc = gethook("accnum", "salacc", "name", "salaries control");
    $commacc = gethook("accnum", "salacc", "name", "Commission");
    $payeacc = gethook("accnum", "salacc", "name", "PAYE");
    $uifacc = gethook("accnum", "salacc", "name", "UIF");
    $providente = $myEmp["expacc_provident"];
    $retiree = $myEmp["expacc_ret"];
    $pax = $myEmp["expacc_pension"];
    $uifexp = $myEmp["expacc_uif"];
    $max = $myEmp["expacc_medical"];
    $dedgenerale = $myEmp["expacc_other"];
    $sdlexp = $myEmp["expacc_sdl"];
    $salacc = $myEmp["expacc_salwages"];
    $loanexp = $myEmp["expacc_loan"];
    if ($con) {
        $uifexp = $salacc;
        $sdlexp = $salacc;
        $pax = $salacc;
        $max = $salacc;
        $retiree = $salacc;
    }
    // Get Bank account [the traditional way re: hook of hook]
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accid}' AND div = '" . USER_DIV . "'";
    $Rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($Rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $bank = pg_fetch_array($Rslt);
    # date(todays date)
    $date = $ddate;
    $refnum = getrefnum($date);
    # Debit uif acc and credit uif control acc
    if ($comp_uif > 0) {
        writetrans($uifexp, $uifbal, $date, $refnum, $comp_uif, "Company UIF Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_uif > 0) {
        db_conn("cubit");
        $Sl = "UPDATE employees SET balance=balance-({$emp_uif}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $uifacc, $ydate, $refnum, "UIF", $emp_uif, "d");
        writetrans($salconacc, $uifbal, $date, $refnum, $emp_uif, "Employee UIF Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    # Debit uif sdl and credit sdl control acc
    writetrans($sdlexp, $sdlbal, $date, $refnum, $sdl, "SDL,  {$myEmp['fnames']} {$myEmp['sname']}.");
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    db_conn('cubit');
    $Sl = "UPDATE employees SET balance=balance+({$grossal_nodedall}) WHERE empnum = '{$empnum}'";
    $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
    empledger($empnum, $salacc, $ydate, $refnum, "Gross Salary", $grossal_nodedall, "c");
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    # Debit salaries acc and credit salaries control acc
    writetrans($salacc, $salconacc, $date, $refnum, $grossal_nodedall, "Gross Salary proccessing for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    if ($commission > 0) {
        if ($con) {
            $commacc = $salacc;
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance+({$commission}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $commacc, $ydate, $refnum, "Commission", $commission, "c");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit commission acc and credit salaries control acc
        writetrans($commacc, $salconacc, $date, $refnum, $commission, "Commission for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($paye > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paye}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $payeacc, $ydate, $refnum, "PAYE", $paye, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit salaries control acc and credit PAYE control acc
        writetrans($salconacc, $payeacc, $date, $refnum, $paye, "PAYE for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    db_conn('cubit');
    // fringe benefits
    if (isset($fringeid)) {
        foreach ($fringeid as $i => $id) {
            //			empledger($empnum, $fringeaccs[$i], $ydate, $refnum,"Fringe Benefit, $fringename[$i]" , $fringebens[$i], "d");
            //			writetrans($salconacc, $fringeaccs[$i], $date, $refnum, $fringebens[$i], "Fringe Benefit for employee, $myEmp[fnames] $myEmp[sname].");
        }
    }
    if ($fringe_medical > 0) {
        //		empledger($empnum, $fringe_medexp, $ydate, $refnum,"Medical Fringe Benefit" , $fringe_medical, "d");
        //		writetrans($salconacc, $fringe_medexp, $date, $refnum, $fringe_medical, "Fringe Benefit for employee, $myEmp[fnames] $myEmp[sname].");
    }
    if ($fringe_car1 > 0) {
        //		empledger($empnum, $fringe_carexp, $ydate, $refnum,"Motor Vehicle 1 Fringe Benefit" , $fringe_car1, "d");
        //		writetrans($salconacc, $fringe_carexp, $date, $refnum, $fringe_car1, "Car Fringe Benefit for employee, $myEmp[fnames] $myEmp[sname].");
    }
    if ($fringe_car2 > 0) {
        //		empledger($empnum, $fringe_carexp, $ydate, $refnum,"Motor Vehicle 2 Fringe Benefit" , $fringe_car2, "d");
        //		writetrans($salconacc, $fringe_carexp, $date, $refnum, $fringe_car2, "Car Fringe Benefit for employee, $myEmp[fnames] $myEmp[sname].");
    }
    if ($fringe_loan > 0) {
        //		empledger($empnum, $fringe_loanexp, $ydate, $refnum,"Loan Interest Fringe Benefit" , $fringe_loan, "d");
        //		writetrans($salconacc, $fringe_loanexp, $date, $refnum, $fringe_loan, "Loan Interest Benefit for employee, $myEmp[fnames] $myEmp[sname].");
    }
    # Pay allowances accounts
    if (isset($allowid)) {
        foreach ($allowid as $i => $id) {
            # Debit allowances acc and credit salaries control acc
            if ($con) {
                $allowaccs[$i] = $salacc;
            }
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance+({$allowances[$i]}) WHERE empnum = '{$empnum}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($empnum, $allowaccs[$i], $ydate, $refnum, "Allowance", $allowances[$i], "c");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($allowaccs[$i], $salconacc, $date, $refnum, $allowances[$i], "Allowances for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
        }
    }
    # Pay Deductions accounts
    if (isset($deductid)) {
        foreach ($deductid as $i => $id) {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance-({$deductions[$i]}) WHERE empnum = '{$empnum}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($empnum, $dedaccs[$i], $ydate, $refnum, "Deduction", $deductions[$i], "d");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            # Debit salaries control acc and credit  acc
            // salcon acc - ded balance acc
            writetrans($salconacc, $dedaccs[$i], $date, $refnum, $deductions[$i], "Deductions for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
            db_conn("cubit");
            $sql = "SELECT * FROM salded WHERE id='{$id}'";
            $rslt = db_exec($sql) or errDie("Error reading deduction information.");
            $dedinfo = pg_fetch_array($rslt);
            /*
            			if ( $employer_deductions[$i] > 0 && $dedinfo["creditor"] != "In House" ) {
            				// ded exp acc - ded balance acc
            				writetrans($dedaccs[$i], $bal_dedaccs[$i], $date, $refnum, $employer_deductions[$i], "Company Contribution to Deductions for employee, $myEmp[fnames] $myEmp[sname].");
            			}*/
        }
    }
    if ($comp_pension > 0) {
        writetrans($pax, $pa, $date, $refnum, $comp_pension, "Company Pension Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_pension > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_pension}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $pa, $ydate, $refnum, "Pension Contribution", $emp_pension, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $pa, $date, $refnum, $emp_pension, "Pension Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($comp_medical > 0) {
        writetrans($max, $ma, $date, $refnum, $comp_medical, "Company Medical Aid Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_medical > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_medical}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $ma, $ydate, $refnum, "Medical Aid Contribution", $emp_medical, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $ma, $date, $refnum, $emp_medical, "Employee Medical Aid Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($comp_provident > 0) {
        writetrans($providente, $provident, $date, $refnum, $comp_provident, "Company Provident Fund Contribution, {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_provident > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_provident}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $provident, $ydate, $refnum, "Provident Fund Contribution", $emp_provident, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $provident, $date, $refnum, $emp_provident, "Provident Fund Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if (false && $comp_other > 0) {
        writetrans($dedgenerale, $dedgeneral, $date, $refnum, $comp_other, "Company Contribution to Other Deductions, {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if (false && $emp_other > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_other}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $dedgeneral, $ydate, $refnum, "Other Deductions Contribution", $emp_other, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $dedgeneral, $date, $refnum, $emp_other, "Other Deductions Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_ret > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_ret}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $retire, $ydate, $refnum, "Retirement Annuity Contribution", $emp_ret, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $retire, $date, $refnum, $emp_ret, "Employee Retirement Annuity Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($comp_ret > 0) {
        writetrans($retiree, $retire, $date, $refnum, $comp_ret, "Company Retirement Annuity Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    db_conn('cubit');
    $mons = "{$mon};";
    $due = sprint($nettpay - $paidamount);
    //, balance=balance+'$due
    $sql = "UPDATE employees SET lastpay = '{$mons}',\r\n\t\t\t\tloanamt = (loanamt - cast(float '{$loaninstall}' as numeric)),\r\n\t\t\t\tloanfringe = (loanfringe - cast(float '{$fringe_loan}' as numeric))\r\n\t\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to get employee details.");
    // check if loan is 0, then unmark loan as active, and store in archive
    $sql = "SELECT loanid FROM employees WHERE loanamt=0 AND empnum='{$empnum}' AND gotloan='t'::bool";
    $rslt = db_exec($sql) or errDie("Error reading employee details for loan.");
    if (pg_num_rows($rslt) > 0) {
        $loanid = pg_fetch_result($rslt, 0, 0);
        $sql = "UPDATE employees SET gotloan='f'::bool, loaninstall='0'\r\n\t\t\t\tWHERE empnum='{$empnum}'";
        $rslt = db_exec($sql) or errDie("Unable to update employee loan status.");
        $sql = "UPDATE emp_loanarchive SET donedata=CURRENT_DATE WHERE id='{$loanid}'";
        $rslt = db_exec($sql) or errDie("Unable to archive loan.");
        $sql = "SELECT loanint_unpaid FROM employees WHERE empnum='{$empnum}'";
        $rslt = db_exec($sql) or errDie("Error reading loan interest for installment.");
        $loanint = sprint(pg_fetch_result($rslt, 0, 0));
    } else {
        if ($loaninstall > 0) {
            $sql = "SELECT loanamt_tot, loanint_amt FROM employees WHERE empnum='{$empnum}'";
            $rslt = db_exec($sql) or errDie("Error reading loan interest for installment.");
            $loan_tot = pg_fetch_result($rslt, 0, 0);
            $loan_totint = pg_fetch_result($rslt, 0, 1);
            $loanint = sprint($loaninstall / $loan_tot * $loan_totint);
        } else {
            $loanint = 0;
        }
    }
    $sql = "UPDATE employees SET loanint_unpaid = (loanint_unpaid - cast(float '{$loanint}' as numeric))\r\n\t\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update employee interest.");
    if ($loaninstall > 0 && !empty($loanexp)) {
        $loaninstall += 0;
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$loaninstall}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $loanexp, $ydate, $refnum, "Loan Instalment", $loaninstall, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit salaries control acc and credit loan control acc
        writetrans($salconacc, $loanexp, $date, $refnum, $loaninstall - $loanint, "Loan Installment for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
        writetrans($salconacc, $intrec, $date, $refnum, $loanint, "Loan Interest for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    $loaninstall = $loaninstall + 0;
    $totded = $de_beforeamount + $de_afteramount + $emp_pension + $emp_medical + $emp_provident + $emp_ret + $emp_other;
    $totded_employer = $de_beforeamount_emp + $de_afteramount_emp + $comp_pension + $comp_medical + $comp_provident + $comp_ret + $comp_other;
    $totall = $all_beforeamount + $all_afteramount;
    $parkage = "\r\n\t\t<br><br>\r\n\t\t<center>\r\n\t\t{$cc}\r\n\t\t<table border='2' cellpadding='4' cellspacing='0' width='750' bordercolor='#000000'>\r\n\t        <tr>\r\n\t        \t<td align='center'><b>Description</b></td>\r\n\t        \t<td width='100' align='center'><b>Amount</b></td>\r\n\t        </tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>Basic salary</td>\r\n\t\t\t\t<td align='right'>" . CUR . " {$basic_sal}</td>\r\n\t\t\t</tr>\r\n\t\t\t{$comDis}\r\n\t\t\t{$fringes_desc}\r\n\t\t\t{$all_before}\r\n\t\t\t{$de_before}\r\n\t\t\t{$groDis}\r\n\t\t\t{$talDis}\r\n\t\t\t<tr><td>UIF</td><td align='right'>" . CUR . " {$emp_uif}</td></tr>\r\n\t\t\t<tr><td>PAYE</td><td align='right'>" . CUR . " {$paye}</td></tr>\r\n\t\t\t{$loaDis}\r\n\t\t\t{$all_after}\r\n\t\t\t{$de_after}\r\n\t\t\t<tr><td><b>Nett Pay</b></td><td align='right'><b>" . CUR . " {$nettpay}</b></td></tr>\r\n\t\t\t</form>\r\n\t\t</table>\r\n\t\t</center>";
    $parkagesave = "\r\n\t\t<br><br>\r\n\t\t<center>\r\n\t\t<table border='2' width='750' border=2 cellpadding='4' cellspacing='0' bordercolor='#000000'>\r\n\t\t\t<tr>\r\n\t\t\t\t<td align='center'><b>Description</b></td>\r\n\t\t\t\t<td width='100' align='center'><b>Amount</b></td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>Basic salary</td>\r\n\t\t\t\t<td align='right'>" . CUR . " {$basic_sal}</td>\r\n\t\t\t</tr>\r\n\t\t\t{$comDis}\r\n\t\t\t{$fringes_desc}\r\n\t\t\t{$all_before}\r\n\t\t\t{$de_before}\r\n\t\t\t{$groDis}\r\n\t\t\t{$talDis}\r\n\t\t\t<tr><td>UIF</td><td align='right'>" . CUR . " {$emp_uif}</td></tr>\r\n\t\t\t<tr><td>PAYE</td><td align='right'>" . CUR . " {$paye}</td></tr>\r\n\t\t\t{$loaDis}\r\n\t\t\t{$all_after}\r\n\t\t\t{$de_after}\r\n\t\t\t<tr><td><b>Nett Pay</b></td><td align='right'><b>" . CUR . " {$nettpay}</b></td></tr>\r\n\t\t</form>\r\n\t\t</table>\r\n\t\t</center>";
    $OUTPUT = $parkage;
    $save = base64_encode($parkagesave);
    $Date = $ydate;
    $np = $nettpay;
    if (isset($rbsa)) {
        $np = sprint($np - array_sum($rbsa));
    }
    db_conn("cubit");
    $Sl = "\r\n       \t\tINSERT INTO salpaid (\r\n       \t\t\tempnum, month, bankid, salary, comm, uifperc, uif, payeperc, paye, totded, \r\n       \t\t\ttotded_employer, totallow, loanins, div, display, saldate, week\r\n       \t\t) VALUES (\r\n       \t\t\t'{$empnum}', '{$mon}', '{$accid}', '{$np}', '{$commission}', '0', '{$emp_uif}', '0', '{$paye}', '{$totded}', \r\n       \t\t\t'{$totded_employer}', '{$totall}', '{$loaninstall}', '" . USER_DIV . "','{$save}','{$Date}','{$week}'\r\n       \t\t)";
    $Ry = db_exec($Sl) or errDie("Unable to insert record.");
    $id = pglib_lastid("salpaid", "id");
    $year = $year;
    $payslip_id = $id;
    db_conn('cubit');
    $Sl = "SELECT * FROM rbs ORDER BY name";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    $i = 0;
    if (pg_num_rows($Ri) > 0) {
        while ($td = pg_fetch_array($Ri)) {
            if (!isset($rbsa[$td['id']]) || $rbsa[$td['id']] < 1) {
                continue;
            }
            db_conn('cubit');
            $rbsa[$td['id']] = sprint($rbsa[$td['id']]);
            //$rt.="<tr class='".bg_class()."'>
            //<td><input type=hidden name='rbs[$td[id]]' value='$td[id]'>$td[name]</td>
            //<td>".CUR." <input type=hidden name='rbsa[$td[id]]' value='".$rbsa[$td['id']]."'>".$rbsa[$td['id']]."</td></tr>";
            $rb = $rbsa[$td['id']];
            $i++;
            $Sl = "\r\n\t\t\t\tINSERT INTO emp_inc (\r\n\t\t\t\t\temp, year, period, date, payslip, type, code, description, qty, rate, amount, ex\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$empnum}','{$year}','{$mon}', '{$Date}', '{$payslip_id}', '{$td['id']}', '', '{$td['name']}', '1', '0', '{$rb}', 'RBS'\r\n\t\t\t\t)";
            $Ri = db_exec($Sl) or errDie("unable to insert data.");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance+({$rb}) WHERE empnum = '{$empnum}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($empnum, $td['account'], $ydate, $refnum, "Reimbursement", $rb, "c");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($td['account'], $salconacc, $date, $refnum, $rb, "Reimbursement for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
        }
    }
    if ($myEmp['paytype'] == "Cash") {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paidamount}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $cash_account, $ydate, $refnum, "Payment(Cash)", $paidamount, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit salaries control acc and credit Bank acc
        writetrans($salconacc, $cash_account, $date, $refnum, $paidamount, "Salary Payment(Cash) for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    } elseif ($myEmp['paytype'] == "Ledger Account") {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paidamount}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $account, $ydate, $refnum, "Payment(Ledger Account)", $paidamount, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit salaries control acc and credit Bank acc
        writetrans($salconacc, $account, $date, $refnum, $paidamount, "Salary Payment(Ledger Account) for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    } else {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paidamount}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $bankacc, $ydate, $refnum, "Payment(Bank)", $paidamount, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit salaries control acc and credit Bank acc
        writetrans($salconacc, $bankacc, $date, $refnum, $paidamount, "Salary Payment for employee(Bank),  {$myEmp['fnames']} {$myEmp['sname']}.");
        # issue bank record
        banktrans($accid, "withdrawal", $date, "{$myEmp['fnames']} {$myEmp['sname']}", "Salary Payment for employee,  {$myEmp['fnames']} {$myEmp['sname']}", 0, $paidamount, $salconacc, $myEmp['empnum']);
    }
    db_conn('cubit');
    /*
    	writetrans($uifexp,$uifbal , $date, $refnum, $uif, "Company UIF Contribution,  $myEmp[fnames] $myEmp[sname].");
    */
    # Debit uif sdl and credit sdl control acc
    //	writetrans($sdlexp,$sdlbal , $date, $refnum, $sdl, "SDL,  $myEmp[fnames] $myEmp[sname].");
    db_conn("cubit");
    if ($comp_uif > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','UIFC','','UIF','1','0','{$comp_uif}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data1.");
    }
    if ($emp_uif > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','UIFE','','UIF','1','0','{$emp_uif}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data3.");
    }
    if ($sdl > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','SDL','','SDL','1','0','{$sdl}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data2.");
    }
    if ($paye > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','PAYE','','PAYE','1','0','{$paye}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data3.");
    }
    if ($basic_sal > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INC','','Basic Salary','','1','0','{$basic_sal}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data4.");
    }
    if ($fringe_tot > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INC','','Fringe Benefits Total','','1','0','{$fringe_tot}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data4.");
    }
    if ($myEmp["loanpayslip"] > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','LOAN','','Employee Loan','','1','0','{$myEmp['loanpayslip']}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert loan data for employee income on payslip.");
        $sql = "UPDATE employees SET loanpayslip='0' WHERE empnum='{$empnum}'";
        $rslt = db_exec($sql) or errDie("Error updating loan information for payslip.");
    }
    if ($bonus > 0 && $myEmp["payprd"] != "f" && $myEmp["payprd"] != "w") {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INCB','','Bonus','','1','0','{$bonus}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data5.");
    } else {
        if ($bonus > 0) {
            $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INCB','','Special Bonus/Additional Salary','','1','0','{$bonus}','')";
            $Ri = db_exec($Sl) or errDie("unable to insert data5.");
        }
    }
    if ($annual > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INCAB','','Annual Bonus','','1','0','{$annual}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data5.");
    }
    if ($commission > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INCC','','Commission','','1','0','{$commission}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data6.");
    }
    if ($all_travel > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INCT','','Travel Allowance','','1','0','{$all_travel}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data7.");
    }
    if ($loaninstall > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDL','','Loan Repayment','1','0','{$loaninstall}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data8.");
    }
    if ($comp_pension > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','COMP','','Pension','1','0','{$comp_pension}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_pension > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDP','','Pension','1','0','{$emp_pension}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($comp_ret > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','COMR','','Retirement Annuity Fund','1','0','{$comp_ret}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_ret > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDR','','Retirement Annuity Fund','1','0','{$emp_ret}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($myEmp["fringe_car1_contrib"] > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDR','','Motorcar 1 Contribution for Use','1','0','{$myEmp['fringe_car1_contrib']}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($myEmp["fringe_car2_contrib"] > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDR','','Motorcar 2 Contribution for Use','1','0','{$myEmp['fringe_car2_contrib']}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($comp_medical > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','COMM','','Medical Aid','1','0','{$comp_medical}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data.11");
    }
    if ($emp_medical > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDM','','Medical Aid','1','0','{$emp_medical}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data.12");
    }
    if ($comp_provident > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','COMV','','Provident','1','0','{$comp_provident}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_provident > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDV','','Provident','1','0','{$emp_provident}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($comp_other > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','COMO','','Other Deductions','1','0','{$comp_other}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_other > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDO','','Other Deductions','1','0','{$emp_other}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($overamt > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INCO','','Over Time','1','0','{$overamt}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data.13");
    }
    $payslip_id = $id;
    if (isset($allowid)) {
        $Sl = "SELECT id,allowance FROM allowances";
        $Ri = db_exec($Sl) or errDie("Unable to get allowances.");
        while ($data = pg_fetch_array($Ri)) {
            $allname[$data['id']] = $data['allowance'];
        }
        foreach ($allowid as $i => $id) {
            $aname = $allname[$allowid[$i]];
            if (($allowances[$i] = sprint($allowances[$i])) <= 0) {
                continue;
            }
            $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,qty,rate,amount,ex)\r\n\t\t\t\tVALUES ('{$empnum}','{$year}','{$mon}','{$Date}','{$payslip_id}','{$allowid[$i]}','','{$aname}','1','0','{$allowances[$i]}','')";
            $Ri = db_exec($Sl) or errDie("unable to insert data.");
        }
    }
    # Pay Deductions accounts
    if (isset($deductid)) {
        $Sl = "SELECT id,deduction FROM salded";
        $Ri = db_exec($Sl) or errDie("Unabel to get get dat.");
        while ($data = pg_fetch_array($Ri)) {
            $dnames[$data['id']] = $data['deduction'];
        }
        foreach ($deductid as $i => $id) {
            $dname = $dnames[$deductid[$i]];
            # Debit salaries control acc and credit  acc
            if (($deductions[$i] = sprint($deductions[$i])) > 0) {
                $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t\t\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$payslip_id}','{$deductid[$i]}','','{$dname}','1','0','{$deductions[$i]}')";
                $Ri = db_exec($Sl) or errDie("unable to insert data.");
            }
            if (($employer_deductions[$i] = sprint($employer_deductions[$i])) > 0) {
                $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t\t\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$payslip_id}','{$deductid[$i]}','','{$dname}','1','0','{$employer_deductions[$i]}')";
                //$Ri=db_exec($Sl) or errDie("unable to insert data1.");
            }
        }
    }
    $id = $payslip_id;
    $ecost += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM empc WHERE emp='{$empnum}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        while ($data = pg_fetch_array($Ri)) {
            db_conn('cubit');
            $sql = "SELECT * FROM costcenters WHERE ccid = '{$data['cid']}'";
            $ccRslt = db_exec($sql) or errDie("Unable to retrieve Cost centers from database.");
            $cc = pg_fetch_array($ccRslt);
            $amount = sprint($ecost * $data['amount'] / 100);
            db_conn(PRD_DB);
            $sql = "INSERT INTO cctran(ccid, trantype, typename, edate, description, amount, username, div)\r\n\t\t\tVALUES('{$cc['ccid']}', 'ct', 'Salary', '{$Date}', 'Salary for employee,  {$myEmp['fnames']} {$myEmp['sname']}', '{$amount}', '" . USER_NAME . "', '" . USER_DIV . "')";
            $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
        }
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $OUTPUT = "<script>printer('payslip-print.php?id={$id}');move('../main.php');</script>";
    require "../template.php";
}
function cash_receipt()
{
    extract($_REQUEST);
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$invid}'";
    $inv_rslt = db_exec($sql) or errDie("Unable to retrieve note.");
    $inv = pg_fetch_array($inv_rslt);
    // Retrieve customer account
    $sql = "SELECT accid FROM core.accounts WHERE topacc='6400' AND accnum='000'";
    $acc_rslt = db_exec($sql) or errDie("Unable to retrieve account.");
    $cust_acc = pg_fetch_result($acc_rslt, 0);
    // Retrieve cash on hand
    $sql = "SELECT accid FROM core.accounts WHERE topacc='7200' AND accnum='000'";
    $acc_rslt = db_exec($sql) or errDie("Unable to retrieve account.");
    $coh_acc = pg_fetch_result($acc_rslt, 0);
    $sql = "SELECT * FROM cubit.customers WHERE cusnum='{$inv['cusnum']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
    $cust_data = pg_fetch_array($cust_rslt);
    // Retrieve company details
    $sql = "SELECT * FROM cubit.compinfo WHERE compname='" . COMP_NAME . "'";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company details.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Start transactions -----------------------------------------------------
    pglib_transaction("BEGIN");
    $sql = "INSERT INTO hire.cash (invid, cash)\r\n\t\t\tVALUES ('{$invid}', '{$inv['deposit_amt']}')";
    db_exec($sql) or errDie("Unable to add cash to hire.");
    $refnum = getrefnum();
    writetrans($coh_acc, $cust_acc, $inv["odate"], $refnum, $inv["deposit_amt"], "Cash Receipt for " . CUR . "{$inv['deposit_amt']} from {$cust_data['cusname']} " . "{$cust_data['surname']} for Deposit on Hire Note H" . getHirenum($inv["invid"], 1));
    // Make ledger record
    custledger($inv["cusnum"], $cust_acc, $inv["odate"], $inv["invid"], "Cash Receipt for " . CUR . "{$inv['deposit_amt']} from {$cust_data['cusname']} " . "{$cust_data['surname']} for Deposit on Hire Note H" . getHirenum($inv["invid"], 1), $inv["deposit_amt"], "c");
    custCT($inv["deposit_amt"], $inv["cusnum"], $inv["odate"]);
    // Turn the amount around to a negative
    $stmnt_amt = $inv["deposit_amt"] - $inv["deposit_amt"] * 2;
    // Record the payment on the statement
    $sql = "INSERT INTO cubit.stmnt(cusnum, invid, docref, amount, date, type,\r\n\t\t\t\tdiv)\r\n\t\t\tVALUES('{$inv['cusnum']}', '{$inv['invid']}', '{$inv['invnum']}',\r\n\t\t\t\t'{$stmnt_amt}', '{$inv['odate']}',\r\n\t\t\t\t'Cash Receipt for " . CUR . "{$inv['deposit_amt']} from {$cust_data['cusname']} " . "{$cust_data['surname']} for Deposit on Hire Note H" . getHirenum($inv["invid"], 1) . "',\r\n\t\t\t\t'" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record");
    // Record the payment on the statement
    $sql = "INSERT INTO cubit.open_stmnt(cusnum, invid, docref, amount, balance,\r\n\t\t\t\tdate, type, div)\r\n\t\t\tVALUES ('{$inv['cusnum']}', '{$inv['invid']}', '{$inv['invnum']}',\r\n\t\t\t\t'{$stmnt_amt}', '{$stmnt_amt}', '{$inv['odate']}',\r\n\t\t\t\t'Cash Receipt for " . CUR . "{$inv['deposit_amt']} from {$cust_data['cusname']} " . "{$cust_data['surname']} for Deposit on Hire Note H" . getHirenum($inv["invid"], 1) . "',\r\n\t\t\t\t'" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record.");
    $sql = "UPDATE cubit.customers SET balance=balance-'{$inv['deposit_amt']}'\r\n\t\t\tWHERE cusnum='{$inv['cusnum']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    pglib_transaction("COMMIT");
    // End transactions -------------------------------------------------------
    $OUTPUT = "<table " . TMPL_tblDflts . " style='border: 1px solid #000'>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>\r\n\t\t\t\t<b>CASH RECEIPT</b>\r\n\t\t\t</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'><b>{$comp_data['compname']}</b></td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>{$comp_data['addr1']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>{$comp_data['addr2']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>{$comp_data['addr3']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>{$comp_data['addr4']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td align='center'>Tel: {$comp_data['tel']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td style='border-top: 1px solid #000'>Hire No: H" . getHirenum($inv["invid"], 1) . "</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td>Order No.{$inv['ordno']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td>Hire Date. {$inv['odate']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td style='border-top: 1px solid #000'\r\n\t\t\t\t>Cash Amount Received<br /> From {$cust_data['cusname']} {$cust_data['surname']}: " . CUR . "{$inv['deposit_amt']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td>&nbsp;</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td>By: {$inv['username']}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td><br /><br /></td>\r\n\t\t</tr>\r\n\t</table>";
    require "../tmpl-print.php";
}
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($out, "float", 1, 10, "Invalid out amount.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 10, "Invalid amount.");
    $v->isOk($rate, "float", 1, 10, "Invalid exchange rate.");
    $v->isOk($supid, "num", 1, 10, "Invalid supplier number.");
    $v->isOk($out1, "float", 0, 10, "Invalid paid amount(current).");
    $v->isOk($out2, "float", 0, 10, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 10, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 10, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 10, "Invalid paid amount(120).");
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No.");
            $v->isOk($paidamt[$key], "float", 1, 20, "Invalid amount to be paid.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $bank = pg_fetch_array($rslt);
    db_connect();
    # Supplier name
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql);
    $sup = pg_fetch_array($supRslt);
    db_conn("exten");
    # get debtors control account
    $sql = "SELECT credacc FROM departments WHERE deptid ='{$sup['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    $dept = pg_fetch_array($deptRslt);
    # Update xrate
    xrate_update($sup['fcid'], $rate, "suppurch", "id");
    sup_xrate_update($sup['fcid'], $rate);
    bank_xrate_update($sup['fcid'], $rate);
    $lamt = sprint($amt * $rate);
    # date format
    $sdate = explode("-", $date);
    $sdate = $sdate[2] . "-" . $sdate[1] . "-" . $sdate[0];
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    # Paid invoices
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    db_connect();
    if ($all == 0) {
        $ids = "";
        $purids = "";
        $fpamounts = "";
        $pamounts = "";
        $pdates = "";
        # Begin updates
        # pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                #debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY fbalance LIMIT 1";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class='err'>Invalid Invoice Number.</li>";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - '{$paidamt[$key]}'::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $fpamounts .= "|{$paidamt[$key]}";
                $pamounts .= "|{$lpaidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        if ($out > 0) {
            recordDT($out, $sup['supid']);
        }
        $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
        suppledger($sup['supid'], $bank['accnum'], $sdate, $cheqnum, "Payment for purchases", $lamt, "d");
        db_connect();
        # Update the supplier (make fbalance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Record the payment record
        // $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        //2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, fpamounts, pdates, fcid, currency, location, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$fpamounts}', '{$pdates}', '{$sup['fcid']}', '{$sup['currency']}', '{$sup['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($accdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $lamt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        # Commit updates
        # pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    if ($all == 1) {
        $ids = "";
        $purids = "";
        $fpamounts = "";
        $pamounts = "";
        $pdates = "";
        # Begin updates
        //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY fbalance LIMIT 1";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class='err'>Invalid Invoice Number.</li>";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - {$paidamt[$key]}::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $fpamounts .= "|{$paidamt[$key]}";
                $pamounts .= "|{$lpaidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        if ($out1 > 0) {
            recordDT($out1, $sup['supid']);
        }
        if ($out2 > 0) {
            recordDT($out2, $sup['supid']);
        }
        if ($out3 > 0) {
            recordDT($out3, $sup['supid']);
        }
        if ($out4 > 0) {
            recordDT($out4, $sup['supid']);
        }
        if ($out5 > 0) {
            recordDT($out5, $sup['supid']);
        }
        $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the supplier (make fbalance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Record the payment record
        // $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        //2 $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, pdates, div) VALUES ('$bankid', 'withdrawal', '$sdate', '$sup[supno] - $sup[supname]', 'Supplier Payment to $sup[supname]', '$cheqnum', '$lamt', '$amt', 'no', '$dept[credacc]', '$sup[supid]', '$ids', '$purids', '$pamounts', '$pdates', '".USER_DIV."')";
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, fpamounts, pdates, fcid, currency, location, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$fpamounts}', '{$pdates}', '{$sup['fcid']}', '{$sup['currency']}', '{$sup['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($accdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $lamt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        # Commit updates
        //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
        suppledger($sup['supid'], $bank['accnum'], $sdate, $cheqnum, "Payment to Supplier", $lamt, "d");
        db_connect();
    }
    if ($all == 2) {
        $ids = "";
        $purids = "";
        $fpamounts = "";
        $pamounts = "";
        $pdates = "";
        # Begin updates
        #pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $lpaidamt[$key] = sprint($paidamt[$key] * $rate);
                # Get debt invoice info
                $sql = "SELECT id,pdate FROM suppurch WHERE purid ='{$invids[$key]}' AND div = '" . USER_DIV . "' ORDER BY fbalance LIMIT 1";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class=err>Invalid Invoice Number.";
                }
                $pur = pg_fetch_array($invRslt);
                # reduce the money that has been paid
                $sql = "UPDATE suppurch SET balance = (balance - '{$lpaidamt[$key]}'::numeric(13,2)), fbalance = (fbalance - '{$paidamt[$key]}'::numeric(13,2)) WHERE purid = '{$invids[$key]}' AND div = '" . USER_DIV . "' AND id='{$pur['id']}'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $samount = $paidamt[$key] - $paidamt[$key] * 2;
                $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc,div) VALUES('{$sup['supid']}','{$samount}','{$sdate}', 'Payment - Purchase: {$invids[$key]}','{$cheqnum}','{$bank['accnum']}', '" . USER_DIV . "')";
                $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
                suppledger($sup['supid'], $bank['accnum'], $sdate, $invids[$key], "Payment for Purchase No. {$invids[$key]}", $paidamt[$key], "d");
                db_connect();
                # record the payment on the statement
                $ids .= "|{$pur['id']}";
                $purids .= "|{$invids[$key]}";
                $fpamounts .= "|{$paidamt[$key]}";
                $pamounts .= "|{$lpaidamt[$key]}";
                $pdates .= "|{$pur['pdate']}";
            }
        }
        $samount = $amt - $amt * 2;
        # Update the supplier (make fbalance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Record the payment record
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, famount, banked, accinv, supid, ids, purids, pamounts, fpamounts, pdates, fcid, currency, location, div) VALUES ('{$bankid}', 'withdrawal', '{$sdate}', '{$sup['supno']} - {$sup['supname']}', 'Supplier Payment to {$sup['supname']}', '{$cheqnum}', '{$lamt}', '{$amt}', 'no', '{$dept['credacc']}', '{$sup['supid']}', '{$ids}', '{$purids}', '{$pamounts}', '{$fpamounts}', '{$pdates}', '{$sup['fcid']}', '{$sup['currency']}', '{$sup['location']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Update the bankacct table (make fbalance less) [used for cashbook fc value]
        $sql = "UPDATE bankacct SET balance = (balance - '{$lamt}'::numeric(13,2)), fbalance = (fbalance - '{$amt}'::numeric(13,2)) WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $refnum = getrefnum($accdate);
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
        if (pg_numrows($Rx) < 1) {
            return "Invalid bank acc.";
        }
        $link = pg_fetch_array($Rx);
        writetrans($dept['credacc'], $link['accnum'], $accdate, $refnum, $lamt, "Supplier Payment to {$sup['supname']}");
        db_conn('cubit');
        # Commit updates
        #pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    }
    db_conn('cubit');
    $Sl = "DELETE FROM suppurch WHERE fbalance = 0::numeric(13,2) AND balance = 0::numeric(13,2)";
    $Rx = db_exec($Sl);
    # status report
    $write = "\n\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t<tr>\n\t\t\t<th>International Bank Payment</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>International Bank Payment added to cash book.</td>\n\t\t</tr>\n\t</table>";
    # main table (layout with menu)
    $OUTPUT = "<center>\n\t<table width='90%'>\n\t\t<tr valign='top'>\n\t\t\t<td width='50%'>{$write}</td>\n\t\t\t<td align='center'>\n\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='bank-pay-supp.php'>Add supplier payment</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='bank-pay-add.php'>Add Bank Payment</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='cashbook-view.php'>View Cash Book</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t</tr>\n\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($ctaccid, "num", 1, 50, "Invalid Account to be Credited.");
    $v->isOk($dtaccid, "num", 1, 50, "Invalid Account to be Debited.");
    $v->isOk($prd, "num", 1, 10, "Invalid Period.");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    $v->isOk($amount, "float", 1, 20, "Invalid Amount.");
    $v->isOk($details, "string", 0, 255, "Invalid Details.");
    $v->isOk($author, "string", 1, 30, "Invalid Authorising person name.");
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class=err>" . $e["msg"];
        }
        $write .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    // Accounts details
    $dtaccRs = get("core", "*", "accounts", "accid", $dtaccid);
    $dtacc = pg_fetch_array($dtaccRs);
    $ctaccRs = get("core", "*", "accounts", "accid", $ctaccid);
    $ctacc = pg_fetch_array($ctaccRs);
    db_conn(YR_DB);
    $sql = "SELECT * FROM info WHERE prddb ='{$prd}'";
    $prdRslt = db_exec($sql);
    $prds = pg_fetch_array($prdRslt);
    # write transaction
    writetrans($dtaccid, $ctaccid, $date, $prd, $refnum, $amount, $details);
    // Start layout
    $write = "\n        <center>\n        <h3>Journal transaction has been recorded</h3>\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=500>\n\t\t<tr><td width=50%><h3>Year</h3></td><td width=50%><h3>Period</h3></td></tr>\n\t\t<tr class='bg-even'><td>" . YR_NAME . "</td><td>{$prds['prdname']}</td></tr>\n\t\t<tr><td><br></td></tr>\n\t\t<tr><td width=50%><h3>Debit</h3></td><td width=50%><h3>Credit</h3></td></tr>\n        <tr class='bg-odd'><td>{$dtacc['topacc']}/{$dtacc['accnum']} - {$dtacc['accname']}</td><td>{$ctacc['topacc']}/{$ctacc['accnum']} - {$ctacc['accname']}</td></tr>\n        <tr><td><br></td></tr>\n        <tr colspan=2><td><h4>Amount</h4></td></tr>\n        <tr class='bg-even'><td colspan=2><b>" . CUR . " {$amount}</b></td></tr>\n        </table>\n        <br>\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=25%>\n        <tr><th>Quick Links</th></tr>\n        <tr class=datacell><td align=center><a href='trans-new.php'>Journal Transactions</td></tr>\n        <script>document.write(getQuicklinkSpecial());</script>\n        </table>";
    return $write;
}
function write($_POST)
{
    # processes
    db_connect();
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 10, "Invalid Date Entry.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amount, "float", 1, 10, "Invalid amount.");
    $v->isOk($cusid, "num", 1, 20, "Invalid customer account.");
    # 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;
    }
    # date format
    $date = explode("-", $date);
    $date = $date[2] . "-" . $date[1] . "-" . $date[0];
    $cheqnum = 0 + $cheqnum;
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # Check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $bank = pg_fetch_array($rslt);
    # get account name
    $supRslt = get("cubit", "*", "customers", "cusnum", $cusid);
    $cus = pg_fetch_array($supRslt);
    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);
    db_connect();
    $Sl = "\n\t\tINSERT INTO stmnt \n\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\tVALUES \n\t\t\t('{$cusid}','0','{$amount}', '{$date}','{$descript}','" . USER_DIV . "', '{$date}')";
    $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
    $Sl = "INSERT INTO open_stmnt (cusnum, invid, amount, date, type, div,balance) VALUES ('{$cusid}','0','{$amount}', '{$date}','{$descript}','" . USER_DIV . "','{$amount}')";
    $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
    $sql = "UPDATE customers SET balance = (balance + '{$amount}') WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    custledger($cusid, $bank['accnum'], $date, '0', "Payment to Customer", $amount, "d");
    custDT($amount, $cus['cusnum']);
    # record the payment record
    db_connect();
    $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, suprec, div) VALUES ('{$bankid}', 'withdrawal', '{$date}', '{$cus['cusname']} {$cus['surname']}', '{$descript}', '{$cheqnum}', '{$amount}', 'no', '{$dept['debtacc']}', '{$cusid}', '" . USER_DIV . "')";
    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    $refnum = getrefnum();
    writetrans($dept['debtacc'], $bank['accnum'], $date, $refnum, $amount, $descript);
    # status report
    $write = "\n\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Bank Payment</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>Bank Payment to customer : {$cus['surname']} added to cash book.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t";
    # main table (layout with menu)
    $OUTPUT = "\n\t\t\t\t<center>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr valign='top'>\n\t\t\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td><a href='bank-pay-add.php'>Add Bank Payment</a></td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td><a href='cashbook-view.php'>View Cash Book</a></td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t";
    return $OUTPUT;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (isset($back)) {
        return slctacc($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $date = $date_year . "-" . $date_month . "-" . $date_day;
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    foreach ($accid as $key => $value) {
        $dtamount[$key] += 0;
        $ctamount[$key] += 0;
        if ($dtamount[$key] > 0 || $ctamount[$key] > 0) {
            $v->isOk($accid[$key], "num", 1, 50, "Invalid Account to be Debited.[{$key}]");
            $v->isOk($dtamount[$key], "float", 1, 20, "Invalid Debit Amount.[{$key}]");
            $v->isOk($ctamount[$key], "float", 1, 20, "Invalid Credit Amount.[{$key}]");
            $v->isOk($descript[$key], "string", 0, 255, "Invalid Details.[{$key}]");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    foreach ($accid as $key => $value) {
        # begin sql transaction
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        if ($dtamount[$key] > 0) {
            writetrans($accid[$key], $account, $date, $refnum, $dtamount[$key], $descript[$key]);
        } elseif ($ctamount[$key] > 0) {
            writetrans($account, $accid[$key], $date, $refnum, $ctamount[$key], $descript[$key]);
        }
        pglib_transaction("COMMIT") or errDie("Unable to finish a database transaction.", SELF);
    }
    // Start layout
    $write = "\n\t\t<center>\n\t\t<h3>Journal transactions have been recorded.</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Account</th>\n\t\t\t\t<th>Description</th>\n\t\t\t\t<th>Debit</th>\n\t\t\t\t<th>Credit</th>\n\t\t\t</tr>";
    foreach ($accid as $key => $value) {
        if ($dtamount[$key] > 0 || $ctamount[$key] > 0) {
            core_connect();
            $accRss = get("core", "*", "accounts", "accid", $accid[$key]);
            if (pg_numrows($accRss) < 1) {
                return "<li> Accounts to be debited does not exist.</li>";
            }
            $acc_each[$key] = pg_fetch_array($accRss);
            $write .= "\n\t\t\t\t<tr bgcolor=" . bgcolorg() . ">\n\t\t\t\t\t<td valign='center'>" . $acc_each[$key]['accname'] . "</td>\n\t\t\t\t\t<td>{$descript[$key]}</td>\n\t\t\t\t\t<td nowrap>" . CUR . " " . sprint($dtamount[$key]) . "</td>\n\t\t\t\t\t<td nowrap>" . CUR . " " . sprint($ctamount[$key]) . "</td>\n\t\t\t\t</tr>";
        }
    }
    $write .= "\n\t\t</table>\n\t\t<br>\n\t\t<table " . TMPL_tblDflts . " width='25%'>\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td align='center'><a href='../reporting/index-reports.php'>Financials</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td align='center'><a href='trans-new.php'>Journal Transaction</td>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td align='center'><a href='batch-view.php'>View batch file</td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
function write($_POST)
{
    # Set max execution time to 12 hours
    ini_set("max_execution_time", 43200);
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($invids as $key => $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid recuring invoice number.");
    }
    $VATP = TAX_VAT;
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return $err;
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $i = 0;
    foreach ($invids as $key => $invid) {
        db_connect();
        $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "' and done='n'";
        $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
        if (pg_numrows($invRslt) < 1) {
            return "<i class=err>Not Found</i>";
        }
        $inv = pg_fetch_array($invRslt);
        $ctyp = $inv['ctyp'];
        //$td=$inv['sdate'];
        $td = $inv['odate'];
        //$cus['surname']=$inv['cusname'];
        if ($ctyp == 's') {
            $cusnum = $inv['tval'];
            $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to view customer");
            $cus = pg_fetch_array($custRslt);
            $na = $cus['surname'];
        } elseif ($ctyp == 'c') {
            $deptid = $inv['tval'];
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
            $deptRslt = db_exec($sql) or errDie("Unable to view customers");
            $dept = pg_fetch_array($deptRslt);
            $na = $inv['cusname'];
        }
        db_connect();
        $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql) or errDie("Unable to get data.");
        unset($totstkamt);
        $refnum = getrefnum();
        /*refnum*/
        /* - Start Hooks - */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "NO VAT");
        $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
        /* - End Hooks - */
        db_conn("cubit");
        $real_invid = divlastid('inv', USER_DIV);
        db_conn("cubit");
        # Put in product
        $totstkamt = array();
        while ($stk = pg_fetch_array($stkdRslt)) {
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatex']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            if ($vd['zero'] == "Yes") {
                $stk['vatex'] = "y";
            }
            $t = $inv['chrgvat'];
            $stkacc = $stk['accid'];
            if (isset($totstkamt[$stkacc])) {
                if ($stk['vatex'] == "y") {
                    $totstkamt[$stkacc] += vats($stk['amt'], 'novat', $vd['vat_amount']);
                    $va = 0;
                    $inv['chrgvat'] = "";
                } else {
                    $totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                    $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                    if ($inv['chrgvat'] == "no") {
                        $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                    }
                }
            } else {
                if ($stk['vatex'] == "y") {
                    $totstkamt[$stkacc] = vats($stk['amt'], 'novat', $vd['vat_amount']);
                    $inv['chrgvat'] = "";
                    $va = 0;
                } else {
                    $totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                    $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                    if ($inv['chrgvat'] == "no") {
                        $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                    }
                }
            }
            vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock Sales, invoice No.{$real_invid}", vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']) + $va, $va);
            //print vats($stk['amt'],$inv['chrgvat'], $vd['vat_amount']);
            $inv['chrgvat'] = $t;
            //$sql = "UPDATE nons_inv_items SET accid = '$stk[account]' WHERE id = '$stk[id]'";
            //$sRslt = db_exec($sql);
        }
        /* --- Start Some calculations --- */
        # Subtotal
        $SUBTOT = sprint($inv['subtot']);
        $VAT = sprint($inv['vat']);
        $TOTAL = sprint($inv['total']);
        /* --- End Some calculations --- */
        /* - Start Hooks - */
        //$vatacc = gethook("accnum", "salesacc", "name", "VAT");
        /* - End Hooks - */
        # todays date
        $date = date("d-m-Y");
        $sdate = date("Y-m-d");
        db_conn("cubit");
        if (isset($bankid)) {
            $bankid += 0;
            db_conn("cubit");
            $sql = "SELECT * FROM bankacct WHERE bankid = '{$inv['accid']}'";
            $deptRslt = db_exec($sql) or errDie("Unable to view customers");
            if (pg_numrows($deptRslt) < 1) {
                $error = "<li class=err> Bank not Found.";
                $confirm .= "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
                return $confirm;
            } else {
                $deptd = pg_fetch_array($deptRslt);
            }
            db_conn('core');
            $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
            $rd = db_exec($Sl) or errDie("Unable to get data.");
            $data = pg_fetch_array($rd);
            $BA = $data['accnum'];
        }
        $tot_post = 0;
        # bank  % cust
        if ($ctyp == 's') {
            # Get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                $dept['deptname'] = "<li class=err>Department not Found.";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $tpp = 0;
            //$sql = "SELECT * FROM nons_inv_items  WHERE invid = '$invid' AND div = '".USER_DIV."'";
            //$stkdRslt = db_exec($sql);
            // 			# Put in product
            // 			while($stk = pg_fetch_array($stkdRslt)){
            // 				$wamt=$stk['amt'];
            //
            // 				$tot_post+=$wamt;
            // 				writetrans($dept['debtacc'], $stk['account'], $td, $refnum, $wamt, "Non-Stock Sales on invoice No.$real_invid customer $cus[surname].");
            // 			}
            # record transaction  from data
            foreach ($totstkamt as $stkacc => $wamt) {
                # Debit Customer and Credit stock
                $tot_post += $wamt;
                writetrans($dept['debtacc'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            # Debit bank and credit the account involved
            if ($VAT != 0) {
                $tot_post += $VAT;
                writetrans($dept['debtacc'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            $sdate = date("Y-m-d");
        } else {
            if (!isset($accountc)) {
                $accountc = 0;
            }
            if (!isset($dept['pca'])) {
                $accountc += 0;
                $dept['pca'] = $accountc;
                $dept['debtacc'] = $accountc;
            }
            if (isset($bankid)) {
                $dept['pca'] = $BA;
            }
            if ($ctyp == "ac") {
                $dept['pca'] = $inv['tval'];
            }
            $tpp = 0;
            # record transaction  from data
            foreach ($totstkamt as $stkacc => $wamt) {
                if (!isset($cust['surname'])) {
                    $cust['surname'] = $inv['cusname'];
                    $cust['addr1'] = $inv['cusaddr'];
                }
                # Debit Customer and Credit stock
                $tot_post += $wamt;
                writetrans($dept['pca'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            if (isset($bankid)) {
                db_connect();
                $bankid += 0;
                $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div) VALUES ('{$bankid}', 'deposit', '{$td}', '{$inv['cusname']}', 'Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}', '0', '{$TOTAL}', '{$VAT}', '{$inv['chrgvat']}', 'no', '{$stkacc}', '" . USER_DIV . "')";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                $sql = "UPDATE nons_invoices SET jobid='{$bankid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            }
            # Debit bank and credit the account involved
            if ($VAT != 0) {
                $tot_post += $VAT;
                writetrans($dept['pca'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            $sdate = date("Y-m-d");
        }
        $tot_post = sprint($tot_post);
        db_connect();
        if ($ctyp == 's') {
            $sql = "UPDATE nons_invoices SET balance = total, cusid = '{$cusnum}', ctyp = '{$ctyp}', cusaddr = '{$cus['addr1']}', cusvatno = '{$cus['vatnum']}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
            $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            # Record the payment on the statement
            $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}','{$inv['odate']}', 'Non-Stock Invoice', '" . USER_DIV . "', '{$inv['odate']}')";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            # Record the payment on the statement
            $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}', '{$TOTAL}','{$inv['sdate']}', 'Non-Stock Invoice', '" . USER_DIV . "')";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            # Update the customer (make balance more)
            $sql = "UPDATE customers SET balance = (balance + '{$TOTAL}'::numeric(13,2)) WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            # Make ledge record
            custledger($cusnum, $stkacc, $td, $real_invid, "Non Stock Invoice No. {$real_invid}", $TOTAL, "d");
            custDT($TOTAL, $cusnum, $td, $invid, "nons");
            //print $tot_post;exit;
            $tot_dif = sprint($tot_post - $TOTAL);
            if ($tot_dif > 0) {
                writetrans($varacc, $dept['debtacc'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            } elseif ($tot_dif < 0) {
                $tot_dif = $tot_dif * -1;
                writetrans($dept['debtacc'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            }
        } else {
            $date = date("Y-m-d");
            $sql = "UPDATE nons_invoices SET balance=total, accid = '{$dept['pca']}', ctyp = '{$ctyp}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
            $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            $tot_dif = sprint($tot_post - $TOTAL);
            if ($tot_dif > 0) {
                writetrans($varacc, $dept['pca'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            } elseif ($tot_dif < 0) {
                $tot_dif = $tot_dif * -1;
                writetrans($dept['pca'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            }
            if ($ctyp == "c") {
                $cusnum = "0";
            } elseif ($ctyp == "ac") {
                $cusnum = "0";
                $na = "";
            }
        }
        db_connect();
        $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\tVALUES('{$inv['sdate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$VAT}', '{$TOTAL}', 'non', '" . USER_DIV . "')";
        $recRslt = db_exec($sql);
        db_conn('cubit');
        $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t\t('{$cusnum}','{$na}','Non-stock Invoice {$real_invid}','{$inv['sdate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
        $Ri = db_exec($Sl);
        $ecost = sprint($TOTAL - $VAT);
        db_conn('cubit');
        $inv['jobid'] += 0;
        $Sl = "SELECT * FROM ninvc WHERE inv='{$inv['jobid']}'";
        $Ri = db_exec($Sl);
        if (CC_USE == "use") {
            if (pg_num_rows($Ri) > 0) {
                while ($data = pg_fetch_array($Ri)) {
                    db_conn('cubit');
                    $sql = "SELECT * FROM costcenters WHERE ccid = '{$data['cid']}'";
                    $ccRslt = db_exec($sql) or errDie("Unable to retrieve Cost centers from database.");
                    $cc = pg_fetch_array($ccRslt);
                    $amount = sprint($ecost * $data['amount'] / 100);
                    db_conn(PRD_DB);
                    $sql = "INSERT INTO cctran(ccid, trantype, typename, edate, description, amount, username, div)\n\t\t\t\t\tVALUES('{$cc['ccid']}', 'dt', 'Invoice', '{$inv['sdate']}', 'Invoice No.{$real_invid}', '{$amount}', '" . USER_NAME . "', '" . USER_DIV . "')";
                    $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
                }
            }
        }
        $i++;
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Retrieve template settings
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices' AND div='" . USER_DIV . "'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        pdf($_POST);
    } else {
        templatePdf($_POST);
    }
    // Final Laytout
    $write = "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>{$i} Invoices Proccesed</th></tr>\n\t\t<tr class='bg-even'><td>Invoices have been successfully printed.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t<tr><th>Quick Links</th></tr>\n\t<tr class='bg-odd'><td><a href='invoice-view.php'>View Invoices</a></td></tr>\n\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 50, "Invalid Customer number.");
    $v->isOk($accid, "num", 1, 50, "Invalid Contra Account.");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    $v->isOk($amount, "float", 1, 20, "Invalid Amount.");
    $v->isOk($details, "string", 0, 255, "Invalid Details.");
    $v->isOk($author, "string", 1, 30, "Invalid Authorising person name.");
    $datea = explode("-", $date);
    if (count($datea) == 3) {
        if (!checkdate($datea[1], $datea[2], $datea[0])) {
            $v->isOk($date, "num", 1, 1, "Invalid date.");
        }
    } else {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    # Accounts details
    $accRs = get("core", "*", "accounts", "accid", $accid);
    $acc = pg_fetch_array($accRs);
    # Select customer
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($custRslt) < 1) {
        return "<li> Invalid Customer ID.</li>";
    } else {
        $cust = pg_fetch_array($custRslt);
    }
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        return "<i class='err'>Department Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    $famt = sprint($amount);
    $amount = sprint($amount * $rate);
    cus_xrate_update($cust['fcid'], $rate);
    xrate_update($cust['fcid'], $rate, "invoices", "invid");
    xrate_update($cust['fcid'], $rate, "custran", "id");
    # Probe tran type
    if ($entry == "CT") {
        # Write transaction  (debit contra account, credit debtors control)
        writetrans($accid, $dept['debtacc'], $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
        $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t\t<td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t</tr>";
        $samount = sprint($amount - $amount * 2);
        $sfamt = sprint($famt - $famt * 2);
        // recordCT($samount, $cust['cusnum']);
        frecordCT($famt, $amount, $cust['cusnum'], $cust['fcid'], $date);
        $type = 'c';
    } else {
        # Write transaction  (debit debtors control, credit contra account)
        writetrans($dept['debtacc'], $accid, $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
        $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t</tr>";
        $samount = $amount;
        $sfamt = $famt;
        // recordDT($samount, $cust['cusnum']);
        frecordDT($famt, $amount, $cust['cusnum'], $cust['fcid'], $date);
        $type = 'd';
    }
    db_connect();
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $sdate = date("Y-m-d");
    # record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt \n\t\t\t\t(cusnum, invid, amount, date, type, st, div, allocation_date) \n\t\t\tVALUES \n\t\t\t\t('{$cust['cusnum']}', '0', '{$sfamt}', '{$date}', '{$details}', 'n', '" . USER_DIV . "', '{$date}')";
    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
    # update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$samount}'), fbalance = (fbalance + '{$sfamt}') WHERE cusnum = '{$cust['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Make ledge record
    custledger($cust['cusnum'], $accid, $date, $refnum, $details, $amount, $type);
    // Start layout
    $write = "\n\t\t\t<h3>Journal transaction has been recorded</h3>\n\t\t\t<table " . TMPL_tblDflts . " width='500'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='50%'><h3>Debit</h3></td>\n\t\t\t\t\t<td width='50%'><h3>Credit</h3></td>\n\t\t\t\t</tr>\n\t\t\t\t{$tran}\n\t\t\t\t" . TBL_BR . "\n\t\t\t\t<tr colspan='2'>\n\t\t\t\t\t<td><h4>Amount</h4></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'><b>" . CUR . " {$famt}</b></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<P>\n\t\t\t<table " . TMPL_tblDflts . " width='25%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td align='center'><a href='trans-new.php'>Journal Transactions</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td align='center'><a href='../customers-view.php'>View Customers</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
    return $write;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($bank as $key => $value) {
        $v->isOk($batchid[$key], "num", 1, 10, "Invalid Batch ID.[{$key}]");
        $v->isOk($ctaccid[$key], "num", 1, 50, "Invalid Account to be Credited.[{$key}]");
        $v->isOk($dtaccid[$key], "num", 1, 50, "Invalid Account to be Debited.[{$key}]");
        $v->isOk($refnum[$key], "num", 1, 10, "Invalid Reference number.[{$key}]");
        $v->isOk($amount[$key], "float", 1, 20, "Invalid Amount.[{$key}]");
        $v->isOk($descript[$key], "string", 0, 255, "Invalid Details.[{$key}]");
        $datea = explode("-", $date[$key]);
        if (count($datea) == 3) {
            if (!checkdate($datea[1], $datea[2], $datea[0])) {
                $v->isOk($date[$key], "num", 1, 1, "Invalid date.");
            }
        } else {
            $v->isOk($date[$key], "num", 1, 1, "Invalid date.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    foreach ($bank as $key => $value) {
        // Accounts details
        $dtaccRs = get("core", "accname, topacc, accnum", "accounts", "accid", $dtaccid[$key]);
        $dtacc[$key] = pg_fetch_array($dtaccRs);
        $ctaccRs = get("core", "accname, topacc, accnum", "accounts", "accid", $ctaccid[$key]);
        $ctacc[$key] = pg_fetch_array($ctaccRs);
    }
    // Start layout
    $write = "\n\t\t\t\t<center>\n\t\t\t\t<h3>Journal transactions have been recorded</h3>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t<th>Ref num</th>\n\t\t\t\t\t\t<th>Debit</th>\n\t\t\t\t\t\t<th>Credit</th>\n\t\t\t\t\t\t<th>Amount</th>\n\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t<th>VAT Amount</th>\n\t\t\t\t\t\t<th>Total Transaction Amount</th>\n\t\t\t\t\t</tr>";
    $cc = "";
    foreach ($bank as $key => $value) {
        $write .= "\n\t\t\t\t\t\t<tr bgcolor=" . bgcolorg() . ">\n\t\t\t\t\t\t\t<td>{$date[$key]}</td>\n\t\t\t\t\t\t\t<td>{$refnum[$key]}</td>\n\t\t\t\t\t\t\t<td valign='center'>" . $dtacc[$key]['topacc'] . "/" . $dtacc[$key]['accnum'] . " " . $dtacc[$key]['accname'] . "</td>\n\t\t\t\t\t\t\t<td valign='center'>" . $ctacc[$key]['topacc'] . "/" . $ctacc[$key]['accnum'] . " " . $ctacc[$key]['accname'] . "</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$amount[$key]}</td>\n\t\t\t\t\t\t\t<td>{$descript[$key]}</td>";
        if (isset($chrgvat[$value])) {
            $datea = explode("-", $date[$key]);
            $cdate = "{$datea['2']}-{$datea['1']}-{$datea['0']}";
            $vataccRs = get("core", "*", "accounts", "accid", $vataccid[$value]);
            $vatacc = pg_fetch_array($vataccRs);
            $vataccRs = get("core", "*", "accounts", "accid", $vatdedacc[$value]);
            $vdedacc = pg_fetch_array($vataccRs);
            //$VATP = TAX_VAT;
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$key]}'";
            $Ri = db_exec($Sl);
            $vd = pg_fetch_array($Ri);
            $VATP = $vd['vat_amount'];
            # if vat must be charged
            if ($vatinc[$value] == "no") {
                $vatamt[$value] = sprint($VATP / 100 * $amount[$key]);
                $amt[$key] = sprint($amount[$key]);
                $totamt = sprint($amount[$key] + $vatamt[$value]);
            } else {
                $vatamt[$value] = sprint($amount[$key] / ($VATP + 100) * $VATP);
                $amt[$key] = sprint($amount[$key] - $vatamt[$value]);
                $totamt = sprint($amount[$key]);
            }
            # Check VAt Deductable account
            if ($vatdedacc[$value] == $dtaccid[$key]) {
                db_connect();
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$key]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return "Please select the vatcode";
                }
                $vd = pg_fetch_array($Ri);
                vatr($vd['id'], $date[$key], "INPUT", $vd['code'], $refnum[$key], "{$descript[$key]} VAT", -$totamt, -$vatamt[$value]);
                writetrans($vataccid[$value], $ctaccid[$key], $date[$key], $refnum[$key], $vatamt[$value], $descript[$key] . "  VAT");
                writetrans($dtaccid[$key], $ctaccid[$key], $date[$key], $refnum[$key], $amt[$key], $descript[$key]);
            } elseif ($vatdedacc[$value] == $ctaccid[$key]) {
                db_connect();
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$key]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return "Please select the vatcode";
                }
                $vd = pg_fetch_array($Ri);
                vatr($vd['id'], $date[$key], "OUTPUT", $vd['code'], $refnum[$key], "{$descript[$key]} VAT", $totamt, $vatamt[$value]);
                writetrans($dtaccid[$key], $vataccid[$value], $date[$key], $refnum[$key], $vatamt[$value], $descript[$key] . "  VAT");
                writetrans($dtaccid[$key], $ctaccid[$key], $date[$key], $refnum[$key], $amt[$key], $descript[$key]);
            }
            $write .= "\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$vatamt[$value]}</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$totamt}</td>";
        } else {
            $totamt[$key] = sprint($amount[$key]);
            # Write normal transaction
            writetrans($dtaccid[$key], $ctaccid[$key], $date[$key], $refnum[$key], $totamt[$key], $descript[$key]);
            $write .= "<td>0</td><td>" . CUR . " {$totamt[$key]}</td>";
        }
        $write .= "</tr>";
        db_connect();
        $sql = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '" . USER_DIV . "' LIMIT 1";
        $banks = db_exec($sql);
        if (pg_numrows($banks) < 1) {
            return "<li class='err'> There are no accounts held at the selected Bank.\n\t\t\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
        }
        $barr = pg_fetch_array($banks);
        $bankid = $barr['bankid'];
        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.";
        }
        $banklnk = pg_fetch_array($rslt);
        $cc_trantype = cc_TranTypeAcc($dtaccid[$key], $ctaccid[$key]);
        if ($cc_trantype != false) {
            $cc .= "\n\t\t\t\t\t<script>\n\t\t\t\t\t\tCostCenter('{$cc_trantype}', 'Batch Journal', '{$date[$key]}', '{$descript[$key]}', '{$amount[$key]}', '../');\n\t\t\t\t\t</script>";
        } else {
            $cc .= "";
        }
        db_conn('core');
        #process complete ... remove entry
        $rem_sql = "DELETE FROM batch WHERE batchid = '{$batchid[$key]}'";
        $run_sql = db_exec($rem_sql) or errDie("Unable to remove batch entry.");
    }
    $write .= "\n\t\t\t\t\t\t</table>\n\t\t\t\t\t\t{$cc}\n\t\t\t\t\t\t<br>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='25%'>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='trans-batch.php'>Add Journal Transactions to batch</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='batch-view.php'>View batch Entries</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t</table>";
    return $write;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid purchase number.");
    if (!isset($supid) && !isset($deptid)) {
        $v->isOk($supacc, "num", 1, 10, "Invalid Supplier Account number.");
    }
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            if ($qty > $qts[$keys]) {
                $v->isOk($qty, "num", 0, 0, "Error : Quantity for product number : <b>" . ($keys + 1) . "</b> is more that Qty Purchased");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($pur['pdate']) >= strtotime($blocked_date_from) and strtotime($pur['pdate']) <= 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>";
    }
    $pur['pdate'] = $p_year . "-" . $p_month . "-" . $p_day;
    # Get selected supplier info
    db_connect();
    if (isset($supid)) {
        $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql) or errDie("Unable to get supplier");
        if (pg_numrows($supRslt) < 1) {
            $error = "<li class='err'> Supplier not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $sup = pg_fetch_array($supRslt);
            $pur['supplier'] = $sup['supname'];
            $pur['supaddr'] = $sup['supaddr'];
            # Get department info
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$sup['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $supacc = $dept['credacc'];
        }
    } elseif (isset($deptid)) {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Department not Found.";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = $dept['pca'];
        }
    }
    # check if purchase has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    # Insert purchase to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $refnum = getrefnum();
    /*refnum*/
    db_connect();
    if (isset($qtys)) {
        # amount of stock in
        $totstkamt = array();
        $resub = 0;
        # Get subtotal
        foreach ($qtys as $keys => $value) {
            # Skip zeros
            if ($qtys[$keys] < 1) {
                continue;
            }
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        }
        $SUBTOTAL = array_sum($amt);
        $revat = 0;
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            $sql = "SELECT * FROM nons_pur_items WHERE cod = '{$cod[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # Calculate cost amount bought
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
            /* delivery charge */
            # Calculate percentage from subtotal
            $perc[$keys] = $amt[$keys] / $SUBTOTAL * 100;
            # Get percentage from shipping charges
            $shipc[$keys] = $perc[$keys] / 100 * $shipchrg;
            # add delivery charges
            $amt[$keys] += $shipc[$keys];
            /* end delivery charge */
            # the subtotal + delivery charges
            $resub += $amt[$keys];
            # calculate vat
            $svat[$keys] = svat($amt[$keys], $stkd['amt'], $stkd['svat']);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Vat for Non-Stock Purchase No. {$pur['purnum']}", -$amt[$keys], -$svat[$keys]);
            # received vat
            $revat += $svat[$keys];
            # make amount vat free
            if ($pur['vatinc'] == "yes") {
                $amt[$keys] = $amt[$keys] - $svat[$keys];
            }
            # Update Order items
            $sql = "UPDATE nons_pur_items SET rqty = (rqty + '{$qtys[$keys]}') WHERE cod = '{$cod[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            /* ?: refer to :Code Insert:
            			# keep records for transactions
            			if(isset($totstkamt[$stkacc[$keys]])){
            				$totstkamt[$stkacc[$keys]] += $amt[$keys];
            			}else{
            				$totstkamt[$stkacc[$keys]] = $amt[$keys];
            			}
            			*/
            # check if there are any outstanding items
            $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            # if none the set to received
            if (pg_numrows($stkdRslt) < 1) {
                # update surch_int(received = 'y')
                $sql = "UPDATE nons_purchases SET received = 'y', supplier = '{$pur['supplier']}', supaddr = '{$pur['supaddr']}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF);
            }
        }
    }
    # Update purchase on the DB
    if ($pur['part'] == 'y') {
        # Update purchase on the DB
        $sql = "UPDATE nons_purchases SET shipchrg = (shipchrg + '{$shipchrg}'), refno = '{$refno}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    } else {
        # Update purchase on the DB
        $sql = "UPDATE nons_purchases SET shipchrg = '{$shipchrg}', refno = '{$refno}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    }
    /* Transactions */
    /* - Start Hooks - */
    /* - End Hooks - */
    $detadd = "";
    if (isset($supid)) {
        $detadd = " from Supplier {$sup['supname']}";
    }
    $sdate = $pur['pdate'];
    /* ?:refer to :Code Insert:
    		# record transaction  from data
    		foreach($totstkamt as $stkacc => $wamt){
    			# Debit Stock and Credit Suppliers control
    			writetrans($stkacc, $supacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. $pur[purnum] Received $detadd.");
    			pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. $pur[purnum] Received $detadd.", $wamt, "Cash Purchase");
    		}*/
    # Calc Vat amount on (subtot + delchrg)
    $vatamt = $revat;
    # Add vat if not included
    if ($pur['vatinc'] == 'no') {
        $retot = $resub + $vatamt;
    } elseif ($pur['vatinc'] == "novat") {
        $retot = $resub;
        $vatamt = 0;
    } else {
        $retot = $resub;
    }
    # get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    $tot_post = 0;
    if ($vatamt != 0) {
        $tot_post += $vatamt;
        # Debit bank and credit the account involved
        writetrans($vatacc, $supacc, $pdate, $refnum, $vatamt, "Non-Stock Purchase Vat paid on Non-Stock Purchase No. {$pur['purnum']} {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $vatamt, "Cash Purchase Vat");
        # Record the payment on the statement
        db_connect();
        $sdate = $pur['pdate'];
    }
    if (isset($supid)) {
        $DAte = $pur['pdate'];
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$retot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$sup['supid']}','{$DAte}', '{$dept['credacc']}', '{$retot}','Non-Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}','" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        suppledger($sup['supid'], $wh['stkacc'], $DAte, $pur['purid'], "Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'c');
        db_connect();
        # update the supplier age analysis (make balance less)
        /* Make transaction record for age analysis */
        $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, div) VALUES('{$sup['supid']}', '{$pur['purnum']}', '{$DAte}', '{$retot}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    /* End Transactions */
    # commit updating
    // pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    /* Update items found in ther linked purchase */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    db_conn($pur['spurprd']);
    $stab = $pur['spurtype'] == "int" ? "purch_int" : "purchases";
    $itab = $pur['spurtype'] == "int" ? "purint_items" : "pur_items";
    # Get purchase info
    $sql = "SELECT * FROM {$stab} WHERE purnum = '{$pur['spurnum']}' AND div = '" . USER_DIV . "'";
    $spurRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($spurRslt) < 1) {
        return "<li> - purchase Not Found</li>";
    }
    $spur = pg_fetch_array($spurRslt);
    $purs = explode(",", $pur['purs']);
    $TSUB = 0;
    foreach ($purs as $purID) {
        $purID += 0;
        db_connect();
        $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $p = pg_fetch_array($srchRslt);
            $TSUB += $p['subtot'];
            $Sl = "SELECT sum(unitcost) -sum(svat) as non FROM pur_items WHERE purid='{$p['purid']}' AND stkid=0";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $pi = pg_fetch_array($Ri);
            $pi = $pi['non'];
        }
        $sql = "SELECT * FROM movpurch WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $res = pg_fetch_array($srchRslt);
            db_conn($res['prd']);
            $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
            $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
            if (pg_numrows($srchRslt) > 0) {
                $p = pg_fetch_array($srchRslt);
                $TSUB += $p['subtot'];
                $Sl = "SELECT sum(unitcost)-sum(svat) as non FROM pur_items WHERE purid='{$p['purid']}' AND stkid=0";
                $Ri = db_exec($Sl) or errDie("Unable to get data.");
                $pi = pg_fetch_array($Ri);
                $pi = $pi['non'];
            } else {
                db_conn($res['prd']);
                $sql = "SELECT * FROM purch_int WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
                $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
                if (pg_numrows($srchRslt) > 0) {
                    $p = pg_fetch_array($srchRslt);
                    $TSUB += $p['subtot'];
                    // 					$Sl="SELECT sum(unitcost)-sum(svat) as non FROM purint_items WHERE purid='$p[purid]' AND stkid=0";
                    //
                    // 					$Ri=db_exec($Sl) or errDie("Unable to get data.");
                    // 					$pi=pg_fetch_array($Ri);
                    // 					$pi=$pi['non'];
                    $pi = 0;
                }
            }
        }
        if (!isset($pi)) {
            $pi = 0;
        }
        $TSUB -= $pi;
    }
    $purs = explode(",", $pur['purs']);
    foreach ($purs as $purID) {
        $itab = "pur_items";
        $purID += 0;
        //print $purID;
        db_connect();
        $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $pur['spurprd'] = "cubit";
        }
        $sql = "SELECT * FROM movpurch WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $res = pg_fetch_array($srchRslt);
            db_conn($res['prd']);
            $pur['spurprd'] = $res['prd'];
        }
        db_conn($pur['spurprd']);
        $test = $pur['spurprd'];
        $test += 0;
        if ($test != 0) {
            $s = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
            $q = db_exec($s) or errDie("Unable to retrieve purchases from database.");
            if (pg_num_rows($q) > 0) {
                $p = pg_fetch_array($q);
                $purID = $p['purid'];
            } else {
                $s = "SELECT * FROM purch_int WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
                $q = db_exec($s) or errDie("Unable to retrieve purchases from database.");
                if (pg_num_rows($q) > 0) {
                    $p = pg_fetch_array($q);
                    $purID = $p['purid'];
                    $itab = "purint_items";
                }
            }
        }
        # Get selected stock
        $sql = "SELECT * FROM {$itab} WHERE purid = '{$purID}' AND div = '" . USER_DIV . "' AND stkid!=0";
        $sstkdRslt = db_exec($sql);
        while ($sstk = pg_fetch_array($sstkdRslt)) {
            if ($pur['spurtype'] == "int") {
                $csamt = sprint($sstk['amt'] / $TSUB * ($retot - $vatamt));
            } else {
                if ($spur['vatinc'] == "yes") {
                    $csamt = sprint(($sstk['amt'] - $sstk['svat']) / $TSUB * ($retot - $vatamt));
                } else {
                    $csamt = sprint($sstk['amt'] / $TSUB * ($retot - $vatamt));
                }
            }
            db_connect();
            # get selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            /* Code insert */
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT * FROM warehouses WHERE whid = '{$stkt['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $tot_post += $csamt;
            writetrans($wh['stkacc'], $supacc, $pdate, $refnum, $csamt, "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.");
            /* End code insert */
            db_connect();
            if ($stkt['units'] != 0) {
                $sql = "UPDATE stock SET csamt = (csamt + '{$csamt}'), csprice = (csamt/units) WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            } else {
                $sql = "UPDATE stock SET csamt = (csamt + '{$csamt}') WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            $sdate = $pur['pdate'];
            stockrec($stkt['stkid'], $stkt['stkcod'], $stkt['stkdes'], 'dt', $sdate, 0, $csamt, "Cost Increased with Non Stock Purchase No. {$pur['purnum']}");
            # get selected stock
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            # $csprice = round(($stk['csamt']/$stk['units']), 2);
            if ($stkt['units'] > 0) {
                $csprice = round($stkt['csamt'] / $stkt['units'], 2);
            } else {
                $csprice = round($stkt['csprice'], 2);
            }
            # update stock(csprice = (csamt/units))
            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        }
    }
    //exit;
    /*
    		db_conn($pur['spurprd']);
    		# Get selected stock
    		$sql = "SELECT * FROM $itab WHERE purid = '$spur[purid]' AND div = '".USER_DIV."' AND stkid!=0";
    		$sstkdRslt = db_exec($sql);
    		while($sstk = pg_fetch_array($sstkdRslt)){
    			if($pur['spurtype'] == "int"){
    				$csamt = sprint(($sstk['amt']/$TSUB) * ($retot - $vatamt));
    			}else{
    				if($spur['vatinc'] == "yes"){
    					$csamt = sprint((($sstk['amt'] - $sstk['svat'])/$TSUB) * ($retot - $vatamt));
    				}else{
    					$csamt = sprint((($sstk['amt'])/$TSUB) * ($retot - $vatamt));
    				}
    			}
    
    			db_connect();
    			# get selected stock
    			$sql = "SELECT * FROM stock WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$stktRslt = db_exec($sql);
    			$stkt = pg_fetch_array($stktRslt);
    
    			/* Code insert
    				# get warehouse name
    				db_conn("exten");
    				$sql = "SELECT * FROM warehouses WHERE whid = '$stkt[whid]' AND div = '".USER_DIV."'";
    				$whRslt = db_exec($sql);
    				$wh = pg_fetch_array($whRslt);
    
    				$tot_post+=$csamt;
    
    				writetrans($wh['stkacc'], $supacc, date("d-m-Y"), $refnum, $csamt, "Non-Stock Purchase No. $pur[purnum] Received $detadd.");
    			/* End code insert
    
    			db_connect();
    			if($stkt['units'] <> 0){
    				$sql = "UPDATE stock SET csamt = (csamt + '$csamt'), csprice = (csamt/units) WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    				$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    			}else{
    				$sql = "UPDATE stock SET csamt = (csamt + '$csamt') WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    				$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    			}
    			$sdate = $pur['pdate'];
    			stockrec($stkt['stkid'], $stkt['stkcod'], $stkt['stkdes'], 'dt', $sdate, 0, $csamt, "Cost Increased with Non Stock Purchase No. $pur[purnum]");
    
    			# get selected stock
    			db_connect();
    			$sql = "SELECT * FROM stock WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$stktRslt = db_exec($sql);
    			$stkt = pg_fetch_array($stktRslt);
    
    			# $csprice = round(($stk['csamt']/$stk['units']), 2);
    			if($stkt['units'] > 0){
    				$csprice = round(($stkt['csamt']/$stkt['units']), 2);
    			}else{
    				$csprice = round($stkt['csprice'], 2);
    			}
    
    			# update stock(csprice = (csamt/units))
    			$sql = "UPDATE stock SET csprice = '$csprice' WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    		}
    */
    $diff = sprint($retot - $tot_post);
    if ($diff > 0) {
        writetrans($cvacc, $supacc, $sdate, $refnum, $diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']}");
    } elseif ($diff < 0) {
        writetrans($supacc, $cvacc, $sdate, $refnum, -$diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']}");
    }
    /* End Update items found in ther linked purchase */
    /* Start moving if purchase received */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        if (isset($supid)) {
            $ctyp = "sup";
            $typeid = $supid;
        } elseif (isset($deptid)) {
            $ctyp = "led";
            $typeid = $deptid;
        } else {
            $ctyp = "ot";
            $typeid = 0;
        }
        # copy purchase
        db_conn($pur['prd']);
        $pur['spurprd'] += 0;
        $pur['spurnum'] += 0;
        $sql = "INSERT INTO nons_purchases(purid, deptid, supplier, supaddr, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, remarks, refno, received, done, div, purnum,ctyp,typeid,spurprd,spurnum)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}','{$ctyp}','{$typeid}','{$pur['spurprd']}','{$pur['spurnum']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Purchase to Cubit.", SELF);
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert purchase items
            db_conn($pur['prd']);
            $sql = "INSERT INTO nons_pur_items(purid, cod, des, qty, unitcost, amt, ddate, div,svat) VALUES('{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['ddate']}', '" . USER_DIV . "','{$stktc['svat']}')";
            $rslt = db_exec($sql) or errDie("Unable to insert purchase items to Cubit.", SELF);
        }
        db_connect();
        # Remove the purchase from running DB
        $sql = "DELETE FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Remove those purchase items from running DB
        $sql = "DELETE FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving purchase received */
    $cc = "<script> CostCenter('ct', 'Non-Stock Purchase', '{$pdate}', 'Non Stock Purchase No.{$pur['purnum']}', '" . ($retot - $vatamt) . "', ''); </script>";
    // Final Layout
    $write = "\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Non-Stock Purchase received</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>Non-Stock Purchase receipt has been recorded.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<p>\n\t\t\t\t<table " . TMPL_tblDflts . ">\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='nons-purchase-view.php'>View purchases</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t</table>";
    return $write;
}
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;
}