function write(&$frm)
{
    if (isset($_REQUEST["btn_back"])) {
        return enter($frm);
    }
    if ($frm->validate("write")) {
        return confirm($frm);
    }
    $upd = new dbUpdate("suppstock", "cubit");
    $del = new dbDelete("suppstock", "cubit");
    foreach ($_REQUEST["stkcod"] as $suppid => $stkcod) {
        if (empty($stkcod)) {
            $del->setOpt("suppid='{$suppid}' AND stkid='{$_REQUEST['id']}'");
            $del->run();
            continue;
        }
        $cols = grp(m("suppid", $suppid), m("stkid", $_REQUEST["id"]), m("stkcod", $stkcod));
        $upd->setOpt($cols, "suppid='{$suppid}' AND stkid='{$_REQUEST['id']}'");
        $upd->run(DB_REPLACE);
    }
    foreach ($_REQUEST["stkdes"] as $suppid => $stkdes) {
        if (empty($stkcod)) {
            $del->setOpt("suppid='{$suppid}' AND stkid='{$_REQUEST['id']}'");
            $del->run();
            continue;
        }
        $cols = grp(m("suppid", $suppid), m("stkid", $_REQUEST["id"]), m("stkdes", $stkdes));
        $upd->setOpt($cols, "suppid='{$suppid}' AND stkid='{$_REQUEST['id']}'");
        $upd->run(DB_REPLACE);
    }
    $OUT = "<script>window.close();</script>";
    return $OUT;
}
function printLea($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($f_day, "num", 1, 2, "Invalid from Date day.");
    $v->isOk($f_month, "num", 1, 2, "Invalid from Date month.");
    $v->isOk($f_year, "num", 1, 4, "Invalid from Date Year.");
    $v->isOk($to_day, "num", 1, 2, "Invalid to Date day.");
    $v->isOk($to_month, "num", 1, 2, "Invalid to Date month.");
    $v->isOk($to_year, "num", 1, 4, "Invalid to Date Year.");
    # mix dates
    $fromdate = $f_year . "-" . $f_month . "-" . $f_day;
    $todate = $to_year . "-" . $to_month . "-" . $to_day;
    $v->isOk($fromdate, "date", 1, 1, "Invalid from date.");
    $v->isOk($todate, "date", 1, 1, "Invalid to date.");
    if ($v->isError()) {
        $err = $v->genErrors();
        return $err;
    }
    if (isset($empnum)) {
        $OUTPUT = genslip($empnum, $fromdate, $todate);
    } else {
        $OUTPUT = "";
        $qry = new dbSelect("employees", "cubit", grp(m("cols", "empnum"), m("where", "div='" . USER_DIV . "'")));
        $qry->run();
        while ($row = $qry->fetch_array()) {
            $OUTPUT .= paged(genslip($row["empnum"], $fromdate, $todate));
        }
    }
    require "../tmpl-print.php";
}
function bal($id)
{
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($id, "num", 1, 20, "Invalid Cash Flow Statement number.");
    # display errors, if any
    if ($v->isError()) {
        $theseErrors = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $theseErrors .= "<li class=err>" . $e["msg"];
        }
        $theseErrors .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $theseErrors;
    }
    # connect to core DB
    core_connect();
    # get the Trial Balance
    $cf = new dbSelect("save_cashflow", "core", grp(m("cols", "output, date_trunc('day', gentime) as gentime"), m("where", "id='{$id}'")));
    $cf->run();
    if ($cf->num_rows() < 1) {
        return "<center><li> Invalid Cash Flow Statement Number.</li></center>";
    }
    $stmnt = $cf->fetch_array();
    $OUTPUT = base64_decode($stmnt['output']);
    if (isset($_GET["xls"])) {
        $cftime = preg_replace("/ 00:00.*/", "", $stmnt["gentime"]);
        require_lib("xls");
        Stream("cashflow-{$cftime}", $OUTPUT);
    } else {
        require "../tmpl-print.php";
    }
}
function write(&$frm)
{
    if ($frm->validate("write")) {
        return edit($frm);
    }
    $cols = grp(m("value", $_POST["print_dialog"]));
    $qry = new dbUpdate("settings", "cubit", $cols, "constant='PRINT_DIALOG'");
    $qry->run(DB_UPDATE);
    $OUT = "\n\t<h3>Printing Options</h3>\n\tSuccessfully saved printing options.";
    return $OUT;
}
function write(&$frm)
{
    if ($frm->validate("write")) {
        return edit($frm);
    }
    $cols = grp(m("value", $_POST["vat_setting"]));
    $qry = new dbUpdate("settings", "cubit", $cols, "constant='PURCH_DEFAULT_VAT_SETTING'");
    $qry->run(DB_UPDATE);
    $OUT = "\n\t<h3>Purchase VAT Setting</h3>\n\tSuccessfully saved setting.";
    return $OUT;
}
function write()
{
    extract($_GET);
    if (!isset($id)) {
        $id = 0;
    }
    $cols = grp(m("name", $name), m("in_republic", $in_republic), m("meals", $meals), m("accid", $accid), m("div", USER_DIV));
    $subs = new dbUpdate("subsistence", "cubit", $cols, "id='{$id}'");
    $subs->run(DB_REPLACE);
    $OUT = "\n\t<h3>Define Subsistence Allowance</h3>\n\tSuccessfully created/updated subsistence allowance.";
    return $OUT;
}
/**
 * locates a supplier by name, if not found creates and returns id
 *
 * @param string $name company name
 * @return int
 */
function locateSupplier($name)
{
    $qry = new dbSelect("suppliers", "cubit", grp(m("cols", "supid"), m("where", "lower(supname)=lower('{$name}')")));
    $qry->run();
    if ($qry->num_rows() > 0) {
        $id = $qry->fetch_result();
    } else {
        // insert into new supps
        $id = -1;
    }
    $qry->free();
    return $id;
}
function write($frm)
{
    /* @var $frm cForm */
    if ($frm->validate("confirm")) {
        return edit($frm);
    }
    /* point of sale message at the bottom of the slip */
    $cols = grp(m("value", $_POST["posmsg"]));
    $upd = new dbUpdate("settings", "cubit", $cols, "constant='POSMSG'");
    $upd->run(DB_UPDATE);
    $OUT = "\n\t<h3>Point of Sale Settings</h3>\n\t\n\tSuccessfully updated.<br />";
    return $OUT;
}
function check_messages()
{
    $qry = new dbSelect("req", "cubit", grp(m("cols", "1"), m("where", "recipient='" . USER_NAME . "' AND alerted IS NULL")));
    $qry->run();
    if ($qry->num_rows() == 0) {
        return "NO MESSAGES";
    } else {
        $cols = grp(m("alerted", "1"));
        $upd = new dbUpdate("req", "cubit", $cols, "recipient='" . USER_NAME . "'");
        $upd->run(DB_UPDATE);
        $qry->setOpt(grp(m("where", "recipient='" . USER_NAME . "' AND viewed='0'")));
        $qry->run();
        return "MSGS: " . $qry->num_rows();
    }
}
function writesal($frm)
{
    if ($frm->validate("writesal")) {
        return entersal($frm);
    }
    extract($_POST);
    $upd = new dbUpdate("salpaid", "cubit", false);
    foreach ($sal as $payid => $salrate) {
        $cols = grp(m("salrate", $salrate), isset($hrs[$payid]) ? m("hours", $hrs[$payid]) : false);
        $upd->setOpt($cols, "id='{$payid}'");
        $upd->run(DB_UPDATE);
    }
    $OUT = "\n\t<h3>Previous Employee Salary Information</h3>\n\tSuccessfully updated employee payslip information.";
    return $OUT;
}
function write($frm)
{
    if (isset($_REQUEST["btn_back"])) {
        return select($frm);
    }
    /* @var $frm cForm */
    if ($frm->validate("confirm")) {
        return confirm($frm);
    }
    $cols = grp(m("value", $_REQUEST["emp_year"]));
    $upd = new dbUpdate("settings", "cubit", $cols, "constant='EMP_TAXYEAR'");
    $upd->run(DB_UPDATE);
    $OUT = "\n\t<h3>Active Tax Year</h3>\n\tSuccessfully updated active Tax Year to {$_REQUEST['emp_year']}";
    return $OUT;
}
function buildlist(&$frm)
{
    if (!isset($_GET["cusnum"])) {
        invalid_use();
    }
    $cust = qryCustomer($_GET["cusnum"]);
    $qry = new dbSelect("plist_prices", "exten", grp(m("where", "listid='{$cust['pricelist']}' AND div='" . USER_DIV . "'")));
    $qry->run();
    $pli = array();
    $pli_noshow = array();
    while ($row = $qry->fetch_array()) {
        if ($row["show"] == "Yes") {
            $pli[$row["stkid"]] = $row["price"];
        } else {
            $pli_noshow[$row["stkid"]] = $row["price"];
        }
    }
    $qry = new dbSelect("stock", "cubit", grp(m("where", "div='" . USER_DIV . "'")));
    $qry->run();
    $plist = "";
    while ($row = $qry->fetch_array()) {
        if (isset($pli_noshow[$row["stkid"]])) {
            continue;
        }
        if (isset($pli[$row["stkid"]])) {
            $price = $pli[$row["stkid"]];
        } else {
            $price = $row["selamt"];
        }
        $desc = preg_replace("/,/", "", $row["stkdes"]);
        $plist .= "{$row['stkcod']},{$price},{$desc}\n";
    }
    /* @var $frm cForm */
    $frm->setFormParm("post", "../emailsave_page.php");
    $frm->setkey("sendmails");
    $frm->add_hidden("emailsavepage_key", "sendmails", "string");
    $frm->add_hidden("emailsavepage_action", "email", "string");
    $frm->add_hidden("emailsavepage_content", base64_encode($plist), "string");
    $frm->add_hidden("emailsavepage_mime", "text/plain", "string");
    $frm->add_hidden("emailsavepage_subject", "Pricelist from " . COMP_NAME, "string");
    $frm->add_hidden("emailsavepage_name", "pricelist.csv", "string");
    $frm->add_heading("Sending Pricelist to Customer");
    $frm->add_layout("\n\t\t<tr %bgc>\n\t\t\t<td>Customer:</td>\n\t\t\t<td>{$cust['surname']}</td>\n\t\t</tr>\n\t\t<tr %bgc>\n\t\t\t<td>%disp[0]</td>\n\t\t\t<td>%fld[0]</td>\n\t\t</tr>");
    $frm->add_hidden("surnames[{$cust['cusnum']}]", $cust["surname"], "string");
    $frm->add_text("E-mail", "emailcust[{$cust['cusnum']}]", $cust["email"], "string", "1:255");
    return $frm->getfrm_input();
}
function write()
{
    extract($_POST);
    $qry = new dbSelect("config", "trh", grp(m("where", "readonly='f'")));
    $qry->run();
    $upd = new dbUpdate("config", "trh");
    while ($row = $qry->fetch_array()) {
        if (isset(${$row["name"]})) {
            $cols = grp(m("value", ${$row["name"]}["value"]));
            $upd->setOpt($cols, "name='{$row['name']}'");
            $upd->run(DB_UPDATE);
        }
    }
    r2sListRestore("trh_comminit");
    $OUT = "\n\t<h3>Transactioning Configuration</h3>\n\tSuccessfully updated configuration.";
    return $OUT;
}
function printComp()
{
    $OUT = "\n    <h3>View Companies</h3>\n    <table " . TMPL_tblDflts . ">\n    <tr>\n    \t<th>Company Code</th>\n    \t<th>Company Name</th>\n    \t<th>Status</th>\n    \t<th>Options</th>\n    </tr>";
    $qry = new dbSelect("companies", DB_MCUBIT, grp(m("order", "name ASC")));
    $qry->run();
    $i = 0;
    while ($comp = $qry->fetch_array()) {
        $bgcolor = bgcolor($i);
        $status = ucfirst($comp["status"]);
        $OUT .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>{$comp['code']}</td>\n\t\t\t<td>{$comp['name']}</td>\n\t\t\t<td>{$status}</td>";
        if ($comp["status"] == "removed") {
            $OUT .= "\n\t\t\t<td><a href='company-rem.php?key=recover&code={$comp['code']}'>Recover</a></td>";
        }
        $OUT .= "\n\t\t\t<td><a href='company-rem.php?key=confirm&perm=t&code={$comp['code']}'>" . ($comp["status"] == "removed" ? "Remove Permanently (CAN NOT BE RECOVERED)" : "Remove") . "</a></td>\n\t\t</tr>";
    }
    $OUT .= "\n\t</table>" . mkQuickLinks(ql("company-new.php", "Add New Company"));
    return $OUT;
}
function write()
{
    extract($_POST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($salespno, "num", 1, 10, "Invalid Sales Person number.");
    $v->isOk($salesp, "string", 1, 255, "Invalid Sales Person name.");
    if ($v->isError()) {
        return $v->genErrors();
    }
    $cols = grp(m("salespno", $salespno), m("salesp", $salesp), m("com", $com), m("div", USER_DIV));
    $qry = new dbUpdate("salespeople", "exten", $cols);
    $qry->run(DB_INSERT);
    if ($qry->affected() < 1) {
        return "<li class=err>Unable to add sales person to Cubit.";
    }
    $write = "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th>Sales Person added to system</th>\n\t</tr>\n\t<tr class='text'><td>New Sales Person <b>{$salesp}</b>, has been\n\t\tsuccessfully added to the system.</td>\n\t</tr>\n\t</table>";
    return $write;
}
function view()
{
    // Connect to database
    core_Connect();
    // Query server
    $cf = new dbSelect("save_cashflow", "core", grp(m("where", "div='" . USER_DIV . "'")));
    $cf->run();
    if ($cf->num_rows() < 1) {
        $OUTPUT = "<li> There are no saved Cash Flow Statements.";
    } else {
        // Set up table to display in
        $OUTPUT = "\n\t\t<h3>View Saved Cash Flow Statements</h3>\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=300>\n\t\t<tr>\n\t\t\t<th>Statement No.</th>\n\t\t\t<th>Generated</th>\n\t\t\t<th colspan=2>Options</th>\n\t\t</tr>";
        // display all statements
        while ($stmnt = $cf->fetch_array()) {
            $OUTPUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$stmnt['id']}({$stmnt['des']})</td>\n\t\t\t\t<td>{$stmnt['gentime']}</td>\n\t\t\t\t<td><a target='_blank' href='cash-flow-print.php?id={$stmnt['id']}'>Print</a></td>\n\t\t\t\t<td><a href='cash-flow-print.php?id={$stmnt['id']}&xls=t'>Spreadsheet</a></td>\n\t\t\t</tr>";
        }
        $OUTPUT .= "</table>";
    }
    $OUTPUT .= "\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=datacell><td><a href='index-reports.php'>Financials</a></td></tr>\n\t<tr class=datacell><td><a href='index-reports-stmnt.php'>Current Year Financial Statements</a></td></tr>\n\t<tr class='bg-odd'><td><a href='../main.php'>Main Menu</a></td></tr>\n\t</table>";
    // call template to display the info and die
    return $OUTPUT;
}
function add_tbdata(&$oc, $schema, $yearsback = 0)
{
    global $MONPRD, $PRDMON;
    /* fetch prev year trial bal data */
    $tb = new dbSelect("trial_bal_actual", $schema, grp(m("where", "period!='0'"), m("order", "period, acctype, topacc, accnum")));
    $tb->run();
    $cprd = false;
    $cprd_name = false;
    while ($row = $tb->fetch_array()) {
        /* the period in the table data changed */
        if ($cprd != $row["period"]) {
            $cprd = $row["period"];
            $year = getYearOfFinMon($PRDMON[$cprd]) - $yearsback;
            $mon = getMonthNameS($PRDMON[$cprd]);
            $cprd_name = "{$mon} {$year}";
            $oc[$cprd_name] = array();
        }
        if ($row["period"] == 1 && $row["acctype"] != "B") {
            $hcode = new dbSelect("trial_bal", $schema, grp(m("where", "period='1' AND accid='{$row['accid']}'"), m("limit", 1)));
            $hcode->run();
            $row = $hcode->fetch_array();
        } else {
            if ($row["period"] == 1 && $row["topacc"] == "5200" && $row["accnum"] == "000") {
                /* calculate previous year profit/loss */
                $sql = "SELECT SUM(tb.credit) AS credit, SUM(tb.debit) AS debit\n\t\t\t\t\tFROM core.accounts acc LEFT JOIN {$schema}.trial_bal tb\n\t\t\t\t\t\tON acc.accid=tb.accid AND acc.div=tb.div\n\t\t\t\t\tWHERE (acc.acctype='I' OR acc.acctype='E') AND acc.div='" . USER_DIV . "'\n\t\t\t\t\t\tAND tb.period='0'";
                $qry = new dbSql($sql);
                $qry->run();
                /* then deduct from debit/credit of retained income/accumulated loss */
                $qry->fetch_array();
                $row["debit"] -= $qry->d["debit"];
                $row["credit"] -= $qry->d["credit"];
            }
        }
        /* store data */
        $oc[$cprd_name]["{$row['topacc']}/{$row['accnum']} {$row['accname']}"] = array("debit" => $row["debit"], "credit" => $row["credit"]);
    }
    #sort array to make some sense
    $oc = natksort($oc);
}
function request($frm)
{
    if (isset($_POST["btn_back"])) {
        return enter($frm);
    }
    if ($frm->validate("request")) {
        return confirm($frm);
    }
    $newkey = genkey();
    if (isset($_REQUEST["suppid"])) {
        $suppid = $_REQUEST["suppid"];
        $custid = "0";
    } else {
        $custid = $_REQUEST["custid"];
        $suppid = "0";
    }
    $cols = grp(m("introtime", raw("CURRENT_TIMESTAMP")), m("introip", "0.0.0.0"), m("email", $_REQUEST["email"]), m("custid", $custid), m("suppid", $suppid), m("key", dbrow("0.0.0.0/0", "", $newkey)), m("userid", USER_ID));
    $upd = new dbUpdate("keys", "trh", $cols);
    $upd->run(DB_INSERT);
    if ($upd->affected() > 0) {
        if (isset($_REQUEST["suppid"])) {
            if (($r = send_trhmsg("supp", $_REQUEST["suppid"], $_REQUEST["email"], "reqkey", $newkey)) === true) {
                $OUT = "Sent request for communication to supplier. On response you will be notified.";
            } else {
                $OUT = "Error sending request for communication: {$r}";
            }
        } else {
            if (($r = send_trhmsg("cust", $_REQUEST["custid"], $_REQUEST["email"], "reqkey", $newkey)) === true) {
                $OUT = "Sent request for communication to customer. On response you will be notified.";
            } else {
                $OUT = "Error sending request for communication: {$r}";
            }
        }
    } else {
        $OUT = "Error sending request for communication: Error updating database.";
    }
    return $OUT;
}
function details($_POST, $errata = "<br>")
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($budname, "string", 1, 255, "Invalid Budget Name.");
    $v->isOk($budfor, "string", 1, 20, "Invalid Budget for option.");
    $v->isOk($budtype, "string", 1, 20, "Invalid Budget type.");
    $v->isOk($fromprd, "string", 1, 20, "Invalid Budget period.");
    $v->isOk($toprd, "string", 1, 20, "Invalid Budget period.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>{$e['msg']}</li>";
        }
        return slctOpt($confirm);
    }
    global $BUDFOR, $TYPES, $PERIODS;
    $vbudfor = $BUDFOR[$budfor];
    $vbudtype = $TYPES[$budtype];
    $vfromprd = $PERIODS[$fromprd];
    $vtoprd = $PERIODS[$toprd];
    /* budget headings */
    if ($budfor == 'cost') {
        $head = "\n\t\t<tr>\n\t\t\t<th>Select Cost Centers</th>";
    } else {
        $head = "\n\t\t<tr>\n\t\t\t<th>Select Accounts</th>";
    }
    if ($fromprd < $toprd) {
        for ($i = $fromprd; $i <= $toprd; $i++) {
            $head .= "<th>{$PERIODS[$i]}</th>";
        }
    } elseif ($fromprd > $toprd) {
        for ($i = $fromprd; $i <= 12; $i++) {
            $head .= "<th>{$PERIODS[$i]}</th>";
        }
        for ($i = 1; $i <= $toprd; $i++) {
            $head .= "<th>{$PERIODS[$i]}</th>";
        }
    } else {
        $head .= "<th>{$PERIODS[$toprd]}</th>";
    }
    $head .= "<th>Annual Total</th>";
    $head .= "</tr>";
    /* Toggle Options */
    $list = "";
    $rowcnt = 0;
    $cellcnt = 0;
    # budget for
    $js_funcs_mon = "var tot_annual = new Array();";
    $js_funcs_tot = "";
    if ($budfor == 'cost') {
        # cost centers
        db_connect();
        $sql = "SELECT * FROM costcenters WHERE div = '" . USER_DIV . "' ORDER BY centername ASC";
        $ccRslt = db_exec($sql);
        if (pg_numrows($ccRslt) < 1) {
            return "<li>There are No cost centers in Cubit.";
        }
        $numacc = pg_num_rows($ccRslt);
        $cellcnt = $numacc * 3;
        while ($cc = pg_fetch_array($ccRslt)) {
            if ($rowcnt++ % 9 == 0) {
                $list .= $head;
            }
            $ccid = $cc["ccid"];
            if (isset($all) || isset($ccids[$ccid])) {
                $ch = "checked";
            } else {
                $ch = "";
            }
            $ci = $numacc + $rowcnt + 1;
            // extra one added so submit button is after annuals
            $list .= "\n\t\t\t<tr class='bg-odd'>\n\t\t\t\t<td><input tabindex='{$ci}' id='cb{$ccid}' type=checkbox name='ccids[{$ccid}]' value='{$cc['ccid']}' {$ch}>{$cc['centercode']} - {$cc['centername']}</td>";
            # Budget prd
            $tot_annual = 0;
            $js_totannuals = array();
            if ($fromprd <= $toprd) {
                for ($i = $fromprd; $i <= $toprd; $i++) {
                    if (!isset($amts[$ccid][$i])) {
                        $amts[$ccid][$i] = 0;
                    }
                    $tot_annual += $amts[$ccid][$i];
                    $js_totannuals[] = "amts_{$ccid}_{$i}";
                    ++$cellcnt;
                    $list .= "<td nowrap>" . CUR . " <input tabindex='{$cellcnt}' type=text size=7 id='amts_{$ccid}_{$i}' onChange='changedVal{$ccid}();' name=amts[{$ccid}][{$i}] value='" . $amts[$ccid][$i] . "'></td>";
                }
            } elseif ($fromprd > $toprd) {
                for ($i = $fromprd; $i <= 12; $i++) {
                    if (!isset($amts[$ccid][$i])) {
                        $amts[$ccid][$i] = 0;
                    }
                    $tot_annual += $amts[$ccid][$i];
                    $js_totannuals[] = "amts_{$ccid}_{$i}";
                    ++$cellcnt;
                    $list .= "<td nowrap>" . CUR . " <input tabindex='{$cellcnt}' type=text size=7 id='amts_{$ccid}_{$i}' onChange='changedVal{$ccid}();' name=amts[{$ccid}][{$i}] value='" . $amts[$ccid][$i] . "'></td>";
                }
                for ($i = 1; $i <= $toprd; $i++) {
                    if (!isset($amts[$ccid][$i])) {
                        $amts[$ccid][$i] = 0;
                    }
                    $tot_annual += $amts[$ccid][$i];
                    $js_totannuals[] = "amts_{$ccid}_{$i}";
                    ++$cellcnt;
                    $list .= "<td nowrap>" . CUR . " <input tabindex='{$cellcnt}' type=text size=7 id='amts_{$ccid}_{$i}' name=amts[{$ccid}][{$i}] value='" . $amts[$ccid][$i] . "'></td>";
                }
                //}else{
                //	if (!isset($amts[$cc["ccid"]][$i])) $amts[$cc["ccid"]][$i] = 0;
                //	$list .= "<td nowrap>".CUR." <input type=text size=7 onChange='changedVal$ccid();' name=amts[$cc[ccid]][$toprd] value='".$amts[$cc["ccid"]][$toprd]."'></td>";
            }
            $js_funcs_mon .= "\n\t\t\tfunction changedVal{$ccid}() {\n\t\t\t\tgetObject('cb{$ccid}').checked = true;\n\n\t\t\t\ttot_annual[{$ccid}] = 0;";
            $months_cnt = count($js_totannuals);
            $js_funcs_tot .= "\n\t\t\tfunction changedTot{$ccid}(totobj) {\n\t\t\t\tmthval = parseFloat(totobj.value) / {$months_cnt};\n\n\t\t\t\tsf = 0;";
            $last = 0;
            foreach ($js_totannuals as $fid) {
                ++$last;
                $js_funcs_mon .= "\n\t\t\t\t\tobj = getObject('{$fid}');\n\t\t\t\t\tval = parseFloat(obj.value);\n\t\t\t\t\tobj.value = val.toFixed(2)\n\t\t\t\t\ttot_annual[{$ccid}] += val;";
                $js_funcs_tot .= "\n\t\t\t\t\tobj = getObject('{$fid}');";
                if ($last != $months_cnt) {
                    $js_funcs_tot .= "\n\t\t\t\t\t\tobj.value = (Math.round(100*mthval)/100).toFixed(2);\n\t\t\t\t\t\tsf += Math.round(100*mthval)/100;";
                } else {
                    $js_funcs_tot .= "\n\t\t\t\t\t\tobj.value = (parseFloat(totobj.value) - sf).toFixed(2);";
                }
            }
            $js_funcs_mon .= "\n\t\t\t\t//getObject('annual{$ccid}').innerHTML = '" . CUR . " ' + tot_annual[{$ccid}].toFixed(2);\n\t\t\t\tgetObject('annual_{$ccid}').value = tot_annual[{$ccid}].toFixed(2);\n\t\t\t}\n\n\t\t\ttot_annual[{$ccid}] = {$tot_annual};\n";
            $js_funcs_tot .= "\n\t\t\t}\n";
            $tot_annual = sprint($tot_annual);
            //$list .= "<td nowrap><div id='annual$ccid'>".CUR." $tot_annual</div></td>";
            $list .= "\n\t\t\t<td nowrap>" . CUR . "\n\t\t\t\t<input tabindex='{$rowcnt}' type=text size=7 onchange='changedTot{$ccid}(this);' id='annual_{$accid}' name='annual[{$ccid}]' value='" . $tot_annual . "' />\n\t\t\t</td>";
        }
    } elseif ($budfor == 'acc') {
        # budget type
        if ($budtype == 'exp') {
            $acctype = "E";
        } elseif ($budtype == 'inc') {
            $acctype = "I";
        } else {
            $acctype = "B";
        }
        # accounts
        core_connect();
        $sql = "SELECT * FROM accounts WHERE acctype = '{$acctype}' AND div = '" . USER_DIV . "' ORDER BY accname ASC";
        $accRslt = db_exec($sql);
        if (pg_numrows($accRslt) < 1) {
            return "<li>There are No accounts in Cubit.";
        }
        $tbval = new dbSelect("trial_bal_actual", PYR_DB, grp(m("cols", "acctype, debit, credit")));
        $numacc = pg_num_rows($accRslt);
        $cellcnt += $numacc * 3;
        while ($acc = pg_fetch_array($accRslt)) {
            if ($acc["accname"] == "Retained Income / Accumulated Loss") {
                continue;
            }
            if ($rowcnt++ % 9 == 0) {
                $list .= $head;
            }
            $accid = $acc["accid"];
            /* create default values */
            for ($i = 1; $i <= 12; ++$i) {
                if (!isset($amts[$accid][$i])) {
                    if (isset($import)) {
                        $tbval->setOpt(grp(m("where", "accid='{$accid}' AND month='{$i}'")));
                        $tbval->run();
                        $tbd = $tbval->fetch_array();
                        switch ($tbd["acctype"]) {
                            case "I":
                                $bal = $tbval->d["credit"] - $tbval->d["debit"];
                                break;
                            case "E":
                            case "B":
                                $bal = $tbval->d["debit"] - $tbval->d["credit"];
                                break;
                        }
                        $amts[$accid][$i] = sprint($bal + $bal * $incperc / 100);
                    } else {
                        $amts[$accid][$i] = 0;
                    }
                }
            }
            if (isset($all) || isset($accids[$accid]) || isset($import)) {
                $ch = "checked";
            } else {
                $ch = "";
            }
            $ci = $numacc + $rowcnt + 1;
            // extra one added so submit button is after annuals
            $list .= "\n\t\t\t<tr class='bg-odd'>\n\t\t\t\t<td><input tabindex='{$ci}' id='cb{$accid}' type='checkbox' name='accids[{$accid}]' value='{$accid}' {$ch}>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>";
            # Budget prd
            $tot_annual = 0;
            $js_totannuals = array();
            if ($fromprd <= $toprd) {
                for ($i = $fromprd; $i <= $toprd; $i++) {
                    $tot_annual += $amts[$accid][$i];
                    $js_totannuals[] = "amts_{$accid}_{$i}";
                    ++$cellcnt;
                    $list .= "<td nowrap>" . CUR . " <input tabindex='{$cellcnt}' type=text size=7 onChange='changedVal{$accid}();' id='amts_{$accid}_{$i}' name=amts[{$accid}][{$i}] value='" . $amts[$accid][$i] . "'></td>";
                }
            } elseif ($fromprd > $toprd) {
                for ($i = $fromprd; $i <= 12; $i++) {
                    $tot_annual += $amts[$accid][$i];
                    $js_totannuals[] = "amts_{$accid}_{$i}";
                    ++$cellcnt;
                    $list .= "<td nowrap>" . CUR . " <input tabindex='{$cellcnt}' type=text size=7 onChange='changedVal{$accid}();' id='amts_{$accid}_{$i}' name=amts[{$accid}][{$i}] value='" . $amts[$accid][$i] . "' /></td>";
                }
                for ($i = 1; $i <= $toprd; $i++) {
                    $tot_annual += $amts[$accid][$i];
                    $js_totannuals[] = "amts_{$accid}_{$i}";
                    ++$cellcnt;
                    $list .= "<td nowrap>" . CUR . " <input tabindex='{$cellcnt}' type=text size=7 onChange='changedVal{$accid}();' id='amts_{$accid}_{$i}' name=amts[{$accid}][{$i}] value='" . $amts[$accid][$i] . "' /></td>";
                }
            }
            /* JAVA SCRIPT: BEGIN */
            $js_funcs_mon .= "\n\t\t\tfunction changedVal{$accid}() {\n\t\t\t\tgetObject('cb{$accid}').checked = true;\n\n\t\t\t\ttot_annual[{$accid}] = 0;";
            $months_cnt = count($js_totannuals);
            $js_funcs_tot .= "\n\t\t\tfunction changedTot{$accid}(totobj) {\n\t\t\t\tgetObject('cb{$accid}').checked = true;\n\t\t\t\tmthval = parseFloat(totobj.value) / {$months_cnt};\n\n\t\t\t\tsf = 0;";
            $last = 0;
            foreach ($js_totannuals as $fid) {
                ++$last;
                $js_funcs_mon .= "\n\t\t\t\t\tobj = getObject('{$fid}');\n\t\t\t\t\tval = parseFloat(obj.value);\n\t\t\t\t\tobj.value = val.toFixed(2);\n\t\t\t\t\ttot_annual[{$accid}] += val;";
                $js_funcs_tot .= "\n\t\t\t\t\tobj = getObject('{$fid}');";
                if ($last != $months_cnt) {
                    $js_funcs_tot .= "\n\t\t\t\t\t\tobj.value = (Math.round(100*mthval)/100).toFixed(2);\n\t\t\t\t\t\tsf += Math.round(100*mthval)/100;";
                } else {
                    $js_funcs_tot .= "\n\t\t\t\t\t\tobj.value = (parseFloat(totobj.value) - sf).toFixed(2);";
                }
            }
            $js_funcs_mon .= "\n\t\t\t\tgetObject('annual_{$accid}').value = tot_annual[{$accid}].toFixed(2);\n\t\t\t}\n\n\t\t\ttot_annual[{$accid}] = {$tot_annual};\n";
            $js_funcs_tot .= "\n\t\t\t}\n";
            /* JAVA SCRIPT: END */
            $tot_annual = sprint($tot_annual);
            //$list .= "<td nowrap><div id='annual$accid'>".CUR." $tot_annual</div></td>";
            $list .= "\n\t\t\t<td nowrap='t'>" . CUR . "\n\t\t\t\t<input tabindex='{$rowcnt}' type=text size=7 onchange='changedTot{$accid}(this);' id='annual_{$accid}' name='annual[{$accid}]' value='" . $tot_annual . "' />\n\t\t\t</td>\n\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>";
        }
    }
    /* End Toggle Options */
    $OUT = "\n\t<script>\n\t{$js_funcs_mon}\n\t{$js_funcs_tot}\n\t</script>\n\t<div>\n\t<center><h3>New Monthly Budget</h3>\n\t<form action='" . SELF . "' method=post name=form>\n\t<input type=hidden name=key value=confirm>\n\t<input type=hidden name=budname value='{$budname}'>\n\t<input type=hidden name=budfor value='{$budfor}'>\n\t<input type=hidden name=budtype value='{$budtype}'>\n\t<input type=hidden name=fromprd value='{$fromprd}'>\n\t<input type=hidden name=toprd value='{$toprd}'>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' align=center>\n\t\t<tr>\n\t\t\t<th colspan=2>Details</th>\n\t\t</tr>\n\t\t<tr class='bg-odd'>\n\t\t\t<td>Budget Name</td>\n\t\t\t<td>{$budname}</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td><br></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th colspan=2>Options</th>\n\t\t</tr>\n\t\t<tr class='bg-odd'>\n\t\t\t<td>Budget For</td>\n\t\t\t<td>{$vbudfor}</td>\n\t\t</tr>\n\t\t<tr class='bg-even'>\n\t\t\t<td>Budget Type</td>\n\t\t\t<td>{$vbudtype}</td>\n\t\t</tr>\n\t\t<tr class='bg-odd'>\n\t\t\t<td>Budget Period</td>\n\t\t\t<td>{$vfromprd} to {$vtoprd}</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td colspan=2>{$errata}</td>\n\t\t</tr>\n\t</table>\n\t</div>\n\t<div>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' align=center>\n\t\t{$list}\n\t</table>\n\t</div>\n\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' align=center>\n\t<tr>\n\t\t<td align='right'><input tabindex='" . ($rowcnt + 1) . "' type=submit value='Continue &raquo'></td>\n\t</tr>\n\t</table>\n\t</form>\n\t<p>\n\t<table border=0 cellpadding='2' cellspacing='1' width=15%>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class='bg-odd'><td align=center><a href='budget-view.php'>View Budgets</td></tr>\n\t\t<tr class='bg-odd'><td align=center><a href='../main.php'>Main Menu</td></tr>\n\t</table>";
    return $OUT;
}
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 write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($classcode, "string", 1, 255, "Invalid Classification code.");
    $v->isOk($classname, "string", 1, 255, "Invalid Classification name.");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirmCust .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    # check stock code
    db_connect();
    $sql = "SELECT classcode FROM stockclass WHERE lower(classcode) = lower('{$classcode}') AND div = '" . USER_DIV . "'";
    $cRslt = db_exec($sql);
    if (pg_numrows($cRslt) > 0) {
        $error = "<li class='err'> A Classification with code : <b>{$classcode}</b> already exists.</li>";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # connect to db
    db_connect();
    # write to db
    $sql = "INSERT INTO stockclass(classcode, classname, div) VALUES ('{$classcode}', '{$classname}', '" . USER_DIV . "')";
    $catRslt = db_exec($sql) or errDie("Unable to add class to system.", SELF);
    if (pg_cmdtuples($catRslt) < 1) {
        return "<li class='err'>Unable to add classname to database.</li>";
    }
    if (frmupdate_passon()) {
        $newlst = new dbSelect("stockclass", "cubit", grp(m("cols", "clasid, classname"), m("where", "div='" . USER_DIV . "'"), m("order", "classname ASC")));
        $newlst->run();
        $a = array();
        if ($newlst->num_rows() > 0) {
            while ($row = $newlst->fetch_array()) {
                $a[$row["clasid"]] = $row["classname"];
            }
        }
        $js = frmupdate_exec(array($a), true);
    } else {
        $js = "";
    }
    $write = "\n\t\t\t\t{$js}\n\t\t\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Classification added to system</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>New Classification <b>{$classname}</b>, has been successfully added to the system.</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 border=0 cellpadding='2' cellspacing='1'>\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='stockclass-view.php'>View Classifications</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='main.php'>Main Menu</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    return $write;
}
function add()
{
    extract($_REQUEST);
    $qry = new dbSelect("batch_cashbook", "cubit", grp(m("where", wgrp(m("cashid", "{$id}")))));
    $qry->run();
    if ($qry->num_rows() <= 0) {
        invalid_use("Invalid batch cashbook entry.");
    }
    $bcb = $qry->fetch_array();
    if ($bcb["chrgvat"] == "exc") {
        $bcb["amount"] -= $bcb["vat"];
    }
    extract($bcb, EXTR_SKIP);
    core_connect();
    $accs = qryAccounts();
    if ($accs->num_rows() <= 0) {
        $glacc = "There are no Income accounts in Cubit.";
    }
    $glacc = "<select name='accinv'>";
    while ($acc = $accs->fetch_array()) {
        if (isDisabled($acc['accid'])) {
            continue;
        }
        if ($accinv == $acc['accid']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $glacc .= "<option value='{$acc['accid']}' {$sel}>{$acc['accname']}</option>";
    }
    $glacc .= "</select>";
    $OUT = "\n\t\t\t\t<h3>Edit Bank Receipt</h3>\n\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t\t\t<input type='hidden' name='id' value='{$id}'>\n\t\t\t\t\t<input type='hidden' name='vat' value='{$bcb['vat']}' />\n\t\t\t\t\t<input type='hidden' name='orig_vatcode' value='{$bcb['vatcode']}' />\n\t\t\t\t\t<input type='hidden' name='orig_chrgvat' value='{$bcb['chrgvat']}' />\n\t\t\t\t\t<input type='hidden' name='orig_amount' value='{$bcb['amount']}' />\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Field</th>\n\t\t\t\t\t\t<th>Value</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 Account</td>\n\t\t\t\t\t\t<td valign='center'>\n\t\t\t\t\t\t\t<select name='bankid'>";
    db_connect();
    $qry->setTable("bankacct", "cubit");
    $qry->setOpt(grp(m("where", "btype!='int' AND div='" . USER_DIV . "'")));
    $qry->run();
    if ($qry->num_rows() <= 0) {
        return "<li class='err'> There are no accounts held at the selected Bank.\n\t\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
    }
    while ($acc = $qry->fetch_array()) {
        if (isset($bankid) && $bankid == $acc['bankid']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $OUT .= "<option value='{$acc['bankid']}' {$sel}>{$acc['accname']} - {$acc['bankname']} ({$acc['acctype']})</option>";
    }
    if (!isset($name)) {
        $name = "";
        $descript = "";
        $cheqnum = "";
        $amount = "";
        $chrgvat = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    $Vatcodes = "\n\t\t\t<select name='vatcode'>\n\t\t\t\t<option value='0'>Select</option>";
    $vacs = qryVatcode();
    $Vatcodes = db_mksel($vacs, "vatcode", $vatcode, "#id", "#code", "0:Select");
    list($o_year, $o_month, $o_day) = explode('-', $date);
    $sel1 = "";
    $sel2 = "";
    $sel3 = "";
    if ($chrgvat == "inc") {
        $sel1 = "checked=yes";
    } else {
        if ($chrgvat == "exc") {
            $sel2 = "checked=yes";
        } else {
            if ($chrgvat == "nov") {
                $sel3 = "checked=yes";
            } else {
                $sel1 = "checked=yes";
            }
        }
    }
    $OUT .= "\n\t\t</select>\n\t\t</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Date</td>\n\t\t<td>\n\t\t\t" . mkDateSelect("o", $o_year, $o_month, $o_day) . "\n\t\t</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Received from</td>\n\t\t<td valign='center'><input size='20' name='name' value='{$name}'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Description</td>\n\t\t<td valign='center'><textarea col='18' rows='3' name='descript'>{$descript}</textarea></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Reference</td>\n\t\t<td valign='center'><input size='20' name='reference' value='{$reference}'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Cheque Number</td>\n\t\t<td valign='center'><input size='20' name='cheqnum' value='{$cheqnum}'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Amount</td>\n\t\t<td valign='center'>" . CUR . " <input type='text' size='10' name='amount' value='" . sprint($amount) . "'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>VAT </td>\n\t\t<td>\n\t\t\t<input type='radio' name='chrgvat' value='inc' {$sel1}>Inclusive &nbsp;&nbsp;\n\t\t\t<input type='radio' name='chrgvat' value='exc' {$sel2}>Exclusive &nbsp;&nbsp;\n\t\t\t<input type='radio' name='chrgvat' value='nov' {$sel3}>No VAT\n\t\t</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>VAT Code</td>\n\t\t<td>{$Vatcodes}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td valign='top'>Select Contra Account</td>\n\t\t<td>{$glacc}</td>\n\t</tr>\n\t<tr>\n\t\t<td>&nbsp;</td>\n\t\t<td valign='center' align='right'><input type='submit' value='Confirm &raquo;'></td>\n\t</tr>\n\t</table>";
    # main table (layout with menu)
    $OUT .= mkQuickLinks();
    return $OUT;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    $supplier1 += 0;
    $supplier2 += 0;
    $supplier3 += 0;
    if (isset($back)) {
        return view_err($_POST);
    }
    $vatcode += 0;
    # Validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($whid, "num", 1, 50, "Invalid Store.");
    $v->isOk($catid, "num", 1, 50, "Invalid Stock Category.");
    $v->isOk($stkcod, "string", 1, 50, "Invalid stock code.");
    $v->isOk($stkdes, "string", 0, 255, "Invalid stock description.");
    $v->isOk($bar, "string", 0, 20, "Invalid bar code.");
    $v->isOk($clasid, "num", 1, 50, "Invalid Classification.");
    $v->isOk($buom, "string", 0, 10, "Invalid bought unit of measure.");
    $v->isOk($suom, "string", 0, 10, "Invalid selling unit of measure.");
    $v->isOk($rate, "num", 1, 10, "Invalid selling units per bought unit.");
    $v->isOk($shelf, "string", 0, 10, "Invalid Shelf number.");
    $v->isOk($row, "string", 0, 10, "Invalid Row number.");
    $v->isOk($minlvl, "num", 0, 10, "Invalid minimum stock level.");
    $v->isOk($maxlvl, "num", 0, 10, "Invalid maximum stock level.");
    $v->isOk($selamt, "float", 0, 10, "Invalid selling amount.");
    $v->isOk($markup, "float", 0, 10, "Invalid markup percentage.");
    $v->isOk($warranty, "string", 0, 80, "Invalid warranty.");
    $v->isOk($rfidtype, "string", 0, 80, "Invalid RFID type of tag.");
    $v->isOk($rfidfreq, "string", 0, 80, "Invalid RFID Frequency.");
    $v->isOk($rfidrate, "string", 0, 80, "Invalid RFID Tag read rate.");
    $minlvl += 0;
    $maxlvl += 0;
    $selamt += 0;
    # Display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        $confirm .= "\n\t\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>\n\t\t\t<P>\n\t\t\t<table " . TMPL_tblDflts . " width='100'>\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><a href='stock-view.php'>View Stock</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t</tr>\n\t\t\t</form>\n\t\t\t</table>";
        return $confirm;
    }
    # Get category name
    db_connect();
    $sql = "SELECT cat FROM stockcat WHERE catid = '{$catid}'";
    $catRslt = db_exec($sql);
    $cat = pg_fetch_array($catRslt);
    # Get class
    $sql = "SELECT classname FROM stockclass WHERE clasid = '{$clasid}' AND div = '" . USER_DIV . "'";
    $clasRslt = db_exec($sql);
    $clas = pg_fetch_array($clasRslt);
    # Check stock code
    db_connect();
    $sql = "SELECT stkcod FROM stock WHERE lower(stkcod) = lower('{$stkcod}') AND whid = '{$whid}' AND div = '" . USER_DIV . "'";
    $cRslt = db_exec($sql);
    if (pg_numrows($cRslt) > 0) {
        $error = "<li class='err'> An item with stock code : <b>{$stkcod}</b> already exists in the selected store.</li>";
        return view_err($_POST, $error);
    }
    if (strlen($bar) > 0) {
        $sql = "SELECT bar FROM stock WHERE lower(bar) = lower('{$bar}') AND div = '" . USER_DIV . "'";
        $cRslt = db_exec($sql);
        if (pg_numrows($cRslt) > 0) {
            $error = "<li class='err'> An item with Bar Code : <b>{$bar}</b> already exists.</li>";
            return $error;
        }
    }
    # Insert into stock
    db_connect();
    $sql = "\n\t\tINSERT INTO stock (\n\t\t\tsupplier1, supplier2, supplier3, stkcod, stkdes, prdcls, \n\t\t\tclassname, csamt, units, buom, suom, rate, \n\t\t\tshelf, row, minlvl, maxlvl, csprice, selamt, \n\t\t\texvat, catid, catname, whid, blocked, type, \n\t\t\tserd, alloc, com, bar, div, vatcode, \n\t\t\tmarkup, rfidtype, rfidfreq, rfidrate, warranty\n\t\t) VALUES (\n\t\t\t'{$supplier1}', '{$supplier2}', '{$supplier3}', '{$stkcod}', '{$stkdes}', '{$clasid}', \n\t\t\t'{$clas['classname']}', '0', '0', '{$buom}', '{$suom}', '{$rate}', \n\t\t\t'{$shelf}', '{$row}', '{$minlvl}', '{$maxlvl}', '0', '{$selamt}', \n\t\t\t'n', '{$catid}', '{$cat['cat']}', '{$whid}', 'n', '{$stktp}', \n\t\t\t'{$serd}', '0', '0', '{$bar}', '" . USER_DIV . "', '{$vatcode}', \n\t\t\t'{$markup}', '{$rfidtype}', '{$rfidfreq}', '{$rfidrate}', '{$warranty}'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
    # Get last stock ID
    $stkid = pglib_lastid("stock", "stkid");
    # Add this product to all pricelists
    db_conn("exten");
    $sql = "SELECT * FROM pricelist WHERE div = '" . USER_DIV . "'";
    $listRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($listRslt) > 0) {
        while ($list = pg_fetch_array($listRslt)) {
            db_conn("exten");
            $sql = "INSERT INTO plist_prices (listid, stkid, catid, clasid, price, div,show) VALUES ('{$list['listid']}', '{$stkid}', '{$catid}', '{$clasid}', '{$selamt}', '" . USER_DIV . "','Yes')";
            $rslt = db_exec($sql) or errDie("Unable to insert price list items to Cubit.", SELF);
        }
    }
    $sql = "SELECT * FROM spricelist WHERE div = '" . USER_DIV . "'";
    $listRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($listRslt) > 0) {
        while ($list = pg_fetch_array($listRslt)) {
            db_conn("exten");
            $sql = "INSERT INTO splist_prices (listid, stkid, catid, clasid, price, div) VALUES ('{$list['listid']}', '{$stkid}', '{$catid}', '{$clasid}', '0', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert price list items to Cubit.", SELF);
        }
    }
    /* adding from supplier stock */
    if (isset($supid) && isset($supstkcod)) {
        $cols = grp(m("suppid", $supid), m("stkid", $stkid), m("stkcod", $supstkcod));
        $upd = new dbUpdate("suppstock", "cubit", $cols);
        $upd->run(DB_INSERT);
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM stock WHERE stkid='{$stkid}'";
    $Ri = db_exec($Sl) or errDie("Unable to get stock.");
    $data = pg_fetch_array($Ri);
    $date = date("Y-m-d");
    db_conn('audit');
    $Sl = "SELECT * FROM closedprd ORDER BY id";
    $Ri = db_exec($Sl);
    while ($pd = pg_fetch_array($Ri)) {
        db_conn($pd['prdnum']);
        $Sl = "\n\t\t\tINSERT INTO stkledger (\n\t\t\t\tstkid, stkcod, stkdes, trantype, edate, qty, \n\t\t\t\tcsamt, balance, bqty, details, div, yrdb\n\t\t\t) VALUES (\n\t\t\t\t'{$data['stkid']}', '{$data['stkcod']}', '{$data['stkdes']}', 'bal', '{$date}', '{$data['units']}', \n\t\t\t\t'{$data['csamt']}', '{$data['csamt']}', '{$data['units']}', 'Balance', '" . USER_DIV . "', '" . YR_DB . "'\n\t\t\t)";
        $Ro = db_exec($Sl);
    }
    # deal with logo image
    global $_FILES;
    if ($change_image == "yes") {
        if (empty($_FILES["image"])) {
            return "<li class='err'>Please select an image to upload from your hard drive.</li>";
        }
        if (is_uploaded_file($_FILES["image"]["tmp_name"])) {
            # Check file ext
            if (preg_match("/(image\\/jpeg|image\\/png|image\\/gif)/", $_FILES["image"]["type"], $extension)) {
                $type = $_FILES["image"]["type"];
                // open file in "read, binary" mode
                $img = "";
                $file = fopen($_FILES['image']['tmp_name'], "rb");
                while (!feof($file)) {
                    // fread is binary safe
                    $img .= fread($file, 1024);
                }
                fclose($file);
                # base 64 encoding
                $img = base64_encode($img);
                db_connect();
                $Sl = "INSERT INTO stkimgs (stkid, image, imagetype) VALUES ('{$data['stkid']}','{$img}','{$type}')";
                $Ry = db_exec($Sl) or errDie("Unable to upload company logo Image to DB.", SELF);
                # to show IMG
                //$logoimg = "<br><img src='compinfo/getimg.php' width=230 height=47><br><br>";
                //$logo = "compinfo/getimg.php";
            } else {
                return "<li class='err'>Please note that we only accept images of the types PNG,GIF and JPEG.</li>";
            }
        } else {
            return "Unable to upload file, Please check file permissions.";
        }
    }
    // Layout
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t<tr>\n\t\t\t\t<th>New Stock added to database</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>New Stock, {$stkdes} ({$stkcod}) has been successfully added to Cubit.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table border='0' cellpadding='2' cellspacing='1'>\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='stock-add.php'>Add Stock</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='stock-view.php'>View Stock</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t</tr>\n\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;
}
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($out, "float", 1, 40, "Invalid out amount.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 40, "Invalid amount.");
    $v->isOk($setamt, "float", 1, 40, "Invalid Settlement Amount.");
    $v->isOk($setvat, "string", 1, 10, "Invalid Settlement VAT Option.");
    $v->isOk($setvatcode, "string", 1, 40, "Invalid Settlement VAT code");
    $v->isOk($cusid, "num", 1, 40, "Invalid customer number.");
    $v->isOk($out1, "float", 0, 40, "Invalid paid amount(current).");
    $v->isOk($out2, "float", 0, 40, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 40, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 40, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 40, "Invalid paid amount(120).");
    $v->isOk($overpay, "float", 1, 20, "Invalid Overpay Amount.");
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No.");
            $v->isOk($paidamt[$key], "float", 1, 40, "Invalid amount to be paid.");
            $v->isOk($stock_setamt[$key], "float", 1, 40, "Invalid Settlement Discount Amount");
        }
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . confirm($_POST);
    }
    /* get bank account id of cash on hand account IF this entry is cash */
    if (($bank_acc = getbankaccid($bankid)) === false or $bankid == "0") {
        //old function didnt check if cash is selected ... if(($bank_acc = getbankaccid($bankid)) === false) {
        $sql = "SELECT accid FROM core.accounts WHERE accname='Cash on Hand'";
        $rslt = db_exec($sql);
        if (pg_num_rows($rslt) < 1) {
            if ($bankid == 0) {
                return "There is no 'Cash on Hand' account, there was one, but\n\t\t\t\t\t**s not there now, you must have deleted it, if you want\n\t\t\t\t\tto use cash functionality please create a 'Cash on Hand' account.";
            } else {
                return "Invalid bank acc.";
            }
        }
        $bank_acc = pg_fetch_result($rslt, 0);
    }
    $cus = qryCustomer($cusid, "cusnum, deptid, cusname, surname");
    $dept = qryDepartment($cus["deptid"], "debtacc");
    $refnum = getrefnum();
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # date format
    $sdate = explode("-", $date);
    $_SESSION["global_day"] = $sdate[2];
    $_SESSION["global_month"] = $sdate[1];
    $_SESSION["global_year"] = $sdate[0];
    //	$sdate = $sdate[2]."-".$sdate[1]."-".$sdate[0];
    $sdate = "{$date_year}-{$date_month}-{$date_day}";
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    //	$accdate = "$date_year-$date_month-$date_day";
    /* Paid invoices */
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    $rages = "";
    $setamts = "";
    #get settlement accid
    $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Debtors Settlement Discount'";
    $run_setacc = db_exec($get_setacc) or errDie("Unable to get settlement account information");
    $setaccid = pg_fetch_result($run_setacc, 0, 0);
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    $amt += $overpay;
    /* OPTION 3 : ALLOCATE TO EACH INVOICE (confirm) */
    if ($all == 2) {
        $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt}'::numeric(16,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                # some logic ...
                # because the customer account should be 0 when paid fully, we need
                # to also deduct the settlement amount ...
                $paidamt[$key] = $paidamt[$key] + $stock_setamt[$key];
                # with the amount added to the paid amount, we tract it using a new
                # seperate setamt db column
                if (!isset($itype[$key]) && !isset($ptype[$key])) {
                    $sql = "SELECT prd,invnum,odate FROM cubit.invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.invoices\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2))\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2))\n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, date, type, div, allocation_date, docref, \n\t\t\t\t\t\t\tallocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "', \n\t\t\t\t\t\t\t'{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}', '{$reference}', \n\t\t\t\t\t\t\t'" . abs($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, \n\t\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', \n\t\t\t\t\t\t\t\t'{$sdate}', 'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    #deduct setamt for records ...
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$key] - $stock_setamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    if ($inv['prd'] == "0") {
                        $inv['prd'] = PRD_DB;
                    }
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                } elseif (!isset($ptype[$key])) {
                    $sql = "\n\t\t\t\t\t\tSELECT prd,invnum,descrip,age,odate \n\t\t\t\t\t\tFROM cubit.nons_invoices \n\t\t\t\t\t\tWHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce the invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.nons_invoices \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    if (!isset($inv['odate']) or strlen($inv['odate']) < 1) {
                        $inv['odate'] = $sdate;
                    }
                    // add payment to statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, \n\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "', \n\t\t\t\t\t\t\t'{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', \n\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, \n\t\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', \n\t\t\t\t\t\t\t\t'{$sdate}', 'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                    db_connect();
                    //recordCT($paidamt[$key], $cus['cusnum'],$inv['age'],$accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                } else {
                    /* pos invoices */
                    $sqls = array();
                    for ($i = 1; $i <= 12; ++$i) {
                        $sqls[] = "\n\t\t\t\t\t\t\tSELECT '{$i}' AS prd,invid,invnum,odate \n\t\t\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\tWHERE invid='{$invids[$key]}' AND div='" . USER_DIV . "'";
                    }
                    $sql = implode(" UNION ", $sqls);
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce the invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE \"{$inv['prd']}\".pinvoices \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    // add payment to statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\ttype, div, \n\t\t\t\t\t\t\tallocation_date, docref, allocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($paidamt[$key] - $stock_setamt[$key]) * -1 . "', '{$sdate}', \n\t\t\t\t\t\t\t'Payment for POS Invoice No. {$inv['invnum']}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$inv['odate']}', '{$reference}', '" . abs(($paidamt[$key] - $stock_setamt[$key]) * -1) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\t\tamount, date, \n\t\t\t\t\t\t\t\ttype, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t\t'" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', '{$sdate}', \n\t\t\t\t\t\t\t\t'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for POS Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                    //recordCT($paidamt[$key], $cus['cusnum'],"0",$accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                }
            }
        }
        if (open()) {
            db_conn('cubit');
            $Sl = "SELECT * FROM cubit.open_stmnt WHERE balance>0 AND cusnum='{$cusid}' ORDER BY date";
            $Ri = db_exec($Sl) or errDie("Unable to get open items.");
            //$open_out=$out;
            $ox = "";
            $i = 0;
            while ($od = pg_fetch_array($Ri)) {
                $oid = $od['id'];
                if (!isset($open_amount[$oid]) || $open_amount[$oid] == 0) {
                    continue;
                }
                $ox .= "\n\t\t\t\t\t<input type='hidden' size='20' name='open[{$oid}]' value='{$oid}'>\n\t\t\t\t\t<input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t</tr>";
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$open_amount[$oid]} ::numeric(16,2)) \n\t\t\t\t\tWHERE id = '{$oid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                // record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date, docref, allocation_balance\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cus['cusnum']}', '0', '" . -$open_amount[$oid] . "', '{$sdate}', \n\t\t\t\t\t\t'Payment received', '" . USER_DIV . "', '{$accdate}', '{$reference}', '" . abs($open_amount[$oid]) . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank_acc, $sdate, 0, "Payment received", $open_amount[$oid], "c");
                recordCT($open_amount[$oid], $cus['cusnum'], 0, $accdate);
            }
        }
        // record the payment record
        $cols = grp(m("bankid", $bankid), m("trantype", "deposit"), m("date", $sdate), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheqnum), m("amount", $amt), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference), m("div", USER_DIV));
        $dbobj = new dbUpdate("cashbook", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        $cashbook_id = pglib_lastid("cashbook", "cashid");
        writetrans($bank_acc, $dept['debtacc'], $accdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
    }
    /* start moving invoices */
    // move invoices that are fully paid
    $sql = "SELECT * FROM cubit.invoices WHERE balance='0' AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    while ($x = pg_fetch_array($invbRslt)) {
        if (($prd = $x['prd']) == "0") {
            $prd = PRD_DB;
        }
        // move invoice
        $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
        $dbobj = new dbUpdate("invoices", $prd, $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        // record movement
        $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
        $dbobj->setTable("movinv", "cubit");
        $dbobj->setOpt($cols);
        $dbobj->run();
        $dbobj->free();
        // move invoice items
        $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
        $inv_items->run();
        while ($xi = $inv_items->fetch_array()) {
            $xi['vatcode'] += 0;
            $xi['account'] += 0;
            $xi['del'] += 0;
            $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
            $dbobj->setTable("inv_items", $prd);
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
        }
        /* remove invoice from cubit schema */
        $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
        $dbobj->run();
        $dbobj->setTable("inv_items", "cubit");
        $dbobj->run();
    }
    #do journal for the settlement discount here ... now ...
    if ($setamt > 0) {
        db_conn('core');
        #calculate the settlement vat ... and amt
        if (isset($setvat) and $setvat == 'inc') {
            db_connect();
            $get_vcode = "SELECT * FROM vatcodes WHERE id = '{$setvatcode}' LIMIT 1";
            $run_vcode = db_exec($get_vcode) or errDie("Unable to get vatcode informtion.");
            if (pg_numrows($run_vcode) < 1) {
                return "<li class='err'>Settlement Discount VAT Code Not Set.</li>";
            }
            $vd = pg_fetch_array($run_vcode);
            #vat inc ... recalculate the amts
            $setvatamt = sprint($setamt * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
            $setamt = sprint($setamt - $setvatamt);
            #process the vat amt ...
            writetrans($vatacc, $dept['debtacc'], $accdate, $refnum, $setvatamt, "VAT Received on Settlement Discount (Ref.{$refnum}) for Customer : {$cus['cusname']} {$cus['surname']}");
            vatr($vd['id'], $accdate, "OUTPUT", $vd['code'], $refnum, "VAT for Settlement Discount (Ref.{$refnum}) for Customer : {$cus['cusname']} {$cus['surname']}", ($setamt + $setvatamt) * -1, $setvatamt * -1);
        } else {
            #no vat for set amt ... do nothing
            $setvatamt = 0;
        }
        custledger($cus['cusnum'], $setaccid, $accdate, $refnum, "Settlement Discount (Ref.{$refnum})", $setamt + $setvatamt, "c");
        writetrans($setaccid, $dept['debtacc'], $accdate, $refnum, $setamt, "Settlement Discount (Ref.{$refnum}) For {$cus['cusname']} {$cus['surname']}");
        db_connect();
        #record this paid settlement discount for reporting ...
        $settl_sql = "\n\t\t\tINSERT INTO settlement_cus (\n\t\t\t\tcustomer, amt, setamt, setvatamt, setvat, setvatcode, tdate, sdate, refnum\n\t\t\t) VALUES (\n\t\t\t\t'{$cus['cusnum']}', '{$amt}', '{$setamt}', '{$setvatamt}', '{$setvat}', '{$setvatcode}', '{$accdate}', 'now', '{$refnum}'\n\t\t\t)";
        $run_settl = db_exec($settl_sql) or errDie("Unable to get debtor settlement information.");
    }
    //	$overpay = sprint ($amt - array_sum($paidamt));
    if (!isset($overpay) or $overpay < 0) {
        $overpay = 0.0;
    }
    if ($overpay > 0) {
        recordCT($overpay, $cus['cusnum'], 0, $accdate);
        $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$overpay), m("date", $sdate), m("type", "Payment Received (Receipt " . pglib_lastid("cashbook", "cashid") . ")"), m("div", USER_DIV), m("allocation_date", $accdate), m("docref", $reference));
        $dbobj = new dbUpdate("stmnt", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        custledger($cus['cusnum'], $bank_acc, $sdate, "PAYMENT", "Payment received.", $overpay, "c");
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // status report
    //	$write = "
    //				<table ".TMPL_tblDflts." width='100%'>
    //					<tr>
    //						<th>Bank Receipt</th>
    //					</tr>
    //					<tr class='".bg_class()."'>
    //						<td>Bank Receipt added to cash book.</td>
    //					</tr>
    //				</table>
    //			";
    //
    //	$OUTPUT = "<center>
    //        <table width='90%'>
    //        <tr valign='top'>
    //        	<td width='50%'>$write</td>
    //	        <td align='center'>"
    //				.mkQuickLinks(
    //					ql("bank-pay-add.php", "Add Bank Payment"),
    //					ql("bank-recpt-add.php", "Add Bank Receipt"),
    //					ql("bank-recpt-inv.php", "Add Customer Payment"),
    //					ql("cashbook-view.php", "View Cash Book")
    //				)."
    //			</td>
    //		</tr>
    //		</table>";
    //	return $OUTPUT;
    if (isset($print_recpt) and $print_recpt == "yes") {
        $showreceipt = "printer ('bank/bank-recpt-inv-print.php?recid={$cashbook_id}');";
    } else {
        $showreceipt = "";
    }
    return "\n\t\t<script>\n\t\t\tmove ('../customers-view.php?offset=0&fval=&filter=surname&nozerobal=yes');\n\t\t\t{$showreceipt}\n\t\t</script>";
}
function deny()
{
    extract($_REQUEST);
    /* order info */
    $qry = new dbSelect("recvpurch", "trh", grp(m("where", wgrp(m("id", $id)))));
    $qry->run();
    if ($qry->num_rows() <= 0) {
        invalid_use("<li class='err'>Invalid Sales Order Id (TRHAPP).</li>");
    }
    $soi = $qry->fetch_array();
    /* set approve status */
    $cols = grp(m("approved", "d"));
    $upd = new dbUpdate("recvpurch", "trh", $cols, "id='{$id}'");
    $upd->run(DB_UPDATE);
    /* get customer trh config */
    $keyinfo = trhKeyCust($soi["custid"]);
    $email = $keyinfo["email"];
    /* send trh response message */
    $purinfo = array("purid" => $soi["purid"], "status" => "d");
    $ret = send_trhmsg("cust", $soi["custid"], $email, "rsppur", $purinfo);
    $OUT = listorders("<li class='err'>Successfully denied sales order.</li>");
    return $OUT;
}
function save_sal($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    # Limit field lengths as per database settings
    $v->isOk($empnum, "string", 0, 20, "Invalid empnum.");
    $v->isOk($saltyp, "string", 1, 2, "Invalid salary type.");
    $v->isOk($paytype, "string", 1, 15, "Invalid pay type.");
    if (isset($allowances)) {
        foreach ($allowances as $key => $value) {
            $v->isOk($allowances[$key], "float", 0, 11, "Invalid allowance amount " . ($key + 1) . ".");
        }
    }
    if (isset($deductid)) {
        foreach ($deductid as $key => $value) {
            $v->isOk($deductid[$key], "num", 1, 9, "Invalid deductions ID.");
        }
    }
    if (isset($deductions)) {
        foreach ($deductions as $key => $value) {
            $v->isOk($deductions[$key], "float", 0, 11, "Invalid deduction amount" . ($key + 1) . ".");
        }
    }
    if (isset($allowid)) {
        foreach ($allowid as $key => $value) {
            $v->isOk($allowid[$key], "num", 1, 9, "Invalid allowance ID.");
        }
    }
    if (isset($allowtax)) {
        foreach ($allowtax as $key => $value) {
            $v->isOk($allowtax[$key], "string", 1, 13, "Invalid allowance tax option" . ($key + 1) . ".");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>{$e['msg']}</li>";
        }
        return "<li class='err'>{$confirmCust}</li>";
    }
    switch ($saltyp) {
        case "m":
            $sal_divisor = 12;
            break;
        case "f":
            $sal_divisor = 26;
            break;
        case "w":
            $sal_divisor = 52;
            break;
        case "h":
            $sal_divisor = 52 * $hpweek;
            break;
    }
    $basic_sal = sprint($basic_sal_annum / $sal_divisor);
    db_connect();
    $sql = "\n\t\tUPDATE employees \n\t\tSET basic_sal='{$basic_sal}', paytype='{$paytype}', payprd_day='{$payprd_day}', basic_sal_annum='{$basic_sal_annum}', \n\t\t\tsal_bonus='{$sal_bonus}', sal_bonus_month='{$sal_bonus_month}', all_travel='{$all_travel}', comp_uif='{$comp_uif}', \n\t\t\tcomp_sdl='{$comp_sdl}', emp_uif='{$emp_uif}', comp_pension='{$comp_pension}', emp_pension='{$emp_pension}', \n\t\t\tcomp_ret='{$comp_ret}', emp_ret='{$emp_ret}', comp_medical='{$comp_medical}', emp_medical='{$emp_medical}', \n\t\t\temp_meddeps='{$emp_meddeps}', comp_provident='{$comp_provident}', emp_provident='{$emp_provident}', \n\t\t\tcomp_other='{$comp_other}', emp_other='{$emp_other}', payprd='{$payprd}', saltyp='{$saltyp}', \n\t\t\tfringe_car1='{$fringe_car1}', fringe_car1_contrib='{$fringe_car1_contrib}', fringe_car1_fuel='{$fringe_car1_fuel}', \n\t\t\tfringe_car1_service='{$fringe_car1_service}', fringe_car2='{$fringe_car2}', \n\t\t\tfringe_car2_contrib='{$fringe_car2_contrib}', fringe_car2_fuel='{$fringe_car2_fuel}', \n\t\t\tfringe_car2_service='{$fringe_car2_service}', flag=NULL \n\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
    $nwEmpRslt = db_exec($sql) or errDie("Unable to update employee information.");
    if (isset($allowid)) {
        # Remove old details
        $sql = "DELETE FROM empallow WHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
        $allowRslt = db_exec($sql);
        # write Allowances to db
        foreach ($allowid as $i => $id) {
            if (empty($allowances[$i]) || $allowances[$i] == 0) {
                continue;
            }
            # Insert new records
            $allowances[$i] += 0;
            $allowances[$i] = sprint($allowances[$i]);
            $sql = "\n\t\t\t\tINSERT INTO empallow (\n\t\t\t\t\tallowid, empnum, type, amount, accid, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$id}', '{$empnum}', '{$allowtype[$i]}', '{$allowances[$i]}', '{$allowaccid[$i]}', '" . USER_DIV . "'\n\t\t\t\t)";
            $allowRslt = db_exec($sql) or errDie("Unable to process Employee allowances in database.");
        }
    }
    if (isset($subsname)) {
        $inssub = new dbUpdate("emp_subsistence", "cubit");
        foreach ($subsname as $sid => $sn) {
            $cols = grp(m("subid", $sid), m("empnum", $empnum), m("amount", $subsamt[$sid]), m("days", $subsdays[$sid]), m("accid", $subsacc[$sid]));
            $inssub->setOpt($cols, wgrp(m("subid", $sid), m("empnum", $empnum)));
            $inssub->run(DB_REPLACE);
        }
    }
    if (isset($deductid)) {
        # Remove old records
        $sql = "DELETE FROM empdeduct WHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
        $deductRslt = db_exec($sql);
        # write Deductions to db
        foreach ($deductid as $i => $id) {
            if (isset($ltsal_checked[$i])) {
                $ltsal = "y";
            } else {
                $ltsal = "n";
            }
            # Insert new records
            if (empty($deductions[$i]) || $deductions[$i] == 0) {
                continue;
            }
            if (empty($comp_deductions[$i])) {
                $comp_deductions[$i] = 0;
            }
            $deductions[$i] += 0;
            $deductions[$i] = sprint($deductions[$i]);
            $comp_deductions[$i] += 0;
            $sql = "\n\t\t\t\tINSERT INTO empdeduct (\n\t\t\t\t\tdedid, empnum, amount, employer_amount, div, type, \n\t\t\t\t\temployer_type, grosdeduct, accid\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$id}', '{$empnum}', '{$deductions[$i]}', '{$comp_deductions[$i]}', '" . USER_DIV . "','{$deducttype[$i]}', \n\t\t\t\t\t'{$deducttype[$i]}', '{$ltsal}', '{$deductaccid[$i]}'\n\t\t\t\t)";
            $deductRslt = db_exec($sql) or errDie("Unable to process Employee deductions in database.");
        }
    }
    if (isset($fringebens)) {
        $sql = "DELETE FROM empfringe WHERE empnum='{$empnum}' AND div='" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Error updating fringe benefits (DEL).");
        foreach ($fringeid as $i => $id) {
            if (empty($fringebens[$i]) || $fringebens[$i] == 0) {
                continue;
            }
            $fringebens[$i] += 0;
            $sql = "\n\t\t\t\tINSERT INTO empfringe (\n\t\t\t\t\tfringeid, empnum, amount, type, accid, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$id}', '{$empnum}', '{$fringebens[$i]}', '{$fringetype[$i]}', '{$fringeexpacc[$i]}', '" . USER_DIV . "'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Error updating fringe benefits (INS#{$id}).");
        }
    }
    //				<script>
    //					parent.opener.location.reload();
    //				</script>
    $display = "\n\t\t<script>\n\t\t\tparent.opener.document.form1.submit();\n\t\t\twindow.close();\n\t\t</script>";
    return $display;
}
function checknum()
{
    extract($_REQUEST);
    require_lib("validate");
    $v = new Validate();
    $v->isOk($topacc, "num", 4, 4, "Invalid Main Part.");
    $v->isOk($accnum, "num", 3, 3, "Invalid Sub Part.");
    /* is account number valid */
    if ($v->isError()) {
        $e = $v->getErrors();
        if (count($e) == 2) {
            $err = "Invalid account number.";
        } else {
            $err = $e[0]["msg"];
        }
    } else {
        /* does account number exist */
        $qry = new dbSelect("accounts", "core", grp(m("cols", "accname"), m("where", "topacc='{$topacc}' AND accnum='{$accnum}'"), m("limit", "1")));
        $qry->run();
        if (!isset($rslt)) {
            $rslt = array();
        }
        if ($qry->num_rows($rslt) > 0) {
            $accname = $qry->fetch_result();
            $err = "Account number in use: {$accname}.";
        } else {
            if ($accnum != "000") {
                $qry->setOpt(grp(m("where", "topacc='{$topacc}'")));
                $qry->run();
                if ($qry->num_rows() <= 0) {
                    $err = "Main Account doesn't exist.";
                }
            }
        }
    }
    if (!isset($err)) {
        $err = "<strong>Account number valid.</strong>";
    } else {
        $err = "<li class='err'>{$err}</li>";
    }
    return $err;
}
function update($_POST)
{
    extract($_POST);
    // Validate
    require_lib("validate");
    $v = new validate();
    if (isset($accid) && isset($category)) {
        $v->isOk($accid, "num", 1, 9, "Invalid account selection.");
        $v->isOk($category, "string", 1, 6, "Invalid category selection.");
    }
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return slct($confirm);
    }
    $key = strtolower($key);
    if ($key == "add" || $key == "select account") {
        // Make sure the account has not been added already
        db_conn("cubit");
        $sql = "SELECT * FROM saved_cf_accounts WHERE accid='{$accid}'";
        $cfacc_rslt = db_exec($sql) or errDie("Unable to retrieve account from the account list.");
        if (!pg_num_rows($cfacc_rslt)) {
            db_conn("cubit");
            $sql = "INSERT INTO saved_cf_accounts (accid, category) VALUES ('{$accid}', '{$category}')";
            $cfacc_rslt = db_exec($sql) or errDie("Unable to save account to the accounts list.");
        }
    }
    if ($key == "remove selected") {
        if (!isset($rem)) {
            $rem = array();
        }
        foreach ($rem as $id) {
            db_conn("cubit");
            $sql = "DELETE FROM saved_cf_accounts WHERE accid='{$id}'";
            $cfacc_rslt = db_exec($sql) or errDie("Unable to remove selected account from the accounts list.");
        }
    }
    if ($key == "default") {
        list($accid) = qryAccountsName("Depreciation", "accid");
        db_conn("cubit");
        $cols = grp(m("accid", $accid), m("category", "nciis"));
        $qry = new dbUpdate("saved_cf_accounts", "cubit", $cols);
        $qry->run(DB_INSERT);
        // add balance sheet items to list
        $qry = new dbQuery(DB_SQL, "INSERT INTO cubit.saved_cf_accounts (accid, category)\n\t\t\tSELECT accid, 'ciaal' FROM core.accounts WHERE catid='B10'");
        $qry->run();
        /*
        // Inventory
        db_conn("core");
        $sql = "SELECT accid FROM accounts WHERE accname='Inventory'";
        $rslt = db_exec($sql) or errDie("Unable to retrieve the inventory account.");
        $accid = pg_fetch_result($rslt, 0);
        
        db_conn("cubit");
        $sql = "INSERT INTO saved_cf_accounts (accid, category) VALUES ('$accid', 'ciaal')";
        $rslt = db_exec($sql) or errDie("Unable to add the inventory account.");
        
        // Accounts Receivable
        db_conn("core");
        $sql = "SELECT accid FROM accounts WHERE accname='Customer Control Account'";
        $rslt = db_exec($sql) or errDie("Unable to retrieve the accounts receivable account.");
        $accid = pg_fetch_result($rslt, 0);
        
        db_conn("cubit");
        $sql = "INSERT INTO saved_cf_accounts (accid, category) VALUES ('$accid', 'ciaal')";
        $rslt = db_exec($sql) or errDie("Unable to add the accounts receivable account.");
        */
    }
    return slct();
}
function customize($_POST)
{
    extract($_POST);
    $fields["naccount"] = "";
    $fields["last_year"] = "checked";
    $fields["budget"] = "checked";
    $fields["month_from"] = (int) date("m");
    $fields["month_to"] = (int) date("m");
    $fields["heading_1"] = COMP_NAME;
    $fields["heading_2"] = date("d/m/Y");
    $fields["heading_3"] = "Trial Balance";
    $fields["heading_4"] = "Prepared by: " . USER_NAME;
    $fields["viewyear"] = "core";
    $fields["zero_balance"] = "";
    $fields["debit_credit"] = "";
    foreach ($fields as $var_name => $value) {
        if (!isset(${$var_name})) {
            ${$var_name} = $value;
        }
    }
    $qry = new dbSelect("year", "core", grp(m("where", "closed='y'"), m("order", "yrname ASC")));
    $qry->run();
    if (PRD_STATE == "py") {
        $curyear = PYR_NAME;
    } else {
        $curyear = YR_NAME;
    }
    $year_sel = "\n\t\t<select name='viewyear'>\n\t\t\t<option value='core'>" . $curyear . " (Current)</option>";
    while ($row = $qry->fetch_array()) {
        $sel = fsel($viewyear == $row["yrdb"]);
        $year_sel .= "<option {$sel} value='{$row['yrdb']}'>{$row['yrname']}</option>";
    }
    $year_sel .= "</select>";
    // Should we display the last year field
    if (substr(YR_DB, 2) - 1 > 0) {
        if (isset($last_year) && $last_year) {
            $ch = "checked='t'";
        } else {
            $ch = "";
        }
        $last_year_out = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Last Year</td>\n\t\t\t\t<td align='center'><input type='checkbox' name='last_year' value='checked' {$ch}></td>\n\t\t\t</tr>";
    } else {
        $last_year_out = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Last Year</td>\n\t\t\t\t<td align='center'>No prior years found.</td>\n\t\t\t</tr>";
    }
    /*$months_from = "<select name='month_from'>";
    	// Retrive month names
    	for ($i = 1; $i <= 12; $i++) {
    		if ($month_from == $i) {
    			$selected = "selected";
    		} else {
    			$selected = "";
    		}
    		$months_from .= "<option value='$i' $selected>".getMonthName($i)."</option>";
    	}
    	$months_from .= "</select>";*/
    $months_to = finMonList("month_to", $month_to, true);
    /*// Retrieve list of accounts for the dropdowns
    	db_conn("core");
    	$sql = "SELECT * FROM trial_bal WHERE div='".USER_DIV."' ORDER BY topacc, accnum ASC";
    	$tb_rslt = db_exec($sql) or errDie("Unable to retrieve trial balance accounts from Cubit.");
    
    	$accounts = array();
    	while ($tb_data = pg_fetch_array($tb_rslt)) {
    		$accounts[$tb_data["accid"]] = "$tb_data[topacc]/$tb_data[accnum] $tb_data[accname]";
    	}
    
    	$naccount_out = "
    	<tr class='bg-odd'>
    		<td align=center><select name=naccount style='width: 240px'>
    		<option value='0'>Please select</option>";
    
    	foreach ($accounts as $accid=>$value) {
    		if ($naccount == $accid) {
    			$selected = "selected";
    		} else {
    			$selected = "";
    		}
    
    		$naccount_out .= "<option value='$accid' $selected>$value</option>";
    	}
    
    	$naccount_out .= "</select></td>
    		<td><input type=submit name='key' value='Add'></td>
    	</tr>";*/
    // Retrieved the saved trial balance layout from Cubit
    db_conn("cubit");
    $sql = "SELECT * FROM saved_tb_accounts";
    $stbacc_rslt = db_exec($sql) or errDie("Unable to retrieve saved trial balance accounts from Cubit.");
    if (pg_num_rows($stbacc_rslt) == 0) {
        $accounts_out = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>No accounts have been selected, ALL accounts will be displayed.</td>\n\t\t\t</tr>";
    } else {
        $accounts_out = "";
    }
    $i = 0;
    while ($stbacc_data = pg_fetch_array($stbacc_rslt)) {
        $i++;
        // Was anything in the remove list selected
        if (isset($rem[$stbacc_data["id"]])) {
            $checked = "checked";
        } else {
            $checked = "";
        }
        $accounts_out .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$stbacc_data['topacc']}/{$stbacc_data['accnum']}</td>\n\t\t\t\t<td>{$stbacc_data['accname']}</td>\n\t\t\t\t<td><input type='checkbox' name='rem[{$stbacc_data['id']}]' value='{$stbacc_data['id']}' {$checked}></td>\n\t\t\t\t<td><a href='#' onclick='popupSized(\"" . SELF . "?key=note_view&accid={$stbacc_data['accid']}\", 'note{$stbacc_data['accid']}', 480, 800, '');'>Note</a></td>\n\t\t\t</tr>";
    }
    // Layout
    $OUTPUT = "\n\t\t<h3>Trial Balance</h3>\n\t\t<form method='POST' action='" . SELF . "'>\n\t\t\t<input type='hidden' name='key' value='display'>\n\t\t\t<input type='hidden' name='acc_view' value='sel'>\n\t\t\t<input type='hidden' name='customized' value='true'>\n\t\t<table border='0' cellpadding='0' cellspacing='0'>\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'><h3>Customise</h3></th>\n\t\t\t</tr>\n\t\t\t<tr><td valign=top>\n\t\t\t<table " . TMPL_tblDflts . " style='width: 300px; margin: 0px;'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>Display</th>\n\t\t\t\t</tr>\n\t\t\t\t{$last_year_out}\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Annual Budget</td>\n\t\t\t\t\t<td align=center><input type=checkbox name=budget value='checked' {$budget}></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Zero Balances</td>\n\t\t\t\t\t<td align='center'><input type='checkbox' name='zero_balance' value='checked' {$zero_balance}></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>List Debit & Credit</td>\n\t\t\t\t\t<td align='center'><input type='checkbox' name='debit_credit' {$debit_credit}></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Year</td>\n\t\t\t\t\t<td align='center'>{$year_sel}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Month</td>\n\t\t\t\t\t<td align=center nowrap>{$months_to}</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<!--<table " . TMPL_tblDflts . " style='width: 300px; margin: 0px;'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>Add Account</th>\n\t\t\t\t</tr>\n\t\t\t\t\$naccount_out\n\t\t\t</table>//-->\n\t\t\t<table " . TMPL_tblDflts . " style='width: 300px; margin: 0px;'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>Headings</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Heading 1</td>\n\t\t\t\t\t<td><input type='text' name='heading_1' value='{$heading_1}' style='width: 100%'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Heading 2</td>\n\t\t\t\t\t<td><input type='text' name='heading_2' value='{$heading_2}' style='width: 100%'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Heading 3</td>\n\t\t\t\t\t<td><input type='text' name='heading_3' value='{$heading_3}' style='width: 100%'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td width='0%'>Heading 4</td>\n\t\t\t\t\t<td><input type='text' name='heading_4' value='{$heading_4}' style='width: 100%'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='3'><input type='submit' value='Display &raquo' style='width:100%; font-weight: bold;'></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td><td valign=top>\n\t\t\t<!--<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='4'>Accounts</th>\n\t\t\t\t</tr>\n\t\t\t\t{$accounts_out}\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='4' align='center'><input type='submit' name='key' value='Remove Selected'></td>\n\t\t\t\t</tr>\n\t\t\t</table>//-->\n\t\t</table>\n\t\t</form>";
    return $OUTPUT;
}