function edit()
{
    extract($_GET);
    if (isset($id)) {
        $subinfo = new dbSelect("subsistence", "cubit", array("where" => wgrp(m("id", "{$id}"))));
        $subinfo->run();
        if ($subinfo->num_rows() > 0) {
            extract($subinfo->fetch_array(), EXTR_SKIP);
        }
    }
    $fields = array("name" => "", "in_republic" => "yes", "meals" => "yes", "accid" => false);
    foreach ($fields as $fname => $val) {
        if (!isset(${$fname})) {
            ${$fname} = $val;
        }
    }
    /* no accid is set, use salaries and wages */
    if ($accid === false) {
        $swacc = qryAccountsName("Salaries and Wages", "accid");
        $accid = $swacc["accid"];
    }
    $bg = 0;
    $OUT = "\n\t<h3>Define Subsistence Allowance</h3>\n\t<li class='err'>The selection on this window will create a Subsistence Allowance\n\twith the specified properties. To assign this subsistence to an employee you\n\twill need to edit the employee, and on the 'Calculate Salary' window\n\tfill out the employee specific information involving the Subsistence Allowance.</li>\n\t<form method='get' action='" . SELF . "'>\n\t<input type='hidden' name='key' value='write'>\n\t" . (isset($id) ? "<input type='hidden' name='id' value='{$id}'" : "") . "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th colspan='2'>Details</th>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Name:</td>\n\t\t<td><input type='text' name='name' value='{$name}'></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>In Republic (ZA):</td>\n\t\t<td>\n\t\t\t<select name='in_republic'>\n\t\t\t\t<option value='yes' " . ($in_republic != "no" ? "selected" : "") . ">Yes</option>\n\t\t\t\t<option value='no' " . ($in_republic == "no" ? "selected" : "") . ">No</option>\n\t\t\t</select>\n\t\t</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Employee pays for own Meals:</td>\n\t\t<td>\n\t\t\t<select name='meals'>\n\t\t\t\t<option value='yes' " . ($meals != "no" ? "selected" : "") . ">Yes</option>\n\t\t\t\t<option value='no' " . ($meals == "no" ? "selected" : "") . ">No</option>\n\t\t\t</select>\n\t\t</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Account:</td>\n\t\t<td>" . finAccList("accid", false, $accid) . "</td>\n\t\t<td class='err'>Select an account where the expense must be debited to.</td>\n\t</tr>\n\t<tr>\n\t\t<td colspan='2' align='right'><input type='submit' value='Next'></td>\n\t</tr>\n\t</table>\n\t</form>\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<td>\n\t\t\t<u><b>Subsistence allowance</b></u>\n\t\t\t<p>\n\t\t\tThe income tax provides that there shall not be included in the\n\t\t\ttaxable income of any person, any amount paid or granted by a\n\t\t\tprincipal as a reimbursement of, or as an advance for, the\n\t\t\texpenditure incurred or to be incurred by the employee - where\n\t\t\tthat employee must produce proof to that employer that such\n\t\t\texpenditure was wholly incurred and must account to that employer\n\t\t\tfor that expenditure.\n\t\t\t</p><p>\n\t\t\tFor the purpose of the above provision an employee shall be deemed\n\t\t\tto have actually incurred expenditure:\n\t\t\t<li>Where the employee proves to the Commissioner the amount of\n\t\t\tthe expenses incurred by him in respect of accommodation, meals or\n\t\t\tother incidental costs, the amount so actually incurred but\n\t\t\tlimited to the amount of the allowance or advance paid or granted\n\t\t\tto meet those expenses; or</li>\n\t\t\t<li>For each day or part of a day in the period during which that\n\t\t\temployee is absent from his or her usual place of residence, an\n\t\t\tamount in respect of meals and other incidental costs, or\n\t\t\tincidental costs only, determined by the Minister for the relevant\n\t\t\tyear of assessment by way of notice in The Gazette but limited to\n\t\t\tthe amount of the allowance paid or granted to meet those\n\t\t\texpenses.\n\t\t\t</p><p>\n\t\t\tAccording to the regulations published in The Gazette the\n\t\t\tfollowing amounts will be deemted to have been expended by an\n\t\t\temployee to whom an allowance or advance has been granted or paid:\n\t\t\t<li>Where the accommodation to which that allowance or advance\n\t\t\trelate is the Republic and that allowance or the advance is paid\n\t\t\tor granted to defray Incidental costs only, an amount equal to R93\n\t\t\tper day; or<br />\n\t\t\tThe cost of meals and incidental costs, an amount equal to R303\n\t\t\tper day; or</li>\n\t\t\t<li>Where the accommodation to which that allowance or advance\n\t\t\trelates is outside the Republic and that the allowance or advance\n\t\t\tis paid or granted to defray the cost of meals and incidental\n\t\t\tcosts, an amount equal to U.S. \$215 per day.</li>\n\t\t</td>\n\t</tr>\n\t</table>";
    return $OUT;
}
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()
{
    extract($_REQUEST);
    if ($page_option == "Edit") {
        $sql = "UPDATE cubit.diary_locations SET location='{$location}'\n\t\tWHERE id='{$id}'";
    } else {
        $sql = "INSERT INTO cubit.diary_locations (location) VALUES ('{$location}')";
    }
    db_exec($sql) or errDie("Unable to save location.");
    if (frmupdate_passon()) {
        $newlist = new dbSelect("diary_locations", "cubit");
        $newlist->run();
        $a = array();
        if ($newlist->num_rows() > 0) {
            while ($row = $newlist->fetch_array()) {
                $a[$row["id"]] = "{$row['location']}";
            }
        }
        $js = frmupdate_exec(array($a), true);
    } else {
        $js = "";
    }
    $OUTPUT = "{$js}\n\t<h3>{$page_option} Location</h3>\n\t<table cellpadding='2' cellspacing='0' class='shtable'>\n\t\t<tr>\n\t\t\t<th>Write</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Successfully saved location.</td>\n\t\t</tr>\n\t</table>";
    return $OUTPUT;
}
function edit()
{
    extract($_GET);
    $subinfo = new dbSelect("subsistence", "cubit", array("where" => "div='" . USER_DIV . "'"));
    $subinfo->run();
    $bg = 0;
    $OUT = "\n\t\t<h3>Define Subsistence Allowance</h3>\n\t\t<form method='get' action='" . SELF . "'>\n\t\t\t<input type='hidden' name='key' value='write'>\n\t\t\t" . (isset($id) ? "<input type='hidden' name='id' value='{$id}'" : "") . "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Name</th>\n\t\t\t\t<th>In Republic</th>\n\t\t\t\t<th>Pays for own Meals</th>\n\t\t\t\t<th>Options</th>\n\t\t\t</tr>";
    while ($row = $subinfo->fetch_array()) {
        $OUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$row['name']}</td>\n\t\t\t\t<td>" . ucfirst($row["in_republic"]) . "</td>\n\t\t\t\t<td>" . ucfirst($row["meals"]) . "</td>\n\t\t\t\t<td><a href='subsistence-edit.php?id={$row['id']}'>Edit</a></td>\n\t\t\t</tr>";
    }
    $OUT .= "\n\t\t</table>\n\t\t</form>";
    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 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 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 entersal(&$frm)
{
    /* @var $frm cForm */
    if ($frm->validate("entersal")) {
        return select_emp($frm);
    }
    $frm->setkey("writesal");
    extract($_POST);
    $empi = qryEmployee($empnum);
    $qry = new dbSelect("salpaid", "cubit", grp(m("cols", "month, week"), m("where", "empnum='{$empnum}' AND cyear='" . EMP_YEAR . "'"), m("order", "month, week"), m("group", "month, week")));
    //print $qry->sql;
    $qry->run();
    /* in case we did a correction, we run clean_fields to remove the 
    		previous employee's fields */
    $frm->clean_fields("headers");
    $frm->clean_fields("hrs", true);
    $frm->clean_fields("sal", true);
    $frm->setcell(1, 2);
    $frm->add_layout("\n\t\t<tr>\n\t\t\t<th>Month</th>\n\t\t\t" . ($empi["payprd"] == "m" ? "" : "<th>Week/Day</th>") . "\n\t\t\t<th>Basic Salary Rate<br />for Month</th>\n\t\t\t" . ($empi["saltyp"] != "h" ? "" : "<th>Hours Worked</th>") . "\n\t\t</tr>", false, "headers");
    while ($row = $qry->fetch_array()) {
        $sqry = new dbSelect("salpaid", "cubit", grp(m("where", "empnum='{$empnum}' AND cyear='" . EMP_YEAR . "'\n\t\t\t\t\t\tAND month='{$row['month']}' AND week='{$row['week']}'"), m("order", "true_ids DESC"), m("limit", "1")));
        $sqry->run();
        if ($sqry->num_rows() > 0) {
            $si = $sqry->fetch_array();
            /* hours field option */
            if ($empi["saltyp"] == "h") {
                $hrsopt = "<td>%fldonly</td>";
            } else {
                $hrsopt = "";
            }
            /* show week number */
            if ($empi["payprd"] == "m") {
                $weekdisp = "";
            } else {
                $weekdisp = "<td>{$row['week']}</td>";
            }
            $lay = "\n\t\t\t<tr %bg>\n\t\t\t\t<td>{$row['month']}</td>\n\t\t\t\t{$weekdisp}\n\t\t\t\t<td>%fldonly</td>\n\t\t\t\t{$hrsopt}\n\t\t\t</tr>";
            $frm->add_layout($lay);
            $frm->add_text("", "sal[{$si['id']}]", $si["salrate"], "float", "1:40", array("size" => "7"));
            if ($empi["saltyp"] == "h") {
                $frm->add_text("", "hrs[{$si['id']}]", $si["hours"], "float", "1:40", array("size" => "5"));
            }
        }
    }
    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 slct()
{
    # Select the stock category
    db_connect();
    $cats = "<select name='catid'>";
    $sql = "SELECT catid,cat,catcod FROM stockcat WHERE div = '" . USER_DIV . "' ORDER BY cat ASC";
    $catRslt = db_exec($sql);
    if (pg_numrows($catRslt) < 1) {
        return "<li>There are no stock categories in Cubit.";
    } else {
        while ($cat = pg_fetch_array($catRslt)) {
            $cats .= "<option value='{$cat['catid']}'>({$cat['catcod']}) {$cat['cat']}</option>";
        }
    }
    $cats .= "</select>";
    # Select classification
    $class = "<select name='clasid' style='width: 167'>";
    $sql = "SELECT * FROM stockclass WHERE div = '" . USER_DIV . "' ORDER BY classname ASC";
    $clasRslt = db_exec($sql);
    if (pg_numrows($clasRslt) < 1) {
        return "<li>There are no Classifications in Cubit.</li>";
    } else {
        while ($clas = pg_fetch_array($clasRslt)) {
            $class .= "<option value='{$clas['clasid']}'>{$clas['classname']}</option>";
        }
    }
    $class .= "</select>";
    $wh_rslt = new dbSelect("warehouses", "exten");
    $wh_rslt->run();
    $warehouses = "<select name='whid' style='width: 167'>";
    while ($wh_data = $wh_rslt->fetch_array()) {
        $warehouses .= "<option value='{$wh_data['whid']}'>{$wh_data['whname']}</option>";
    }
    $warehouses .= "</select>";
    /* cut code
    	<input type=hidden name=key value=view>
    	<tr><th colspan=2>Store</th></tr>
    	<tr class='bg-odd'><td align=center colspan=2>$whs</td></tr>
    	<tr><td><br></td></tr>
    	*/
    // Layout
    $view = "\n\t\t<h3>Stock Levels</h3>\n\t\t<table cellpadding='5'>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t\t\t\t<input type='hidden' name='key' value='view'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'>Criteria</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td align='center'>Only show stock below minimun level</td>\n\t\t\t\t\t\t\t<td valign='bottom'><input type='checkbox' name='min' checked></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'>By Category</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td align='center'>{$cats}</td>\n\t\t\t\t\t\t\t<td valign='bottom'><input type='submit' name='cat' value='View'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'>By Classification</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td align='center'>{$class}</td>\n\t\t\t\t\t\t\t<td valign='bottom'><input type='submit' name='class' value='View'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'>By Store</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td align='center'>{$warehouses}</td>\n\t\t\t\t\t\t\t<td valign='bottom'><input type='submit' name='warehouse' value='View' /></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'>All Categories, Classifications and Stores</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td align='center' colspan='2'>\n\t\t\t\t\t\t\t\t<input type='submit' name='all' value='View All'>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</form>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table border=0 cellpadding='2' cellspacing='1' width=15%>\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-report.php'>Stock Reports</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 $view;
}
function enter(&$frm)
{
    if (!isset($_REQUEST["id"])) {
        invalid_use();
    }
    $frm->settitle("Supplier Stock Codes");
    $frm->setmsg("Please enter the stock codes each of your suppliers use for the\n\t\tselected stock item.<br /><br />\n\t\t<li class='err'>To remove an item from supplier, simply leave field blank.</li>");
    $frm->setkey("confirm");
    $frm->add_hidden("id", $_REQUEST["id"], "num");
    $qry = new dbSelect("suppliers", "cubit");
    $qry->run();
    $frm->add_heading("Details");
    while ($si = $qry->fetch_array()) {
        $stkcod = trhSuppStkcod($si["supid"], $_REQUEST["id"]);
        $supdisp = "({$si['supno']}) {$si['supname']}";
        $frm->add_text($supdisp, "stkcod[{$si['supid']}]", $stkcod, "string", "0:50");
    }
    return $frm->getfrm_input();
}
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 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 write()
{
    extract($_REQUEST);
    if ($page_option == "Edit") {
        $sql = "UPDATE cubit.todo_main SET title='{$title}', team_id='{$team_id}'\n\t\tWHERE id='{$id}' AND user_id='" . USER_ID . "'";
    } else {
        $sql = "INSERT INTO cubit.todo_main (title, user_id, team_id)\n\t\tVALUES ('{$title}', '" . USER_ID . "', '{$team_id}')";
    }
    db_exec($sql) or errDie("Unable to save main todo.");
    if (frmupdate_passon()) {
        $newlist = new dbSelect("todo_main", "cubit");
        $newlist->run();
        // are we an admin?
        $sql = "SELECT admin FROM cubit.users WHERE userid='" . USER_ID . "'";
        $admin_rslt = db_exec($sql) or errDie("Unable to check for admin.");
        $admin = pg_fetch_result($admin_rslt, 0);
        $a = array();
        if ($newlist->num_rows() > 0) {
            $a[0] = "[None]";
            while ($row = $newlist->fetch_array()) {
                if (in_team(USER_ID, $row["team_id"])) {
                    $sql = "SELECT * FROM cubit.todo_main WHERE id='{$row['id']}'";
                    $tm_rslt = db_exec($sql) or errDie("Unable to retrieve todo.");
                    $count = pg_num_rows($tm_rslt);
                    $a[$row["id"]] = "{$row['title']} ({$count})";
                } else {
                    continue;
                }
            }
        }
        $js = frmupdate_exec(array($a), true);
    } else {
        $js = "";
    }
    $OUTPUT = "{$js}\n\t<h3>{$page_option} Main Todo</h3>\n\t<table cellpadding='2' cellspacing='0' class='shtable'>\n\t\t<tr>\n\t\t\t<th>Write</th>\n\t\t</tr>\n\t\t<tr class='odd'><td>Successfully saved the main todo.</td></tr>\n\t</table>";
    return $OUTPUT;
}
function errSend()
{
    /* check for valid email settings */
    $settings = new dbSelect("esettings", "cubit");
    $settings->run();
    if ($settings->num_rows() <= 0) {
        r2sListSet("emailsettings");
        header("Location: email-settings.php");
        exit;
    }
    $settings->fetch_array();
    $server = $settings->d["smtp_host"];
    $from = $settings->d["fromname"];
    $reply = $settings->d["reply"];
    /* build the email */
    $data = errData($_GET["id"]);
    $msg = new clsMailMsg();
    $msg->newMessage($from, $reply, "Error Report: {$data['errtime']}", "Error report file attached.");
    $msg->addAttachment("application/octet-stream", "error{$_GET['id']}-{$data['errtime']}.cer", $data["errdata"]);
    $md = $msg->getNewMessage();
    /* send the email */
    /**
     * ok, so lets stop catching errors because if the email sending fails
     * we are just going to go back to "an error has occured"
     */
    disableErrorNet();
    $smtp = new clsSMTPMail();
    $smtp->sendMessages($server, 25, false, false, false, ERRORNET_EMAIL, $md["from"], $md["subject"], $md["body"], $md["headers"]);
    $OUTPUT = "<h3>Error Report</h3>";
    if ($smtp->bool_success !== true) {
        $OUTPUT .= "Error sending report. Please save report and email it\n\t\t\tto <a class='nav' href='mailto: " . ERRORNET_EMAIL . "'>" . ERRORNET_EMAIL . "</a><br />\n\t\t\t<br />\n\t\t\t<input type='button' value='Save Error Report'\n\t\t\t\tonClick='document.location.href=\"" . relpath("geterror.php") . "?id={$_GET['id']}\";' />";
    } else {
        $OUTPUT .= "Successfully sent report. Thank You.";
    }
    return $OUTPUT;
}
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 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;
}
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);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($rec_amount, "num", 1, 5, "Invalid amount of entries.");
    for ($t = 0; $t < $rec_amount; $t++) {
        if (!isset($descript[$t]) or !isset($reference[$t]) or !isset($setamt[$t]) or empty($descript[$t]) or empty($reference[$t]) or empty($setamt[$t])) {
            continue;
        }
        $v->isOk($bankid[$t], "num", 1, 30, "Invalid Bank Account.");
        $v->isOk($date[$t], "date", 1, 14, "Invalid Date.");
        $v->isOk($out[$t], "float", 1, 40, "Invalid out amount.");
        $v->isOk($descript[$t], "string", 0, 255, "Invalid Description.");
        $v->isOk($reference[$t], "string", 0, 50, "Invalid Reference Name/Number.");
        $v->isOk($cheqnum[$t], "num", 0, 30, "Invalid Cheque number.");
        $v->isOk($amt[$t], "float", 1, 40, "Invalid amount.");
        $v->isOk($setamt[$t], "float", 1, 40, "Invalid Settlement amount.");
        $v->isOk($setvat[$t], "string", 1, 10, "Invalid Settlement VAT Option.");
        $v->isOk($setvatcode[$t], "string", 1, 40, "Invalid Settlement VAT code");
        $v->isOk($cusid[$t], "num", 1, 40, "Invalid customer number.");
        $v->isOk($out1[$t], "float", 0, 40, "Invalid paid amount(currant).");
        $v->isOk($out2[$t], "float", 0, 40, "Invalid paid amount(30).");
        $v->isOk($out3[$t], "float", 0, 40, "Invalid paid amount(60).");
        $v->isOk($out4[$t], "float", 0, 40, "Invalid paid amount(90).");
        $v->isOk($out5[$t], "float", 0, 40, "Invalid paid amount(120).");
        if (isset($invids[$t])) {
            foreach ($invids[$t] as $key => $value) {
                $v->isOk($invids[$t][$key], "num", 1, 50, "Invalid Invoice No.");
                $v->isOk($paidamt[$t][$key], "float", 1, 40, "Invalid amount to be paid.");
            }
        }
        if (strtotime($date[$t]) >= strtotime($blocked_date_from) and strtotime($date[$t]) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
            return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
        }
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . confirm($_POST);
    }
    for ($t = 0; $t < $rec_amount; $t++) {
        if (!isset($descript[$t]) or !isset($reference[$t]) or !isset($setamt[$t]) or empty($descript[$t]) or empty($reference[$t]) or empty($setamt[$t])) {
            continue;
        }
        /* get bank account id */
        if (($bank_acc[$t] = getbankaccid($bankid[$t])) === false) {
            $sql = "SELECT accid FROM core.accounts WHERE accname='Cash on Hand'";
            $rslt = db_exec($sql);
            if (pg_num_rows($rslt) < 1) {
                if ($bankid[$t] == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but\n\t\t\t\t\t\t**s not there now, you mudst have deleted it, if you want\n\t\t\t\t\t\tto use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $bank_acc[$t] = pg_fetch_result($rslt, 0);
        }
        $cus = qryCustomer($cusid[$t], "cusnum, deptid, cusname, surname");
        $dept = qryDepartment($cus["deptid"], "debtacc");
        $refnum = getrefnum();
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        # date format
        $sdate[$t] = explode("-", $date[$t]);
        $sdate[$t] = $sdate[$t][2] . "-" . $sdate[$t][1] . "-" . $sdate[$t][0];
        $cheqnum[$t] = 0 + $cheqnum[$t];
        $pay = "";
        $accdate[$t] = $sdate[$t];
        /* Paid invoices */
        $invidsers = "";
        $rinvids = "";
        $amounts = "";
        $invprds = "";
        $rages = "";
        /* OPTION 1 : AUTO ALLOCATE (write) */
        if ($all == 0) {
            # update the customer (make balance less)
            $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt[$t]}'::numeric(13,2))\n\t\t\t\t\tWHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            if (isset($invids[$t])) {
                foreach ($invids[$t] as $key => $value) {
                    $ii = $invids[$t][$key];
                    $pp = $paidamt[$t][$key];
                    /* OPTION 1: STOCK INVOICES */
                    if (!isset($itype[$t][$ii]) && !isset($ptype[$t][$ii])) {
                        $sql = "SELECT prd,invnum,odate FROM cubit.invoices\n\t\t\t\t\t\t\t\tWHERE invid ='{$ii}' AND div = '" . USER_DIV . "'";
                        $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                        if (pg_numrows($invRslt) < 1) {
                            return "<li class='err'>Invalid Invoice Number.</li>";
                        }
                        $inv = pg_fetch_array($invRslt);
                        $inv['invnum'] += 0;
                        // reduce invoice balance
                        $sql = "UPDATE cubit.invoices \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        $sql = "UPDATE cubit.open_stmnt \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        # record the payment on the statement
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($pp - $pp * 2) . "', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                        custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$t][$key], "c");
                        $rinvids .= "|{$invids[$t]}[{$key}]";
                        $amounts .= "|{$pp}";
                        if ($inv['prd'] == "0") {
                            $inv['prd'] = PRD_DB;
                        }
                        $invprds .= "|{$inv['prd']}";
                        $rages .= "|0";
                        $invidsers .= " - {$inv['invnum']}";
                        /* OPTION 1: NONS STOCK INVOICES */
                    } else {
                        if (!isset($ptype[$t][$ii])) {
                            $sql = "SELECT prd,invnum,descrip,age,odate FROM cubit.nons_invoices\n\t\t\t\t\t\t\t\tWHERE invid ='{$ii}' AND div = '" . USER_DIV . "'";
                            $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                            if (pg_numrows($invRslt) < 1) {
                                return "<li class='err'>Invalid Invoice Number.</li>";
                            }
                            $inv = pg_fetch_array($invRslt);
                            $inv['invnum'] += 0;
                            # reduce the money that has been paid
                            $sql = "UPDATE cubit.nons_invoices\n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            # record the payment on the statement
                            $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($pp - $pp * 2) . "', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$t][$key], "c");
                            recordCT($pp, $cus['cusnum'], $inv['age'], $accdate[$t]);
                            $rinvids .= "|{$ii}";
                            $amounts .= "|{$pp}";
                            $invprds .= "|0";
                            $rages .= "|{$inv['age']}";
                            $invidsers .= " - {$inv['invnum']}";
                        } else {
                            /* pos invoices */
                            $sqls = array();
                            for ($i = 1; $i <= 12; ++$i) {
                                $sqls[] = "SELECT '{$i}' AS prd,invid,invnum,odate FROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\t\t\tWHERE invid='{$ii}' AND div='" . USER_DIV . "'";
                            }
                            $sql = implode(" UNION ", $sqls);
                            $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                            if (pg_numrows($invRslt) < 1) {
                                return "<li class='err'>Invalid Invoice Number.</li>";
                            }
                            $inv = pg_fetch_array($invRslt);
                            // reduce the invoice balance
                            $sql = "UPDATE \"{$inv['prd']}\".pinvoices \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2)) \n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            $sql = "UPDATE cubit.open_stmnt \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2)) \n\t\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            # record the payment on the statement
                            $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, type, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}','{$inv['invnum']}', '" . ($pp - $pp * 2) . "','{$sdate[$t]}', 'Payment for Non Stock Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']}", $paidamt[$t][$key], "c");
                            recordCT($paidamt[$t][$key], $cus['cusnum'], 0, $accdate[$t]);
                            $rinvids .= "|{$invids[$t]}[{$key}]";
                            $amounts .= "|{$paidamt[$t]}[{$key}]";
                            $invprds .= "|{$inv['prd']}";
                            //$rages .= "|$inv[age]";
                            $invidsers .= " - {$inv['invnum']}";
                        }
                    }
                }
            }
            $cols = grp(m("bankid", $bankid[$t]), m("trantype", "deposit"), m("date", $sdate[$t]), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheqnum[$t]), m("amount", $amt[$t]), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference[$t]), m("div", USER_DIV));
            $dbobj = new dbUpdate("cashbook", "cubit", $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            /*
            $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript,
            			cheqnum, amount, banked, accinv, cusnum, rinvids, amounts,
            			invprds, rages, reference, div)
            		VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]',
            			'',
            			'$cheqnum', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]',
            			'$rinvids', '$amounts', '$invprds', '$rages', '$reference',
            			'".USER_DIV."')";
            $Rslt = db_exec ($sql) or errDie ("Unable to add bank payment to database.",SELF);
            */
            $refnum = getrefnum($accdate[$t]);
            writetrans($bank_acc[$t], $dept['debtacc'], $accdate[$t], $refnum, $amt[$t], "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
            db_conn('cubit');
            if ($out > 0) {
                /* START OPEN ITEMS */
                $openstmnt = new dbSelect("open_stmnt", "cubit", grp(m("where", "balance>0 AND cusnum='{$cusid[$t]}'"), m("order", "date")));
                $openstmnt->run();
                $open_out[$t] = $out[$t];
                $i = 0;
                $ox = "";
                while ($od = $openstmnt->fetch_array()) {
                    if ($open_out[$t] == 0) {
                        continue;
                    }
                    $oid = $od['id'];
                    if ($open_out[$t] >= $od['balance']) {
                        $open_amount[$t][$oid] = $od['balance'];
                        $open_out[$t] = sprint($open_out[$t] - $od['balance']);
                        $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$t}][{$oid}]' value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$t}][{$oid}]' value='{$open_amount[$t]}[{$oid}]'>" . CUR . " {$open_amount[$t]}[{$oid}]</td>\n\t\t\t\t\t\t\t</tr>";
                        $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'" . $open_amount[$t][$oid] . "' WHERE id='{$oid}'";
                        $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                    } elseif ($open_out < $od['balance']) {
                        $open_amount[$t][$oid] = $open_out[$t];
                        $open_out = 0;
                        $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$t}][{$oid}]' value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$t}][{$oid}]' value='{$open_amount[$t]}[{$oid}]'>" . CUR . " {$open_amount[$t]}[{$oid}]</td>\n\t\t\t\t\t\t\t</tr>";
                        $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'" . $open_amount[$t][$oid] . "' WHERE id='{$oid}'";
                        $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                    }
                    $i++;
                }
                if (open()) {
                    $bout[$t] = $out[$t];
                    $out[$t] = $open_out[$t];
                    if ($out > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.open_stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, balance, date, \n\t\t\t\t\t\t\t\ttype, st, div\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '0', '-{$out[$t]}', '-{$out[$t]}', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment Received', 'n', '" . USER_DIV . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                        //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";
                    }
                    $out[$t] = $bout[$t];
                } else {
                    //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";}
                }
            }
            if ($out[$t] > 0) {
                recordCT($out[$t], $cus['cusnum'], 0, $accdate[$t]);
                $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$out[$t]), m("date", $sdate[$t]), m("type", "Payment Received"), m("div", USER_DIV), m("allocation_date", $accdate[$t]));
                $dbobj = new dbUpdate("stmnt", "cubit", $cols);
                $dbobj->run(DB_INSERT);
                $dbobj->free();
                custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], "PAYMENT", "Payment received.", $out[$t], "c");
            }
        }
        /* start moving invoices */
        // move invoices that are fully paid
        $sql = "SELECT * FROM cubit.invoices WHERE balance=0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
        $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        while ($x = pg_fetch_array($invbRslt)) {
            if (($prd = $x['prd']) == "0") {
                $prd = PRD_DB;
            }
            // move invoice
            $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
            $dbobj = new dbUpdate("invoices", $prd, $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            // record movement
            $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
            $dbobj->setTable("movinv", "cubit");
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
            // move invoice items
            $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
            $inv_items->run();
            while ($xi = $inv_items->fetch_array()) {
                $xi['vatcode'] += 0;
                $xi['account'] += 0;
                $xi['del'] += 0;
                $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
                $dbobj->setTable("inv_items", $prd);
                $dbobj->setOpt($cols);
                $dbobj->run();
                $dbobj->free();
            }
            /* remove invoice from cubit schema */
            $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
            $dbobj->run();
            $dbobj->setTable("inv_items", "cubit");
            $dbobj->run();
        }
        /* start moving invoices */
        // move invoices that are fully paid
        $sql = "SELECT * FROM cubit.invoices WHERE balance=0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
        $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        while ($x = pg_fetch_array($invbRslt)) {
            if (($prd = $x['prd']) == "0") {
                $prd = PRD_DB;
            }
            // move invoice
            $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
            $dbobj = new dbUpdate("invoices", $prd, $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            // record movement
            $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
            $dbobj->setTable("movinv", "cubit");
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
            // move invoice items
            $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
            $inv_items->run();
            while ($xi = $inv_items->fetch_array()) {
                $xi['vatcode'] += 0;
                $xi['account'] += 0;
                $xi['del'] += 0;
                $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
                $dbobj->setTable("inv_items", $prd);
                $dbobj->setOpt($cols);
                $dbobj->run();
                $dbobj->free();
            }
            /* remove invoice from cubit schema */
            $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
            $dbobj->run();
            $dbobj->setTable("inv_items", "cubit");
            $dbobj->run();
        }
        #do journal for the settlement discount here ... now ...
        if ($setamt[$t] > 0) {
            db_conn('core');
            #get settlement accid
            $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Debtors Settlement Discount'";
            $run_setacc = db_exec($get_setacc) or errDie("Unable to get settlement account information");
            $setaccid = pg_fetch_result($run_setacc, 0, 0);
            #calculate the settlement vat ... and amt
            if (isset($setvat[$t]) and $setvat[$t] == 'inc') {
                db_connect();
                $get_vcode = "SELECT * FROM vatcodes WHERE id = '{$setvatcode[$t]}' LIMIT 1";
                $run_vcode = db_exec($get_vcode) or errDie("Unable to get vatcode informtion.");
                if (pg_numrows($run_vcode) < 1) {
                    return "<li class='err'>Settlement Discount VAT Code Not Set.</li>";
                }
                $vd = pg_fetch_array($run_vcode);
                #vat inc ... recalculate the amts
                $setvatamt = sprint($setamt[$t] * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
                $setamt[$t] = sprint($setamt[$t] - $setvatamt);
                $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
                $svattot = sprint($setamt[$t] + $setvatamt - ($setamt[$t] + $setvatamt) * 2);
                $svatamt = sprint($setvatamt - $setvatamt * 2);
                #process the vat amt ...
                writetrans($vatacc, $dept['debtacc'], $accdate[$t], $refnum, $setvatamt, "VAT Received on Settlement Discount for Customer : {$cus['cusname']} {$cus['surname']}");
                vatr($vd['id'], $accdate[$t], "OUTPUT", $vd['code'], $refnum, "VAT for Settlement Discount for Customer : {$cus['cusname']} {$cus['surname']}", $svattot, $svatamt);
            } else {
                #no vat for set amt ... do nothing
                $setvatamt = 0;
                $svattot = 0;
                $svatamt = 0;
            }
            writetrans($setaccid, $dept['debtacc'], $accdate[$t], $refnum, sprint($setamt[$t]), "Settlement Discount For {$cus['cusname']} {$cus['surname']}");
            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], "{$refnum}", "Payment Settlement Discount Received.", sprint($setamt[$t] + $setvatamt), "c");
            $sql = "\n\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cus['cusnum']}', '0', '" . $svattot . "', '{$sdate[$t]}', \n\t\t\t\t\t'Settlement Discount for Payment. Ref {$refnum}', '" . USER_DIV . "', '{$accdate[$t]}'\n\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            db_connect();
            #record this paid settlement discount for reporting ...
            $settl_sql = "\n\t\t\t\tINSERT INTO settlement_cus (\n\t\t\t\t\tcustomer, amt, setamt, setvatamt, setvat, \n\t\t\t\t\tsetvatcode, tdate, sdate, refnum\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cus['cusnum']}', '{$amt[$t]}', '{$setamt[$t]}', '{$setvatamt}', '{$setvat[$t]}', \n\t\t\t\t\t'{$setvatcode[$t]}', '{$accdate[$t]}', 'now', '{$refnum[$t]}'\n\t\t\t\t)";
            $run_settl = db_exec($settl_sql) or errDie("Unable to get debtor settlement information.");
        }
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    }
    // status report
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>Bank Receipt</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Bank Receipt added to cash book.</td>\n\t\t\t</tr>\n\t\t</table>";
    $OUTPUT = "\n\t\t<center>\n\t\t<table width='90%'>\n\t\t\t<tr valign='top'>\n\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t<td align='center'>" . mkQuickLinks(ql("bank-pay-add.php", "Add Bank Payment"), ql("bank-recpt-add.php", "Add Bank Receipt"), ql("bank-recpt-inv.php", "Add Customer Payment"), ql("cashbook-view.php", "View Cash Book")) . "\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
function 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 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 customize($_POST)
{
    extract($_POST);
    $fields = array();
    $fields["heading_1"] = COMP_NAME;
    $fields["heading_2"] = date("d/m/Y");
    $fields["heading_3"] = "Income Statement";
    $fields["heading_4"] = "Prepared by: " . USER_NAME;
    $fields["viewview"] = "core";
    $fields["month_from"] = (int) date("m");
    $fields["month_to"] = (int) date("m");
    $fields["this_year_this_month"] = true;
    $fields["last_year_same_month"] = true;
    $fields["this_year_year_to_date"] = true;
    $fields["last_year_year_to_date"] = true;
    $fields["budget"] = true;
    $fields["this_year_budget"] = true;
    $fields["zero_balance"] = "";
    $fields["naccount"] = "";
    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<select name='viewyear'>\n\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 .= "\n\t</select>";
    /*$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 account dropdown
    db_conn("core");
    $sql = "SELECT * FROM accounts WHERE acctype='I' OR acctype='E' ORDER BY accname,topacc ASC";
    $acc_rslt = db_exec($sql) or errDie("Unable to retrieve accounts information from Cubit.");
    /*
    	// Accounts dropdown output
    	$acc_sel = "<select name='naccount' style='width: 200px'>
    		<option value='0'>Please select</option>";
    	while ($acc_data = pg_fetch_array($acc_rslt)) {
    		if ($naccount == $acc_data["accid"]) {
    			$selected = "selected";
    		} else {
    			$selected = "";
    		}
    
    		$acc_sel .= "<option value='$acc_data[accid]' $selected>$acc_data[accname]</option>";
    	}
    	$acc_sel .= "</select>";
    
    	// Retrieve saved accounts from Cubit
    	db_conn("cubit");
    	$sql = "SELECT * FROM saved_is_accounts";
    	$sisacc_rslt = db_exec($sql) or errDie("Unable to retrieve saved income statement accounts from Cubit");
    
    	if (!pg_num_rows($sisacc_rslt)) {
    		$accounts_out = "
    		<tr class='bg-odd'>
    			<td>No accounts have been selected, ALL accounts will be displayed</td>
    		</tr>";
    	} else {
    		$accounts_out = "";
    	}
    
    	$i = 0;
    	while ($sisacc_data = pg_fetch_array($sisacc_rslt)) {
    		// Alternate the background colour
    		$i++;
    
    		if (isset($rem[$sisacc_data["id"]])) {
    			$checked = "checked";
    		} else {
    			$checked = "";
    		}
    
    		$accounts_out .= "
    		<tr class='".bg_class()."'>
    			<td>$sisacc_data[accname]</td>
    			<td><input type='checkbox' name='rem[$sisacc_data[id]]' value='$sisacc_data[id]' $checked></td>
    		</tr>";
    	}*/
    $accounts_out = "";
    //------------------------------------------------------------------------
    if (isset($last_year_same_month) && $last_year_same_month) {
        $lysm = "checked";
    } else {
        $lysm = "";
    }
    //------------------------------------------------------------------------
    if (isset($this_year_year_to_date) && $this_year_year_to_date) {
        $tyytd = "checked";
    } else {
        $tyytd = "";
    }
    //------------------------------------------------------------------------
    if (isset($last_year_year_to_date) && $last_year_year_to_date) {
        $lyytd = "checked";
    } else {
        $lyytd = "";
    }
    //------------------------------------------------------------------------
    if (isset($budget) && $budget) {
        $budget = "checked";
    } else {
        $budget = "";
    }
    //------------------------------------------------------------------------
    if (isset($this_year_budget) && $this_year_budget) {
        $tybudget = "checked";
    } else {
        $tybudget = "";
    }
    // Layout
    $OUTPUT = "<h3>Income Statement</h3>\n\t<form method='post' action='" . SELF . "'>\n\t<input type='hidden' name='key' value='display' />\n\t<input type='hidden' name='acc_view' value='sel'>\n\t<input type='hidden' name='customized' value='true'>\n\t<table border='0' cellpadding='0' cellspacing='0'>\n\t\t<tr>\n\t\t\t<th colspan=2><h3>Customise<h3></th>\n\t\t</tr>\n\n\t\t<tr><td valign='top'>\n\t\t<table border='0' cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' style='margin: 0px; width: 300px'>\n\t\t\t<tr>\n\t\t\t\t<th colspan=2>Headings</th>\n\t\t\t</tr>\n\t\t\t<tr class='bg-odd'>\n\t\t\t\t<td>Heading 1</td>\n\t\t\t\t<td><input type=text name='heading_1' value='{$heading_1}' style='width: 100%'></td>\n\t\t\t</tr>\n\t\t\t<tr class='bg-even'>\n\t\t\t\t<td>Heading 2</td>\n\t\t\t\t<td><input type=text name='heading_2' value='{$heading_2}' style='width: 100%'></td>\n\t\t\t</tr>\n\t\t\t<tr class='bg-odd'>\n\t\t\t\t<td>Heading 3</td>\n\t\t\t\t<td><input type=text name='heading_3' value='{$heading_3}' style='width: 100%'></td>\n\t\t\t</tr>\n\t\t\t<tr class='bg-even'>\n\t\t\t\t<td width='0%'>Heading 4</td>\n\t\t\t\t<td><input type=text name='heading_4' value='{$heading_4}' style='width: 100%'></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th colspan=2>Display</th>\n\t\t\t</tr>\n\t\t\t<tr class='bg-odd'>\n\t\t\t\t<td>Last Year - Same Month</td>\n\t\t\t\t<td><input type='checkbox' name='last_year_same_month' value='true' {$lysm} \\></td>\n\t\t\t</tr>\n\t\t\t<tr class='bg-even'>\n\t\t\t\t<td>This Year - To Month</td>\n\t\t\t\t<td><input type='checkbox' name='this_year_year_to_date' value='true' {$tyytd} \\></td>\n\t\t\t</tr>\n\t\t\t<tr class='bg-odd'>\n\t\t\t\t<td>Last Year - Year To Date</td>\n\t\t\t\t<td><input type='checkbox' name='last_year_year_to_date' value='true' {$lyytd} \\></td>\n\t\t\t</tr>\n\t\t\t<tr class='bg-even'>\n\t\t\t\t<td>Month Budget</td>\n\t\t\t\t<td><input type='checkbox' name='budget' value='true' {$budget} \\></td>\n\t\t\t</tr>\n\t\t\t<tr class='bg-odd'>\n\t\t\t\t<td>This Year Budget To Month</td>\n\t\t\t\t<td><input type='checkbox' name='this_year_budget' value='true' {$tybudget} \\></td>\n\t\t\t</tr>\n\t\t\t<tr class='bg-even'>\n\t\t\t\t<td>Zero Balances</td>\n\t\t\t\t<td><input type='checkbox' name='zero_balance' value='checked' {$zero_balance} \\></td>\n\t\t\t</tr>\n\t\t\t<tr class='bg-odd'>\n\t\t\t\t<td colspan='2'>\n\t\t\t\t\t<table border='0' cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t\t\t\t<tr class='bg-odd'>\n\t\t\t\t\t\t<td>Year</td>\n\t\t\t\t\t\t<td align='center'>{$year_sel}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>Month</td>\n\t\t\t\t\t\t<td nowrap>{$months_to}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<table border='0' cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' style='margin: 0px; width: 300px'>\n\t\t\t<!--<tr>\n\t\t\t\t<th colspan='2'>Add Account</th>\n\t\t\t</tr>\n\t\t\t<tr class='bg-odd'>\n\t\t\t\t<td align='center'>\$acc_sel</td>\n\t\t\t\t<td align='center'><input type='submit' name='key' value='Add'></td>\n\t\t\t</tr>//-->\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><input type='submit' value='Display' style='width: 100%; font-weight: bold;'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</td>\n\n\t\t<!--<td valign='top'>\n\t\t<table border='0' cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='250px'>\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Accounts</th>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t{$accounts_out}\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='center'><input type='submit' name='key' value='Remove Selected'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</td>//-->\n\t\t</tr>\n\t</table>\n\t</form>";
    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 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 write($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($catcod, "string", 0, 50, "Invalid category code.");
    $v->isOk($cat, "string", 1, 255, "Invalid stock category name.");
    $v->isOk($descript, "string", 0, 100, "Invalid stock category descripting.");
    # Display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>{$e['msg']}</li>";
        }
        $confirm .= "</li><p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>\n\t\t\t\t<P>\n\t\t\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=100>\n\t\t\t\t<tr><th>Quick Links</th></tr>\n\t\t\t\t\t<tr class='bg-even'><td><a href='stockcat-view.php'>View Stock Category</a></td></tr>\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t</form>\n\t\t\t\t</table>";
        return $confirm;
    }
    # check stock code
    db_connect();
    $sql = "SELECT catcod FROM stockcat WHERE lower(catcod) = lower('{$catcod}') AND div = '" . USER_DIV . "'";
    $cRslt = db_exec($sql);
    if (pg_numrows($cRslt) > 0) {
        $error = "<li class=err> A Category with code : <b>{$catcod}</b> already exists.</li>";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        //return $error;
    }
    // insert into stock
    db_connect();
    $sql = "INSERT INTO stockcat(catcod, cat, descript, div) VALUES('{$catcod}', '{$cat}', '{$descript}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert stock category to Cubit.", SELF);
    if (frmupdate_passon()) {
        $newlst = new dbSelect("stockcat", "cubit", grp(m("cols", "catid, catcod, cat"), m("where", "div='" . USER_DIV . "'"), m("order", "cat ASC")));
        $newlst->run();
        $a = array();
        if ($newlst->num_rows() > 0) {
            while ($row = $newlst->fetch_array()) {
                $a[$row["catid"]] = "({$row['catcod']}) {$row['cat']}";
            }
        }
        $js = frmupdate_exec(array($a), true);
    } else {
        $js = "";
    }
    $write = "\n\t{$js}\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\n\t\t<tr><th>New Stock Category added to database</th></tr>\n\t\t<tr class=datacell><td>New Stock Category, {$cat} ({$catcod}) has been successfully added to Cubit.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='2' cellspacing='1'>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class='bg-even'><td><a href='stockcat-view.php'>View Stock Category</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\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 deny(&$frm)
{
    /* @var $frm cForm */
    if (($e = $frm->validateValue($_GET["id"], "num", 1, 10)) !== false) {
        return view($frm, "<li class='err'>Error reading key: {$e}.</li>");
    }
    $qry = new dbSelect("keys", "trh", grp(m("cols", "*, (key).*"), m("where", "id='{$_GET['id']}'")));
    $qry->run();
    if ($qry->num_rows() <= 0) {
        return view($frm, "<li class='err'>Invalid key selected.</li>");
    }
    $ki = $qry->fetch_array();
    if ($ki["custid"] == "-1") {
        $fromwho = "cust";
    } else {
        if ($ki["suppid"] == "-1") {
            $fromwho = "supp";
        } else {
            return view($frm, "<li class='err'>Key already approved.</li>");
        }
    }
    if (send_trhmsg($fromwho, "-1", $ki["email"], "rspkey", str_pad("denied", 32, 'A', STR_PAD_RIGHT))) {
        $upd = new dbDelete("keys", "trh", "id='{$_GET['id']}'");
        $upd->run();
        return view($frm, "<li class='err'>Successfully denied request.</li>");
    } else {
        /* set the id back to -1, because there was an error */
        $cols = grp(m("{$fromwho}id", "-1"));
        $upd = new dbUpdate("keys", "trh", $cols, "id='{$_POST['id']}'");
        $upd->run(DB_UPDATE);
        return view($frm, "<li class='err'>Error denying request.</li>");
    }
}