function write(&$frm)
{
    if (isset($_REQUEST["btn_back"])) {
        return enter($frm);
    }
    if ($frm->validate("write")) {
        return confirm($frm);
    }
    $upd = new dbUpdate("suppstock", "cubit");
    $del = new dbDelete("suppstock", "cubit");
    foreach ($_REQUEST["stkcod"] as $suppid => $stkcod) {
        if (empty($stkcod)) {
            $del->setOpt("suppid='{$suppid}' AND stkid='{$_REQUEST['id']}'");
            $del->run();
            continue;
        }
        $cols = grp(m("suppid", $suppid), m("stkid", $_REQUEST["id"]), m("stkcod", $stkcod));
        $upd->setOpt($cols, "suppid='{$suppid}' AND stkid='{$_REQUEST['id']}'");
        $upd->run(DB_REPLACE);
    }
    foreach ($_REQUEST["stkdes"] as $suppid => $stkdes) {
        if (empty($stkcod)) {
            $del->setOpt("suppid='{$suppid}' AND stkid='{$_REQUEST['id']}'");
            $del->run();
            continue;
        }
        $cols = grp(m("suppid", $suppid), m("stkid", $_REQUEST["id"]), m("stkdes", $stkdes));
        $upd->setOpt($cols, "suppid='{$suppid}' AND stkid='{$_REQUEST['id']}'");
        $upd->run(DB_REPLACE);
    }
    $OUT = "<script>window.close();</script>";
    return $OUT;
}
function write(&$frm)
{
    if ($frm->validate("write")) {
        return edit($frm);
    }
    $cols = grp(m("value", $_POST["print_dialog"]));
    $qry = new dbUpdate("settings", "cubit", $cols, "constant='PRINT_DIALOG'");
    $qry->run(DB_UPDATE);
    $OUT = "\n\t<h3>Printing Options</h3>\n\tSuccessfully saved printing options.";
    return $OUT;
}
function write(&$frm)
{
    if ($frm->validate("write")) {
        return edit($frm);
    }
    $cols = grp(m("value", $_POST["vat_setting"]));
    $qry = new dbUpdate("settings", "cubit", $cols, "constant='PURCH_DEFAULT_VAT_SETTING'");
    $qry->run(DB_UPDATE);
    $OUT = "\n\t<h3>Purchase VAT Setting</h3>\n\tSuccessfully saved setting.";
    return $OUT;
}
function write()
{
    extract($_GET);
    if (!isset($id)) {
        $id = 0;
    }
    $cols = grp(m("name", $name), m("in_republic", $in_republic), m("meals", $meals), m("accid", $accid), m("div", USER_DIV));
    $subs = new dbUpdate("subsistence", "cubit", $cols, "id='{$id}'");
    $subs->run(DB_REPLACE);
    $OUT = "\n\t<h3>Define Subsistence Allowance</h3>\n\tSuccessfully created/updated subsistence allowance.";
    return $OUT;
}
function write($frm)
{
    /* @var $frm cForm */
    if ($frm->validate("confirm")) {
        return edit($frm);
    }
    /* point of sale message at the bottom of the slip */
    $cols = grp(m("value", $_POST["posmsg"]));
    $upd = new dbUpdate("settings", "cubit", $cols, "constant='POSMSG'");
    $upd->run(DB_UPDATE);
    $OUT = "\n\t<h3>Point of Sale Settings</h3>\n\t\n\tSuccessfully updated.<br />";
    return $OUT;
}
function write($frm)
{
    if (isset($_REQUEST["btn_back"])) {
        return select($frm);
    }
    /* @var $frm cForm */
    if ($frm->validate("confirm")) {
        return confirm($frm);
    }
    $cols = grp(m("value", $_REQUEST["emp_year"]));
    $upd = new dbUpdate("settings", "cubit", $cols, "constant='EMP_TAXYEAR'");
    $upd->run(DB_UPDATE);
    $OUT = "\n\t<h3>Active Tax Year</h3>\n\tSuccessfully updated active Tax Year to {$_REQUEST['emp_year']}";
    return $OUT;
}
function check_messages()
{
    $qry = new dbSelect("req", "cubit", grp(m("cols", "1"), m("where", "recipient='" . USER_NAME . "' AND alerted IS NULL")));
    $qry->run();
    if ($qry->num_rows() == 0) {
        return "NO MESSAGES";
    } else {
        $cols = grp(m("alerted", "1"));
        $upd = new dbUpdate("req", "cubit", $cols, "recipient='" . USER_NAME . "'");
        $upd->run(DB_UPDATE);
        $qry->setOpt(grp(m("where", "recipient='" . USER_NAME . "' AND viewed='0'")));
        $qry->run();
        return "MSGS: " . $qry->num_rows();
    }
}
function writesal($frm)
{
    if ($frm->validate("writesal")) {
        return entersal($frm);
    }
    extract($_POST);
    $upd = new dbUpdate("salpaid", "cubit", false);
    foreach ($sal as $payid => $salrate) {
        $cols = grp(m("salrate", $salrate), isset($hrs[$payid]) ? m("hours", $hrs[$payid]) : false);
        $upd->setOpt($cols, "id='{$payid}'");
        $upd->run(DB_UPDATE);
    }
    $OUT = "\n\t<h3>Previous Employee Salary Information</h3>\n\tSuccessfully updated employee payslip information.";
    return $OUT;
}
function write()
{
    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 write()
{
    extract($_POST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($salespno, "num", 1, 10, "Invalid Sales Person number.");
    $v->isOk($salesp, "string", 1, 255, "Invalid Sales Person name.");
    if ($v->isError()) {
        return $v->genErrors();
    }
    $cols = grp(m("salespno", $salespno), m("salesp", $salesp), m("com", $com), m("div", USER_DIV));
    $qry = new dbUpdate("salespeople", "exten", $cols);
    $qry->run(DB_INSERT);
    if ($qry->affected() < 1) {
        return "<li class=err>Unable to add sales person to Cubit.";
    }
    $write = "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th>Sales Person added to system</th>\n\t</tr>\n\t<tr class='text'><td>New Sales Person <b>{$salesp}</b>, has been\n\t\tsuccessfully added to the system.</td>\n\t</tr>\n\t</table>";
    return $write;
}
function request($frm)
{
    if (isset($_POST["btn_back"])) {
        return enter($frm);
    }
    if ($frm->validate("request")) {
        return confirm($frm);
    }
    $newkey = genkey();
    if (isset($_REQUEST["suppid"])) {
        $suppid = $_REQUEST["suppid"];
        $custid = "0";
    } else {
        $custid = $_REQUEST["custid"];
        $suppid = "0";
    }
    $cols = grp(m("introtime", raw("CURRENT_TIMESTAMP")), m("introip", "0.0.0.0"), m("email", $_REQUEST["email"]), m("custid", $custid), m("suppid", $suppid), m("key", dbrow("0.0.0.0/0", "", $newkey)), m("userid", USER_ID));
    $upd = new dbUpdate("keys", "trh", $cols);
    $upd->run(DB_INSERT);
    if ($upd->affected() > 0) {
        if (isset($_REQUEST["suppid"])) {
            if (($r = send_trhmsg("supp", $_REQUEST["suppid"], $_REQUEST["email"], "reqkey", $newkey)) === true) {
                $OUT = "Sent request for communication to supplier. On response you will be notified.";
            } else {
                $OUT = "Error sending request for communication: {$r}";
            }
        } else {
            if (($r = send_trhmsg("cust", $_REQUEST["custid"], $_REQUEST["email"], "reqkey", $newkey)) === true) {
                $OUT = "Sent request for communication to customer. On response you will be notified.";
            } else {
                $OUT = "Error sending request for communication: {$r}";
            }
        }
    } else {
        $OUT = "Error sending request for communication: Error updating database.";
    }
    return $OUT;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    $supplier1 += 0;
    $supplier2 += 0;
    $supplier3 += 0;
    if (isset($back)) {
        return view_err($_POST);
    }
    $vatcode += 0;
    # Validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($whid, "num", 1, 50, "Invalid Store.");
    $v->isOk($catid, "num", 1, 50, "Invalid Stock Category.");
    $v->isOk($stkcod, "string", 1, 50, "Invalid stock code.");
    $v->isOk($stkdes, "string", 0, 255, "Invalid stock description.");
    $v->isOk($bar, "string", 0, 20, "Invalid bar code.");
    $v->isOk($clasid, "num", 1, 50, "Invalid Classification.");
    $v->isOk($buom, "string", 0, 10, "Invalid bought unit of measure.");
    $v->isOk($suom, "string", 0, 10, "Invalid selling unit of measure.");
    $v->isOk($rate, "num", 1, 10, "Invalid selling units per bought unit.");
    $v->isOk($shelf, "string", 0, 10, "Invalid Shelf number.");
    $v->isOk($row, "string", 0, 10, "Invalid Row number.");
    $v->isOk($minlvl, "num", 0, 10, "Invalid minimum stock level.");
    $v->isOk($maxlvl, "num", 0, 10, "Invalid maximum stock level.");
    $v->isOk($selamt, "float", 0, 10, "Invalid selling amount.");
    $v->isOk($markup, "float", 0, 10, "Invalid markup percentage.");
    $v->isOk($warranty, "string", 0, 80, "Invalid warranty.");
    $v->isOk($rfidtype, "string", 0, 80, "Invalid RFID type of tag.");
    $v->isOk($rfidfreq, "string", 0, 80, "Invalid RFID Frequency.");
    $v->isOk($rfidrate, "string", 0, 80, "Invalid RFID Tag read rate.");
    $minlvl += 0;
    $maxlvl += 0;
    $selamt += 0;
    # Display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        $confirm .= "\n\t\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>\n\t\t\t<P>\n\t\t\t<table " . TMPL_tblDflts . " width='100'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='stock-view.php'>View Stock</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t</tr>\n\t\t\t</form>\n\t\t\t</table>";
        return $confirm;
    }
    # Get category name
    db_connect();
    $sql = "SELECT cat FROM stockcat WHERE catid = '{$catid}'";
    $catRslt = db_exec($sql);
    $cat = pg_fetch_array($catRslt);
    # Get class
    $sql = "SELECT classname FROM stockclass WHERE clasid = '{$clasid}' AND div = '" . USER_DIV . "'";
    $clasRslt = db_exec($sql);
    $clas = pg_fetch_array($clasRslt);
    # Check stock code
    db_connect();
    $sql = "SELECT stkcod FROM stock WHERE lower(stkcod) = lower('{$stkcod}') AND whid = '{$whid}' AND div = '" . USER_DIV . "'";
    $cRslt = db_exec($sql);
    if (pg_numrows($cRslt) > 0) {
        $error = "<li class='err'> An item with stock code : <b>{$stkcod}</b> already exists in the selected store.</li>";
        return view_err($_POST, $error);
    }
    if (strlen($bar) > 0) {
        $sql = "SELECT bar FROM stock WHERE lower(bar) = lower('{$bar}') AND div = '" . USER_DIV . "'";
        $cRslt = db_exec($sql);
        if (pg_numrows($cRslt) > 0) {
            $error = "<li class='err'> An item with Bar Code : <b>{$bar}</b> already exists.</li>";
            return $error;
        }
    }
    # Insert into stock
    db_connect();
    $sql = "\n\t\tINSERT INTO stock (\n\t\t\tsupplier1, supplier2, supplier3, stkcod, stkdes, prdcls, \n\t\t\tclassname, csamt, units, buom, suom, rate, \n\t\t\tshelf, row, minlvl, maxlvl, csprice, selamt, \n\t\t\texvat, catid, catname, whid, blocked, type, \n\t\t\tserd, alloc, com, bar, div, vatcode, \n\t\t\tmarkup, rfidtype, rfidfreq, rfidrate, warranty\n\t\t) VALUES (\n\t\t\t'{$supplier1}', '{$supplier2}', '{$supplier3}', '{$stkcod}', '{$stkdes}', '{$clasid}', \n\t\t\t'{$clas['classname']}', '0', '0', '{$buom}', '{$suom}', '{$rate}', \n\t\t\t'{$shelf}', '{$row}', '{$minlvl}', '{$maxlvl}', '0', '{$selamt}', \n\t\t\t'n', '{$catid}', '{$cat['cat']}', '{$whid}', 'n', '{$stktp}', \n\t\t\t'{$serd}', '0', '0', '{$bar}', '" . USER_DIV . "', '{$vatcode}', \n\t\t\t'{$markup}', '{$rfidtype}', '{$rfidfreq}', '{$rfidrate}', '{$warranty}'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
    # Get last stock ID
    $stkid = pglib_lastid("stock", "stkid");
    # Add this product to all pricelists
    db_conn("exten");
    $sql = "SELECT * FROM pricelist WHERE div = '" . USER_DIV . "'";
    $listRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($listRslt) > 0) {
        while ($list = pg_fetch_array($listRslt)) {
            db_conn("exten");
            $sql = "INSERT INTO plist_prices (listid, stkid, catid, clasid, price, div,show) VALUES ('{$list['listid']}', '{$stkid}', '{$catid}', '{$clasid}', '{$selamt}', '" . USER_DIV . "','Yes')";
            $rslt = db_exec($sql) or errDie("Unable to insert price list items to Cubit.", SELF);
        }
    }
    $sql = "SELECT * FROM spricelist WHERE div = '" . USER_DIV . "'";
    $listRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($listRslt) > 0) {
        while ($list = pg_fetch_array($listRslt)) {
            db_conn("exten");
            $sql = "INSERT INTO splist_prices (listid, stkid, catid, clasid, price, div) VALUES ('{$list['listid']}', '{$stkid}', '{$catid}', '{$clasid}', '0', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert price list items to Cubit.", SELF);
        }
    }
    /* adding from supplier stock */
    if (isset($supid) && isset($supstkcod)) {
        $cols = grp(m("suppid", $supid), m("stkid", $stkid), m("stkcod", $supstkcod));
        $upd = new dbUpdate("suppstock", "cubit", $cols);
        $upd->run(DB_INSERT);
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM stock WHERE stkid='{$stkid}'";
    $Ri = db_exec($Sl) or errDie("Unable to get stock.");
    $data = pg_fetch_array($Ri);
    $date = date("Y-m-d");
    db_conn('audit');
    $Sl = "SELECT * FROM closedprd ORDER BY id";
    $Ri = db_exec($Sl);
    while ($pd = pg_fetch_array($Ri)) {
        db_conn($pd['prdnum']);
        $Sl = "\n\t\t\tINSERT INTO stkledger (\n\t\t\t\tstkid, stkcod, stkdes, trantype, edate, qty, \n\t\t\t\tcsamt, balance, bqty, details, div, yrdb\n\t\t\t) VALUES (\n\t\t\t\t'{$data['stkid']}', '{$data['stkcod']}', '{$data['stkdes']}', 'bal', '{$date}', '{$data['units']}', \n\t\t\t\t'{$data['csamt']}', '{$data['csamt']}', '{$data['units']}', 'Balance', '" . USER_DIV . "', '" . YR_DB . "'\n\t\t\t)";
        $Ro = db_exec($Sl);
    }
    # deal with logo image
    global $_FILES;
    if ($change_image == "yes") {
        if (empty($_FILES["image"])) {
            return "<li class='err'>Please select an image to upload from your hard drive.</li>";
        }
        if (is_uploaded_file($_FILES["image"]["tmp_name"])) {
            # Check file ext
            if (preg_match("/(image\\/jpeg|image\\/png|image\\/gif)/", $_FILES["image"]["type"], $extension)) {
                $type = $_FILES["image"]["type"];
                // open file in "read, binary" mode
                $img = "";
                $file = fopen($_FILES['image']['tmp_name'], "rb");
                while (!feof($file)) {
                    // fread is binary safe
                    $img .= fread($file, 1024);
                }
                fclose($file);
                # base 64 encoding
                $img = base64_encode($img);
                db_connect();
                $Sl = "INSERT INTO stkimgs (stkid, image, imagetype) VALUES ('{$data['stkid']}','{$img}','{$type}')";
                $Ry = db_exec($Sl) or errDie("Unable to upload company logo Image to DB.", SELF);
                # to show IMG
                //$logoimg = "<br><img src='compinfo/getimg.php' width=230 height=47><br><br>";
                //$logo = "compinfo/getimg.php";
            } else {
                return "<li class='err'>Please note that we only accept images of the types PNG,GIF and JPEG.</li>";
            }
        } else {
            return "Unable to upload file, Please check file permissions.";
        }
    }
    // Layout
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t<tr>\n\t\t\t\t<th>New Stock added to database</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>New Stock, {$stkdes} ({$stkcod}) has been successfully added to Cubit.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table border='0' cellpadding='2' cellspacing='1'>\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='stock-add.php'>Add Stock</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='stock-view.php'>View Stock</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t</tr>\n\t\t</table>";
    return $write;
}
function package($_POST)
{
    $_POST = var_makesafe($_POST);
    extract($_POST);
    $week += 0;
    if (isset($back)) {
        return process($_POST);
    }
    $annual += 0;
    $bonus += 0;
    $paye_salary += 0;
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    $v->isOk($accid, "num", 1, 20, "Invalid bank number.");
    $v->isOk($MON, "num", 1, 2, "Invalid month.");
    $v->isOk($basic_sal, "float", 1, 40, "Invalid basic salary.");
    $v->isOk($overamt, "float", 1, 40, "Invalid overtime amount.");
    $v->isOk($income, "float", 1, 40, "Invalid income.");
    $v->isOk($commission, "float", 0, 40, "Invalid commision.");
    $v->isOk($abonus, "float", 0, 40, "Invalid Bonus.");
    $v->isOk($loaninstall, "float", 0, 40, "Invalid loan installment.");
    $v->isOk($paidamount, "float", 1, 40, "Invalid paid amount.");
    if (isset($allowances)) {
        foreach ($allowances as $key => $value) {
            $v->isOk($allowances[$key], "float", 0, 20, "Invalid allowance amount " . ($key + 1) . ".");
        }
    }
    if (isset($deductid)) {
        foreach ($deductid as $key => $value) {
            $v->isOk($deductid[$key], "num", 1, 20, "Invalid deductions ID.");
        }
    }
    if (isset($deductions)) {
        foreach ($deductions as $key => $value) {
            $v->isOk($deductions[$key], "float", 0, 20, "Invalid deduction amount" . ($key + 1) . ".");
        }
    }
    if (isset($allowid)) {
        foreach ($allowid as $key => $value) {
            $v->isOk($allowid[$key], "num", 1, 20, "Invalid allowance ID.");
        }
    }
    if (isset($allowtax)) {
        foreach ($allowtax as $key => $value) {
            $v->isOk($allowtax[$key], "string", 2, 20, "Invalid allowance tax " . ($key + 1) . ".");
        }
    }
    $date = mkdate($year, $mon, $day);
    $pdate = mkdate($year, $MON, $pday);
    if (!checkdate($mon, $day, $year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    $mon = $MON;
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    $basic_sal_save = $basic_sal;
    if (isset($multi)) {
        $basic_sal = sprint($basic_sal * $multi);
        $tyear = $tyear / $multi;
    } else {
        $basic_sal = $basic_sal;
    }
    db_conn('cubit');
    $nettpay = $income;
    $sql = "SELECT * FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "'";
    $empRslt = db_exec($sql) or errDie("Unable to select employees from database.");
    if (pg_numrows($empRslt) < 1) {
        return "Invalid employee ID.";
    }
    $ecost = 0;
    $myEmp = pg_fetch_array($empRslt);
    // fringe benefits
    $i = 0;
    $fringes = "";
    $fringes_desc = "";
    if (isset($fringebens)) {
        foreach ($fringebens as $key => $value) {
            if ($fringebens[$key] > 0) {
                $fringes_desc .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$fringename[$key]}</td>\n\t\t\t\t\t<td>" . CUR . " {$fringebens[$key]}</td>\n\t\t\t\t</tr>";
            }
        }
    }
    if (!empty($fringes_desc)) {
        $fringes_desc = "<tr><th colspan='2'>Fringe Benefits</th></tr>{$fringes_desc}";
    }
    $all_before = "";
    $all_after = "";
    $all_beforeamount = 0;
    $all_afteramount = 0;
    if (isset($allowtax)) {
        foreach ($allowtax as $key => $perc) {
            if ($perc == "Yes" and $allowances[$key] > 0) {
                $all_before .= "<tr><td>{$allowname[$key]}</td><td align='right'>" . CUR . " {$allowances[$key]}</td></tr>";
                $all_beforeamount = $all_beforeamount + $allowances[$key];
            } elseif ($allowances[$key] > 0) {
                $all_after .= "<tr><td>{$allowname[$key]}</td><td align='right'>" . CUR . " {$allowances[$key]}</td></tr>";
                $all_afteramount = $all_afteramount + $allowances[$key];
            }
        }
    }
    $de_before = "\n\t\t<tr>\n\t\t\t<td colspan='2'>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Details</th>\n\t\t\t\t\t\t<th>Employee aContribution</th>\n\t\t\t\t\t\t<!--<th>Employer Contribution</th>//-->\n\t\t\t\t\t</tr>";
    $de_after = "\n\t\t<tr>\n\t\t\t<td colspan='2'>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Details</th>\n\t\t\t\t\t\t<th>Employee Contribution</th>\n\t\t\t\t\t\t<!--<th>Employer Contribution</th>//-->\n\t\t\t\t\t</tr>";
    $de_beforeamount = 0;
    $de_afteramount = 0;
    $de_beforeamount_emp = 0;
    $de_afteramount_emp = 0;
    if (isset($deducttax)) {
        foreach ($deducttax as $key => $perc) {
            if ($perc == "Yes" and $deductions[$key] > 0) {
                $de_before .= "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>{$deductname[$key]}</td>\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$deductions[$key]}</td>\n<!--\t\t\t\t\t\t<td align='right'>" . CUR . " {$employer_deductions[$key]}</td> //-->\n\t\t\t\t\t</tr>";
                $de_beforeamount = $de_beforeamount + $deductions[$key] + $employer_deductions[$key];
                $de_beforeamount_emp += $employer_deductions[$key];
            } elseif ($deductions[$key] > 0) {
                $de_after .= "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>{$deductname[$key]}</td>\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$deductions[$key]}</td>\n<!--\t\t\t\t\t\t<td align='right'>" . CUR . " {$employer_deductions[$key]}</td> //-->\n\t\t\t\t\t</tr>";
                $de_afteramount = $de_afteramount + $deductions[$key] + $employer_deductions[$key];
                $de_afteramount_emp += $employer_deductions[$key];
            }
        }
    }
    $de_before .= "</table></td></tr>";
    $de_after .= "</table></td></tr>";
    if ($all_beforeamount > 0) {
        $all_before = "<tr><td colspan='2'>Allowances</td></tr>" . $all_before;
    }
    if ($all_afteramount > 0) {
        $all_after = "<tr><td colspan='2'>Allowances</td></tr>" . $all_after;
    }
    if ($de_beforeamount > 0) {
        $de_before = "<tr><td colspan='2'>Deductions</td></tr>" . $de_before;
    }
    if ($de_afteramount > 0) {
        $de_after = "<tr><td colspan='2'>Deductions</td></tr>" . $de_after;
    }
    $gros_sal = sprint($grossal);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $bank = pg_fetch_array($rslt);
    $bankacc = $bank["accnum"];
    $basic_sal = sprint($basic_sal);
    $commission = sprint($commission);
    $abonus = sprint($abonus);
    $overamt = sprint($overamt);
    $paye = sprint($paye);
    $nettpay = sprint($nettpay);
    $sdl = sprint($comp_sdl);
    $amount = sprint($gros_sal + $comp_pension + $comp_provident + $comp_medical + $comp_other + $comp_uif + $comp_ret + $sdl);
    $loaninstall = sprint($loaninstall);
    //Original CC
    //$cc = "<script> CostCenter('ct', 'Salaries', '$date', 'Salary Payment for employee,  $myEmp[fnames] $myEmp[sname]', '$amount', '../'); </script>";
    //New CC
    $cc = "CostCenter('ct', 'Salaries', '{$date}', 'Salary Payment for employee,  {$myEmp['fnames']} {$myEmp['sname']}', '{$amount}', '../'); ";
    $ecost = $amount;
    if ($commission > 0) {
        $comDis = "<tr><td>Commission</td><td align='right'>" . CUR . " {$commission}</td></tr>";
    } else {
        $comDis = "";
    }
    if ($abonus > 0) {
        $aboDis = "<tr><td>Annual Bonus</td><td align='right'>" . CUR . " {$abonus}</td></tr>";
    } else {
        $aboDis = "";
    }
    if ($overamt > 0) {
        $oveDis = "<tr><td>Overtime</td><td align='right'>" . CUR . " {$overamt}</td></tr>";
    } else {
        $oveDis = "";
    }
    if ($loaninstall > 0) {
        $loaDis = "<tr><td>Loan Instalment</td><td align='right'>" . CUR . " {$loaninstall}</td></tr>";
    } else {
        $loaDis = "";
    }
    if ($basic_sal != $gros_sal) {
        $groDis = "<tr><td>Gross Salary</td><td align='right'>" . CUR . " {$gros_sal}</td></tr>";
    } else {
        $groDis = "";
    }
    if ($all_travel > 0) {
        $talDis = "<tr><td>Travel Allowance</td><td align='right'>" . CUR . " {$all_travel}</td></tr>";
    } else {
        $talDis = "";
    }
    db_connect();
    $Sl = "SELECT * FROM salset";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        $con = true;
    } else {
        $con = false;
    }
    $intrec = gethook("accnum", "salacc", "name", "interestreceived");
    $uifbal = gethook("accnum", "salacc", "name", "uifbal");
    $sdlbal = gethook("accnum", "salacc", "name", "sdlbal");
    $pa = gethook("accnum", "salacc", "name", "pension");
    $ma = gethook("accnum", "salacc", "name", "medical");
    $cash_account = gethook("accnum", "salacc", "name", "cash");
    $retire = gethook("accnum", "salacc", "name", "retire");
    $provident = gethook("accnum", "salacc", "name", "provident");
    $salconacc = gethook("accnum", "salacc", "name", "salaries control");
    $commacc = gethook("accnum", "salacc", "name", "Commission");
    $abonusacc = gethook("accnum", "salacc", "name", "Bonus");
    $payeacc = gethook("accnum", "salacc", "name", "PAYE");
    $uifacc = gethook("accnum", "salacc", "name", "UIF");
    $providente = $myEmp["expacc_provident"];
    $retiree = $myEmp["expacc_ret"];
    $pax = $myEmp["expacc_pension"];
    $uifexp = $myEmp["expacc_uif"];
    $max = $myEmp["expacc_medical"];
    $dedgenerale = $myEmp["expacc_other"];
    $sdlexp = $myEmp["expacc_sdl"];
    $salacc = $myEmp["expacc_salwages"];
    $loanexp = $myEmp["expacc_loan"];
    $reimbursexp = $myEmp["expacc_reimburs"];
    if ($con) {
        $uifexp = $salacc;
        $sdlexp = $salacc;
        $pax = $salacc;
        $max = $salacc;
        $retiree = $salacc;
    }
    // Get Bank account [the traditional way re: hook of hook]
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accid}' AND div = '" . USER_DIV . "'";
    $Rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($Rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.";
    }
    $bank = pg_fetch_array($Rslt);
    $refnum = getrefnum($date);
    # Debit uif acc and credit uif control acc
    if ($comp_uif > 0) {
        writetrans($uifexp, $uifbal, $date, $refnum, $comp_uif, "Company UIF Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_uif > 0) {
        db_conn("cubit");
        $Sl = "UPDATE employees SET balance=balance-({$emp_uif}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $uifacc, $date, $refnum, "UIF", $emp_uif, "d");
        writetrans($salconacc, $uifbal, $date, $refnum, $emp_uif, "Employee UIF Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    # Debit uif sdl and credit sdl control acc
    writetrans($sdlexp, $sdlbal, $date, $refnum, $sdl, "SDL,  {$myEmp['fnames']} {$myEmp['sname']}.");
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    db_conn('cubit');
    $Sl = "UPDATE employees SET balance=balance+({$grossal_nodedall}) WHERE empnum = '{$empnum}'";
    $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
    empledger($empnum, $salacc, $date, $refnum, "Gross Salary", $grossal_nodedall, "c");
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    # Debit salaries acc and credit salaries control acc
    writetrans($salacc, $salconacc, $date, $refnum, $grossal_nodedall, "Gross Salary proccessing for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    if ($commission > 0) {
        if ($con) {
            $commacc = $salacc;
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance+({$commission}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $commacc, $date, $refnum, "Commission", $commission, "c");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit commission acc and credit salaries control acc
        writetrans($commacc, $salconacc, $date, $refnum, $commission, "Commission for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($abonus > 0) {
        if ($con) {
            $abonusacc = $salacc;
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance+({$abonus}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $abonusacc, $date, $refnum, "Bonus", $abonus, "c");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit bonus acc and credit salaries control acc
        writetrans($abonusacc, $salconacc, $date, $refnum, $abonus, "Bonus for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($paye > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paye}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $payeacc, $date, $refnum, "PAYE", $paye, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit salaries control acc and credit PAYE control acc
        writetrans($salconacc, $payeacc, $date, $refnum, $paye, "PAYE for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    db_conn('cubit');
    # Pay allowances accounts
    if (isset($allowid)) {
        foreach ($allowid as $i => $id) {
            # Debit allowances acc and credit salaries control acc
            if ($con) {
                $allowaccs[$i] = $salacc;
            }
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance+({$allowances[$i]}) WHERE empnum = '{$empnum}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($empnum, $allowaccs[$i], $date, $refnum, "Allowance", $allowances[$i], "c");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($allowaccs[$i], $salconacc, $date, $refnum, $allowances[$i], "Allowances for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
        }
    }
    # Pay Deductions accounts
    if (isset($deductid)) {
        foreach ($deductid as $i => $id) {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance-({$deductions[$i]}) WHERE empnum = '{$empnum}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($empnum, $dedaccs[$i], $date, $refnum, "Deduction", $deductions[$i], "d");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            # Debit salaries control acc and credit  acc
            // salcon acc - ded balance acc
            writetrans($salconacc, $dedaccs[$i], $date, $refnum, $deductions[$i], "Deductions for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
            db_conn("cubit");
            $sql = "SELECT * FROM salded WHERE id='{$id}'";
            $rslt = db_exec($sql) or errDie("Error reading deduction information.");
            $dedinfo = pg_fetch_array($rslt);
        }
    }
    if ($comp_pension > 0) {
        writetrans($pax, $pa, $date, $refnum, $comp_pension, "Company Pension Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_pension > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_pension}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $pa, $date, $refnum, "Pension Contribution", $emp_pension, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $pa, $date, $refnum, $emp_pension, "Pension Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($comp_medical > 0) {
        writetrans($max, $ma, $date, $refnum, $comp_medical, "Company Medical Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_medical > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_medical}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $ma, $date, $refnum, "Medical Contribution", $emp_medical, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $ma, $date, $refnum, $emp_medical, "Employee Medical Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($comp_provident > 0) {
        writetrans($providente, $provident, $date, $refnum, $comp_provident, "Company Provident Fund Contribution, {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_provident > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_provident}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $provident, $date, $refnum, "Provident Fund Contribution", $emp_provident, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $provident, $date, $refnum, $emp_provident, "Provident Fund Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if (false && $comp_other > 0) {
        writetrans($dedgenerale, $dedgeneral, $date, $refnum, $comp_other, "Company Contribution to Other Deductions, {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if (false && $emp_other > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_other}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $dedgeneral, $date, $refnum, "Other Deductions Contribution", $emp_other, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $dedgeneral, $date, $refnum, $emp_other, "Other Deductions Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_ret > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_ret}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $retire, $date, $refnum, "Retirement Annuity Contribution", $emp_ret, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $retire, $date, $refnum, $emp_ret, "Employee Retirement Annuity Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($comp_ret > 0) {
        writetrans($retiree, $retire, $date, $refnum, $comp_ret, "Company Retirement Annuity Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    db_conn('cubit');
    $mons = "{$mon};";
    $due = sprint($nettpay - $paidamount);
    //, balance=balance+'$due
    $sql = "\n\t\tUPDATE employees \n\t\tSET lastpay = '{$mons}', loanamt = (loanamt - cast(float '{$loaninstall}' as numeric)), \n\t\t\tloanfringe = (loanfringe - cast(float '{$fringe_loan}' as numeric)) \n\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to get employee details.");
    // check if loan is 0, then unmark loan as active, and store in archive
    $sql = "SELECT loanid FROM employees WHERE loanamt=0 AND empnum='{$empnum}' AND gotloan='t'::bool";
    $rslt = db_exec($sql) or errDie("Error reading employee details for loan.");
    if (pg_num_rows($rslt) > 0) {
        $loanid = pg_fetch_result($rslt, 0, 0);
        $sql = "UPDATE employees SET gotloan='f'::bool, loaninstall='0' WHERE empnum='{$empnum}'";
        $rslt = db_exec($sql) or errDie("Unable to update employee loan status.");
        $sql = "UPDATE emp_loanarchive SET donedata=CURRENT_DATE WHERE id='{$loanid}'";
        $rslt = db_exec($sql) or errDie("Unable to archive loan.");
        $sql = "SELECT loanint_unpaid FROM employees WHERE empnum='{$empnum}'";
        $rslt = db_exec($sql) or errDie("Error reading loan interest for installment.");
        $loanint = sprint(pg_fetch_result($rslt, 0, 0));
    } else {
        if ($loaninstall > 0) {
            $sql = "SELECT loanamt_tot, loanint_amt FROM employees WHERE empnum='{$empnum}'";
            $rslt = db_exec($sql) or errDie("Error reading loan interest for installment.");
            $loan_tot = pg_fetch_result($rslt, 0, 0);
            $loan_totint = pg_fetch_result($rslt, 0, 1);
            $loanint = sprint($loaninstall / $loan_tot * $loan_totint);
        } else {
            $loanint = 0;
        }
    }
    $sql = "\n\t\tUPDATE employees \n\t\tSET loanint_unpaid = (loanint_unpaid - cast(float '{$loanint}' as numeric)) \n\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update employee interest.");
    if ($loaninstall > 0 && !empty($loanexp)) {
        $loaninstall += 0;
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$loaninstall}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $loanexp, $date, $refnum, "Loan Instalment", $loaninstall, "d");
        # Debit salaries control acc and credit loan control acc
        writetrans($salconacc, $loanexp, $date, $refnum, $loaninstall - $loanint, "Loan Installment for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
        writetrans($salconacc, $intrec, $date, $refnum, $loanint, "Loan Interest for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
        /* record this month's loan amounts (for reversal purposes) */
        // determine the salary period
        switch ($myEmp["payprd"]) {
            case "d":
                $lprd = date_part($pdate, DP_DAY);
                break;
            case "m":
            case "f":
            case "w":
            default:
                $lprd = $week;
                break;
        }
        // record it!
        db_conn("cubit");
        $sql = "\n\t\t\tINSERT INTO emp_loaninstallments (\n\t\t\t\tempnum, fdate, fperiod, fmonth, fyear, installment, interest, fringe\n\t\t\t) VALUES (\n\t\t\t\t'{$empnum}', '{$date}', '{$lprd}', '{$mon}', '" . EMP_YEAR . "', '{$loaninstall}', '{$loanint}', '{$fringe_loan}'\n\t\t\t)";
        $rslt = db_exec($sql) or errDie("Error record loan fringe benefit.");
    }
    $loaninstall = $loaninstall + 0;
    $totded = sprint($de_beforeamount + $de_afteramount + $emp_pension + $emp_medical + $emp_provident + $emp_ret + $emp_other);
    $totded_employer = sprint($de_beforeamount_emp + $de_afteramount_emp + $comp_pension + $comp_medical + $comp_provident + $comp_ret + $comp_other);
    $totall = sprint($all_beforeamount + $all_afteramount + $all_travel);
    $parkage = "\n\t\t<br><br>\n\t\t<center>\n\t\t{$cc}\n\t\t<table border=2 cellpadding='4' cellspacing='0' width='750' bordercolor='#000000'>\n\t\t\t<tr>\n\t\t\t\t<td align='center'><b>Description</b></td>\n\t\t\t\t<td width='100' align='center'><b>Amount</b></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>Basic salary</td>\n\t\t\t\t<td align='right'>" . CUR . " {$basic_sal}</td>\n\t\t\t</tr>\n\t\t\t{$comDis}\n\t\t\t{$aboDis}\n\t\t\t{$fringes_desc}\n\t\t\t{$all_before}\n\t\t\t{$de_before}\n\t\t\t{$groDis}\n\t\t\t{$talDis}\n\t\t\t<tr>\n\t\t\t\t<td>UIF</td>\n\t\t\t\t<td align='right'>" . CUR . " {$emp_uif}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>PAYE</td>\n\t\t\t\t<td align='right'>" . CUR . " {$paye}</td>\n\t\t\t</tr>\n\t\t\t{$loaDis}\n\t\t\t{$all_after}\n\t\t\t{$de_after}\n\t\t\t<tr>\n\t\t\t\t<td><b>Nett Pay</b></td>\n\t\t\t\t<td align='right'><b>" . CUR . " {$nettpay}</b></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>\n\t\t</center>";
    $parkagesave = "\n\t\t<br><br>\n\t\t<center>\n\t\t<table border='2' width='750' border=2 cellpadding='4' cellspacing='0' bordercolor='#000000'>\n\t\t\t<tr>\n\t\t\t\t<td align='center'><b>Description</b></td>\n\t\t\t\t<td width='100' align='center'><b>Amount</b></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>Basic salary</td>\n\t\t\t\t<td align='right'>" . CUR . " {$basic_sal}</td>\n\t\t\t</tr>\n\t\t\t{$comDis}\n\t\t\t{$aboDis}\n\t\t\t{$fringes_desc}\n\t\t\t{$all_before}\n\t\t\t{$de_before}\n\t\t\t{$groDis}\n\t\t\t{$talDis}\n\t\t\t<tr>\n\t\t\t\t<td>UIF</td>\n\t\t\t\t<td align='right'>" . CUR . " {$emp_uif}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>PAYE</td>\n\t\t\t\t<td align='right'>" . CUR . " {$paye}</td>\n\t\t\t</tr>\n\t\t\t{$loaDis}\n\t\t\t{$all_after}\n\t\t\t{$de_after}\n\t\t\t<tr>\n\t\t\t\t<td><b>Nett Pay</b></td>\n\t\t\t\t<td align='right'><b>" . CUR . " {$nettpay}</b></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>\n\t\t</center>";
    $OUTPUT = $parkage;
    $save = base64_encode($parkagesave);
    $Date = $date;
    $np = $nettpay;
    if (isset($rbsa)) {
        $np = sprint($np - array_sum($rbsa));
    }
    /* hack to store the pay date for dailies */
    if ($myEmp["payprd"] == "d") {
        $week = $pday;
    }
    if (empty($novert)) {
        $novert = "0";
    }
    if (empty($hovert)) {
        $hovert = "0";
    }
    db_conn("cubit");
    $sql = "\n   \t\tINSERT INTO cubit.salpaid (\n   \t\t\tempnum, month, bankid, salary, comm, uifperc, uif, payeperc, paye, totded, totded_employer, \n\t\t\ttotallow, loanins, tot_fringe, div, display, saldate, week, cyear, novert, \n   \t\t\thovert, taxed_sal, hours, salrate, bonus\n   \t\t) VALUES (\n   \t\t\t'{$empnum}', '{$mon}', '{$accid}', '{$np}', '{$commission}', '0', '{$emp_uif}', '0', '{$paye}', '{$totded}', '{$totded_employer}', \n\t\t\t'{$totall}', '{$loaninstall}', '{$fringe_tot}', '" . USER_DIV . "', '{$save}', '{$Date}', '{$week}', '" . EMP_YEAR . "', '{$novert}', \n   \t\t\t'{$hovert}', '{$paye_salary}', '{$multi}', '{$basic_sal_save}', '{$abonus}'\n   \t\t)";
    $Ry = db_exec($sql) or errDie("Unable to insert record.");
    $id = pglib_lastid("salpaid", "id");
    $year = $year;
    $payslip_id = $id;
    db_conn("cubit");
    $Sl = "SELECT * FROM cubit.rbs ORDER BY name";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    $i = 0;
    if (pg_num_rows($Ri) > 0) {
        while ($td = pg_fetch_array($Ri)) {
            if (!isset($rbsa[$td['id']]) || $rbsa[$td['id']] < 1) {
                continue;
            }
            $rb = sprint($rbsa[$td['id']]);
            db_conn("cubit");
            $sql = "\n\t\t\t\tINSERT INTO emp_inc (\n\t\t\t\t\temp, year, period, date, week, payslip, type, code, description, \n\t\t\t\t\tqty, rate, amount, ex\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$Date}', '{$week}', '{$payslip_id}', '{$td['id']}', '', '{$td['name']}', \n\t\t\t\t\t'1', '0', '{$rb}', 'RBS'\n\t\t\t\t)";
            db_exec($sql) or errDie("unable to insert data.");
            $sql = "UPDATE employees SET balance=balance+({$rb}) WHERE empnum = '{$empnum}'";
            db_exec($sql) or errDie("Unable to get employee details.");
            empledger($empnum, $td['account'], $date, $refnum, "Reimbursement", $rb, "c");
            writetrans($td['account'], $salconacc, $date, $refnum, $rb, "Reimbursement for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
        }
    }
    if (isset($subsname)) {
        foreach ($subsname as $sid => $sn) {
            if (empty($subsamt[$sid]) || $subsamt[$sid] <= 0) {
                continue;
            }
            $samt = sprint($subsamt[$sid]);
            $i++;
            db_conn('cubit');
            $cols = grp(m("emp", $empnum), m("year", EMP_YEAR), m("period", $mon), m("week", $week), m("date", $Date), m("payslip", $payslip_id), m("type", $sid), m("code", ""), m("description", $subsname[$sid]), m("qty", 1), m("rate", 0), m("amount", $samt), m("ex", "SUBS"));
            $subin = new dbUpdate("emp_inc", "cubit", $cols);
            $subin->run(DB_INSERT);
            $cols = grp(m("balance", raw("balance+({$samt})")));
            $subin->setTable("employees");
            $subin->setOpt($cols, wgrp(m("empnum", $empnum)));
            $subin->run(DB_UPDATE);
            empledger($empnum, $subsacc[$sid], $date, $refnum, "Subsistence Allowance: {$subsname[$sid]}", $samt, "c");
            writetrans($subsacc[$sid], $salconacc, $date, $refnum, $samt, "Subsistence Allownace ({$subsname[$sid]}) for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
        }
    }
    if ($myEmp['paytype'] == "Cash") {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paidamount}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $cash_account, $date, $refnum, "Payment(Cash)", $paidamount, "d");
        writetrans($salconacc, $cash_account, $date, $refnum, $paidamount, "Salary Payment(Cash) for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    } elseif ($myEmp['paytype'] == "Ledger Account") {
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paidamount}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $account, $date, $refnum, "Payment(Ledger Account)", $paidamount, "d");
        writetrans($salconacc, $account, $date, $refnum, $paidamount, "Salary Payment(Ledger Account) for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    } else {
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paidamount}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $bankacc, $date, $refnum, "Payment(Bank)", $paidamount, "d");
        writetrans($salconacc, $bankacc, $date, $refnum, $paidamount, "Salary Payment for employee(Bank),  {$myEmp['fnames']} {$myEmp['sname']}.");
        # issue bank record
        banktrans($accid, "withdrawal", $date, "{$myEmp['fnames']} {$myEmp['sname']}", "Salary Payment for employee,  {$myEmp['fnames']} {$myEmp['sname']}", 0, $paidamount, $salconacc, $myEmp['empnum']);
    }
    db_conn('cubit');
    /*
    	writetrans($uifexp,$uifbal , $date, $refnum, $uif, "Company UIF Contribution,  $myEmp[fnames] $myEmp[sname].");
    */
    # Debit uif sdl and credit sdl control acc
    //	writetrans($sdlexp,$sdlbal , $date, $refnum, $sdl, "SDL,  $myEmp[fnames] $myEmp[sname].");
    db_conn("cubit");
    if ($comp_uif > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'UIFC', '', 'UIF', '1', '0','{$comp_uif}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data1.");
    }
    if ($emp_uif > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'UIFE', '', 'UIF', '1', '0', '{$emp_uif}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data3.");
    }
    if ($sdl > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'SDL', '', 'SDL', '1', '0', '{$sdl}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data2.");
    }
    if ($paye > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'PAYE', '', 'PAYE', '1', '0', '{$paye}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data3.");
    }
    if ($basic_sal > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INC', '', 'Basic Salary', '', '1', '0', '{$basic_sal}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data4.");
    }
    if ($myEmp["loanpayslip"] > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'LOAN', '', 'Employee Loan', '', '1', '0', '{$myEmp['loanpayslip']}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert loan data for employee income on payslip.");
        $sql = "UPDATE employees SET loanpayslip='0' WHERE empnum='{$empnum}'";
        $rslt = db_exec($sql) or errDie("Error updating loan information for payslip.");
    }
    if ($bonus > 0 && $myEmp["payprd"] != "f" && $myEmp["payprd"] != "w") {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCB', '', 'Bonus', '', '1', '0', '{$bonus}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data5.");
    } else {
        if ($bonus > 0) {
            $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCB', '', 'Special Bonus/Additional Salary', '', '1', '0', '{$bonus}', '')";
            $Ri = db_exec($Sl) or errDie("unable to insert data5.");
        }
    }
    if ($annual > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCAB', '', 'Annual Bonus', '', '1', '0', '{$annual}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data5.");
    }
    if ($commission > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCC', '', 'Commission', '', '1', '0', '{$commission}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data6.");
    }
    if ($abonus > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCAB', '', 'Bonus', '', '1', '0', '{$abonus}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data6.");
    }
    if ($all_travel > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCT', '', 'Travel Allowance', '', '1', '0', '{$all_travel}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data7.");
    }
    if ($loaninstall > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDL', '', 'Loan Repayment', '1', '0', '{$loaninstall}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data8.");
    }
    if ($comp_pension > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'COMP', '', 'Pension', '1', '0', '{$comp_pension}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_pension > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDP', '', 'Pension', '1', '0', '{$emp_pension}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($comp_ret > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'COMR', '', 'Retirement Annuity Fund', '1', '0', '{$comp_ret}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_ret > 0) {
        $Sl = "\n        \tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n        \tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDR', '', 'Retirement Annuity Fund', '1', '0', '{$emp_ret}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($myEmp["fringe_car1_contrib"] > 0) {
        $Sl = "\n        \tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n        \tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDA', '', 'Motorcar 1 Contribution for Use', '1', '0', '{$myEmp['fringe_car1_contrib']}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($myEmp["fringe_car2_contrib"] > 0) {
        $Sl = "\n        \tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n        \tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDB', '', 'Motorcar 2 Contribution for Use', '1', '0', '{$myEmp['fringe_car2_contrib']}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($comp_medical > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'COMM', '', 'Medical Contribution', '1', '0', '{$comp_medical}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data.11");
    }
    if ($emp_medical > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDM', '', 'Medical Contribution', '1', '0', '{$emp_medical}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data.12");
    }
    if ($comp_provident > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'COMV', '', 'Provident', '1', '0', '{$comp_provident}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_provident > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDV', '', 'Provident', '1', '0', '{$emp_provident}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($comp_other > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'COMO', '', 'Other Deductions', '1', '0', '{$comp_other}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_other > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDO', '', 'Other Deductions', '1', '0', '{$emp_other}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($overamt > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCO', '', 'Over Time', '1', '0', '{$overamt}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data.13");
    }
    $payslip_id = $id;
    // fringe benefits
    $frinupd = new dbUpdate("emp_frin", "cubit");
    if (isset($fringebens)) {
        foreach ($fringebens as $key => $value) {
            $cols = grp(m("emp", $empnum), m("year", EMP_YEAR), m("period", $mon), m("week", $week), m("fdate", $Date), m("payslip", $payslip_id), m("code", $key), m("description", $fringename[$key]), m("qty", 1), m("amount", sprint($fringebens[$key])));
            $frinupd->setCols($cols);
            $frinupd->run(DB_INSERT);
        }
    }
    if ($fringe_loan > 0) {
        $cols = grp(m("emp", $empnum), m("year", $year), m("period", $mon), m("fdate", $Date), m("payslip", $payslip_id), m("code", "FRINLOAN"), m("description", "Loan Fringe Benefit"), m("qty", 1), m("amount", $fringe_loan));
        $frinupd->setCols($cols);
        $frinupd->run(DB_INSERT);
    }
    if ($fringe_medical > 0) {
        $cols = grp(m("emp", $empnum), m("year", $year), m("period", $mon), m("fdate", $Date), m("payslip", $payslip_id), m("code", "FRINMED"), m("description", "Medical Fringe Benefit"), m("qty", 1), m("amount", $fringe_medical));
        $frinupd->setCols($cols);
        $frinupd->run(DB_INSERT);
    }
    if ($fringe_car1 > 0) {
        $cols = grp(m("emp", $empnum), m("year", $year), m("period", $mon), m("fdate", $Date), m("payslip", $payslip_id), m("code", "FRINCAR1"), m("description", "Fringe Benefit: Vehicle 1"), m("qty", 1), m("amount", $fringe_car1));
        $frinupd->setCols($cols);
        $frinupd->run(DB_INSERT);
    }
    if ($fringe_car2 > 0) {
        $cols = grp(m("emp", $empnum), m("year", $year), m("period", $mon), m("fdate", $Date), m("payslip", $payslip_id), m("code", "FRINCAR2"), m("description", "Fringe Benefit: Vehicle 2"), m("qty", 1), m("amount", $fringe_car2));
        $frinupd->setCols($cols);
        $frinupd->run(DB_INSERT);
    }
    if (isset($allowid)) {
        $Sl = "SELECT id,allowance FROM allowances";
        $Ri = db_exec($Sl) or errDie("Unable to get allowances.");
        while ($data = pg_fetch_array($Ri)) {
            $allname[$data['id']] = $data['allowance'];
        }
        foreach ($allowid as $i => $id) {
            $aname = $allname[$allowid[$i]];
            if (($allowances[$i] = sprint($allowances[$i])) <= 0) {
                continue;
            }
            $Sl = "\n\t\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount, ex)\n\t\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$payslip_id}', '{$allowid[$i]}', '', '{$aname}', '1', '0', '{$allowances[$i]}', '')";
            $Ri = db_exec($Sl) or errDie("unable to insert data.");
        }
    }
    # Pay Deductions accounts
    if (isset($deductid)) {
        $Sl = "SELECT id,deduction FROM salded";
        $Ri = db_exec($Sl) or errDie("Unabel to get get dat.");
        while ($data = pg_fetch_array($Ri)) {
            $dnames[$data['id']] = $data['deduction'];
        }
        foreach ($deductid as $i => $id) {
            $dname = $dnames[$deductid[$i]];
            # Debit salaries control acc and credit  acc
            if (($deductions[$i] = sprint($deductions[$i])) > 0) {
                $Sl = "\n\t\t\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$payslip_id}', '{$deductid[$i]}', '', '{$dname}', '1', '0', '{$deductions[$i]}')";
                $Ri = db_exec($Sl) or errDie("unable to insert data.");
            }
            if (($employer_deductions[$i] = sprint($employer_deductions[$i])) > 0) {
                $Sl = "\n\t\t\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$payslip_id}', '{$deductid[$i]}', '', '{$dname}', '1', '0', '{$employer_deductions[$i]}')";
                //$Ri=db_exec($Sl) or errDie("unable to insert data1.");
            }
        }
    }
    $id = $payslip_id;
    $ecost += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM empc WHERE emp='{$empnum}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        while ($data = pg_fetch_array($Ri)) {
            db_conn('cubit');
            $sql = "SELECT * FROM costcenters WHERE ccid = '{$data['cid']}'";
            $ccRslt = db_exec($sql) or errDie("Unable to retrieve Cost centers from database.");
            $cc = pg_fetch_array($ccRslt);
            $amount = sprint($ecost * $data['amount'] / 100);
            db_conn(PRD_DB);
            $sql = "\n\t\t\t\tINSERT INTO cctran (\n\t\t\t\t\tccid, trantype, typename, edate, \n\t\t\t\t\tdescription, amount, username, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cc['ccid']}', 'ct', 'Salary', '{$Date}', \n\t\t\t\t\t'Salary for employee,  {$myEmp['fnames']} {$myEmp['sname']}', '{$amount}', '" . USER_NAME . "', '" . USER_DIV . "'\n\t\t\t\t)";
            $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
        }
    }
    /* update printslip setting */
    setCSetting("EMP_PRINTSLIP", $printslip);
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if ($printslip != "n") {
        $OUTPUT = "<script>printer('salwages/payslip-print.php?id={$id}');spmove('../main.php');</script>";
    } else {
        $OUTPUT = "\n\t\t\t<h3>Process Employee Salary</h3>\n\t\t\tSuccessfully processed salary.<br /><br />" . mkQuickLinks(ql("salaries-staff.php", "Process Employee Salary"), ql("../admin-employee-view.php", "View Employees/Process Salaries by Batch"), ql("../admin-employee-add.php", "Add New Employee"), ql("settings-acc-edit.php", "Salary Settings"));
    }
    //$OUTPUT .= "<script>move('../index-salaries.php');</script>";
    require "../template.php";
}
function update($_POST)
{
    extract($_POST);
    // Validate
    require_lib("validate");
    $v = new validate();
    if (isset($accid) && isset($category)) {
        $v->isOk($accid, "num", 1, 9, "Invalid account selection.");
        $v->isOk($category, "string", 1, 6, "Invalid category selection.");
    }
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return slct($confirm);
    }
    $key = strtolower($key);
    if ($key == "add" || $key == "select account") {
        // Make sure the account has not been added already
        db_conn("cubit");
        $sql = "SELECT * FROM saved_cf_accounts WHERE accid='{$accid}'";
        $cfacc_rslt = db_exec($sql) or errDie("Unable to retrieve account from the account list.");
        if (!pg_num_rows($cfacc_rslt)) {
            db_conn("cubit");
            $sql = "INSERT INTO saved_cf_accounts (accid, category) VALUES ('{$accid}', '{$category}')";
            $cfacc_rslt = db_exec($sql) or errDie("Unable to save account to the accounts list.");
        }
    }
    if ($key == "remove selected") {
        if (!isset($rem)) {
            $rem = array();
        }
        foreach ($rem as $id) {
            db_conn("cubit");
            $sql = "DELETE FROM saved_cf_accounts WHERE accid='{$id}'";
            $cfacc_rslt = db_exec($sql) or errDie("Unable to remove selected account from the accounts list.");
        }
    }
    if ($key == "default") {
        list($accid) = qryAccountsName("Depreciation", "accid");
        db_conn("cubit");
        $cols = grp(m("accid", $accid), m("category", "nciis"));
        $qry = new dbUpdate("saved_cf_accounts", "cubit", $cols);
        $qry->run(DB_INSERT);
        // add balance sheet items to list
        $qry = new dbQuery(DB_SQL, "INSERT INTO cubit.saved_cf_accounts (accid, category)\n\t\t\tSELECT accid, 'ciaal' FROM core.accounts WHERE catid='B10'");
        $qry->run();
        /*
        // Inventory
        db_conn("core");
        $sql = "SELECT accid FROM accounts WHERE accname='Inventory'";
        $rslt = db_exec($sql) or errDie("Unable to retrieve the inventory account.");
        $accid = pg_fetch_result($rslt, 0);
        
        db_conn("cubit");
        $sql = "INSERT INTO saved_cf_accounts (accid, category) VALUES ('$accid', 'ciaal')";
        $rslt = db_exec($sql) or errDie("Unable to add the inventory account.");
        
        // Accounts Receivable
        db_conn("core");
        $sql = "SELECT accid FROM accounts WHERE accname='Customer Control Account'";
        $rslt = db_exec($sql) or errDie("Unable to retrieve the accounts receivable account.");
        $accid = pg_fetch_result($rslt, 0);
        
        db_conn("cubit");
        $sql = "INSERT INTO saved_cf_accounts (accid, category) VALUES ('$accid', 'ciaal')";
        $rslt = db_exec($sql) or errDie("Unable to add the accounts receivable account.");
        */
    }
    return slct();
}
function 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()
{
    extract($_POST);
    if (isset($back)) {
        return enter();
    }
    if ($err = validate($_POST)) {
        return enter($err);
    }
    /* check account number */
    if (!isset($cusnum)) {
        $qry = new dbSelect("customers", "cubit", grp(m("where", "accno='{$accno}' AND div='" . USER_DIV . "'")));
        $qry->run();
        if ($qry->num_rows() > 0) {
            return enter("<li class='err'>A Customer/Client with this account number already exists.</li>");
        }
    }
    $data = qryCategory($category);
    $catname = $data["category"];
    $data = qryClass($class);
    $classname = $data["classname"];
    $data = qryPricelist($pricelist);
    $plist = $data["listname"];
    $curr = getSymbol($fcid);
    $currency = $curr["symbol"];
    /* fix numerics */
    $traddisc += 0;
    $setdisc += 0;
    $pricelist += 0;
    $overdue += 0;
    $credterm += 0;
    $credlimit += 0;
    pglib_transaction("BEGIN");
    /* insert into database / update */
    $cols = grp(m("deptid", $deptid), m("accno", $accno), m("surname", $surname), m("title", $title), m("init", $init), m("location", $location), m("fcid", $fcid), m("currency", $currency), m("category", $category), m("class", $class), m("addr1", $addr1), m("paddr1", $paddr1), m("del_addr1", $del_addr1), m("vatnum", $vatnum), m("contname", $contname), m("bustel", $bustel), m("tel", $tel), m("cellno", $cellno), m("fax", $fax), m("email", $email), m("url", $url), m("traddisc", $traddisc), m("setdisc", $setdisc), m("pricelist", $pricelist), m("chrgint", $chrgint), m("overdue", $overdue), m("intrate", $intrate), m("chrgvat", "yes"), m("credterm", $credterm), m("odate", $odate), m("credlimit", $credlimit), m("blocked", "no"), m("deptname", $deptname), m("classname", $classname), m("catname", $catname), m("lead_source", $lead_source), m("comments", $comments), m("sales_rep", $sales_rep), m("div", USER_DIV), m("bankname", $bankname), m("branname", $branname), m("brancode", $brancode), m("bankaccname", $bankaccname), m("bankaccno", $bankaccno), m("bankacctype", $bankacctype), m("team_id", $team_id), m("registration", $registration));
    $where = wgrp(m("cusnum", isset($cusnum) ? $cusnum : 0));
    $qryi = new dbUpdate("customers", "cubit", $cols, $where);
    $qryi->run(DB_REPLACE);
    /* get id */
    if (!isset($cusnum)) {
        $cusnum = pglib_lastid("customers", "cusnum");
        $newcust = true;
        // used later to check if we should create the ledgers
    }
    /* add to/update contact list */
    $cols = grp(m("surname", $surname), m("title", $title), m("ref", "Customer"), m("tell", $tel), m("tell_office", $bustel), m("cell", $cellno), m("fax", $fax), m("email", $email), m("hadd", $addr1), m("padd", $paddr1), m("del_addr", $del_addr1), m("date", $odate), m("cust_id", $cusnum), m("con", "No"), m("lead_source", $lead_source), m("description", $comments), m("account_type", "Customer"), m("accountname", $surname), m("account_id", $cusnum), m("by", USER_NAME), m("div", USER_DIV));
    $where = wgrp(m("cust_id", $cusnum));
    $qryi->setTable("cons", "cubit");
    $qryi->setOpt($cols, $where);
    $qryi->run(DB_REPLACE);
    if (PRD_STATE == "py") {
        $audit_db = YR_NAME . "_audit";
        $actyear = PYR_NAME;
    } else {
        $audit_db = "audit";
        $actyear = YR_NAME;
    }
    if (isset($newcust)) {
        /* create customer ledgers */
        for ($i = 1; $i <= 12; ++$i) {
            /* period customer ledger */
            $cols = grp(m("cusnum", $cusnum), m("contra", 0), m("edate", $odate), m("sdate", raw("CURRENT_DATE")), m("eref", 0), m("descript", "Balance"), m("credit", 0), m("debit", 0), m("cbalance", 0), m("dbalance", 0), m("div", USER_DIV));
            $qryi->setTable("custledger", "{$i}");
            $qryi->setOpt($cols);
            $qryi->run(DB_INSERT);
            /* audit customer ledger */
            $cols = grp(m("cusnum", $cusnum), m("contra", 0), m("edate", $odate), m("sdate", raw("CURRENT_DATE")), m("eref", 0), m("descript", "Balance"), m("credit", 0), m("debit", 0), m("cbalance", 0), m("dbalance", 0), m("div", USER_DIV), m("actyear", $actyear));
            $qryi->setTable(getMonthName($i) . "_custledger", $audit_db);
            $qryi->setOpt($cols);
            $qryi->run(DB_INSERT);
        }
        if (isset($crm)) {
            header("Location: crm/tokens-new.php?value={$surname}");
            exit;
        }
        if ($re != "not") {
            $qryi->setTable("invoices", "cubit");
            $cols = grp(m("cusnum", $cusnum));
            $where = wgrp(m("invid", $re));
            $qryi->setOpt($cols, $where);
            $qryi->run(DB_UPDATE);
            header("Location: cust-credit-stockinv.php?invid={$re}&cont=1&letters=");
            exit;
        }
    }
    pglib_transaction("COMMIT") or errDie("Unable to add customer to database. (TC)");
    // Update documents
    $sql = "SELECT * FROM crm.ctmp_docs WHERE session='{$_REQUEST['CUBIT_SESSION']}'";
    $ctdoc_rslt = db_exec($sql) or errDie("Unable to retrieve docs.");
    while ($ctdoc_data = pg_fetch_array($ctdoc_rslt)) {
        $sql = "INSERT INTO crm.customer_docs (cusnum, file, type, filename, size)\n\t\tVALUES ('{$cusnum}', '{$ctdoc_data['file']}', '{$ctdoc_data['type']}',\n\t\t\t\t'{$ctdoc_data['filename']}', '{$ctdoc_data['size']}')";
        db_exec($sql) or errDie("Unable to save files to customer.");
        $sql = "DELETE FROM crm.ctmp_docs WHERE id='{$ctdoc_data['id']}'";
        db_exec($sql) or errDie("Unable to remove tmp file.");
    }
    $sql = "SELECT * FROM cubit.cons WHERE cust_id='{$cusnum}'";
    $con_rslt = db_exec($sql) or errDie("Unable to retrieve contact.");
    $con_data = pg_fetch_array($con_rslt);
    if (pg_num_rows($con_rslt)) {
        $con_out = "\n\t\t<a href='javascript:popupOpen(\"groupware/conper-add.php?type=conn&id={$con_data['id']}\")'>\n\t\t\tAdd Sub Contact\n\t\t</a>";
    } else {
        $con_out = "";
    }
    onthespot_declare();
    $OUT = "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th>Customer add/update successful.</th>\n\t</tr>\n\t<tr class='datacell'>\n\t\t<td>\n\t\t\tNew Customer <b>{$surname}</b>,\n\t\t\thas been successfully added to the system.\n\t\t\t{$con_out}</td>\n\t</tr>\n\t</table>";
    $OUT .= onthespot_out(mkQuickLinks(ql("customers-new.php", "Add Customers"), ql("customers-view.php", "View Customers")));
    return $OUT;
}
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($out, "float", 1, 40, "Invalid out amount.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 40, "Invalid amount.");
    $v->isOk($setamt, "float", 1, 40, "Invalid Settlement Amount.");
    $v->isOk($setvat, "string", 1, 10, "Invalid Settlement VAT Option.");
    $v->isOk($setvatcode, "string", 1, 40, "Invalid Settlement VAT code");
    $v->isOk($cusid, "num", 1, 40, "Invalid customer number.");
    $v->isOk($out1, "float", 0, 40, "Invalid paid amount(current).");
    $v->isOk($out2, "float", 0, 40, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 40, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 40, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 40, "Invalid paid amount(120).");
    $v->isOk($overpay, "float", 1, 20, "Invalid Overpay Amount.");
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No.");
            $v->isOk($paidamt[$key], "float", 1, 40, "Invalid amount to be paid.");
            $v->isOk($stock_setamt[$key], "float", 1, 40, "Invalid Settlement Discount Amount");
        }
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . confirm($_POST);
    }
    /* get bank account id of cash on hand account IF this entry is cash */
    if (($bank_acc = getbankaccid($bankid)) === false or $bankid == "0") {
        //old function didnt check if cash is selected ... if(($bank_acc = getbankaccid($bankid)) === false) {
        $sql = "SELECT accid FROM core.accounts WHERE accname='Cash on Hand'";
        $rslt = db_exec($sql);
        if (pg_num_rows($rslt) < 1) {
            if ($bankid == 0) {
                return "There is no 'Cash on Hand' account, there was one, but\n\t\t\t\t\t**s not there now, you must have deleted it, if you want\n\t\t\t\t\tto use cash functionality please create a 'Cash on Hand' account.";
            } else {
                return "Invalid bank acc.";
            }
        }
        $bank_acc = pg_fetch_result($rslt, 0);
    }
    $cus = qryCustomer($cusid, "cusnum, deptid, cusname, surname");
    $dept = qryDepartment($cus["deptid"], "debtacc");
    $refnum = getrefnum();
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # date format
    $sdate = explode("-", $date);
    $_SESSION["global_day"] = $sdate[2];
    $_SESSION["global_month"] = $sdate[1];
    $_SESSION["global_year"] = $sdate[0];
    //	$sdate = $sdate[2]."-".$sdate[1]."-".$sdate[0];
    $sdate = "{$date_year}-{$date_month}-{$date_day}";
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    //	$accdate = "$date_year-$date_month-$date_day";
    /* Paid invoices */
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    $rages = "";
    $setamts = "";
    #get settlement accid
    $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Debtors Settlement Discount'";
    $run_setacc = db_exec($get_setacc) or errDie("Unable to get settlement account information");
    $setaccid = pg_fetch_result($run_setacc, 0, 0);
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    $amt += $overpay;
    /* OPTION 3 : ALLOCATE TO EACH INVOICE (confirm) */
    if ($all == 2) {
        $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt}'::numeric(16,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                # some logic ...
                # because the customer account should be 0 when paid fully, we need
                # to also deduct the settlement amount ...
                $paidamt[$key] = $paidamt[$key] + $stock_setamt[$key];
                # with the amount added to the paid amount, we tract it using a new
                # seperate setamt db column
                if (!isset($itype[$key]) && !isset($ptype[$key])) {
                    $sql = "SELECT prd,invnum,odate FROM cubit.invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.invoices\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2))\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2))\n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, date, type, div, allocation_date, docref, \n\t\t\t\t\t\t\tallocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "', \n\t\t\t\t\t\t\t'{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}', '{$reference}', \n\t\t\t\t\t\t\t'" . abs($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, \n\t\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', \n\t\t\t\t\t\t\t\t'{$sdate}', 'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    #deduct setamt for records ...
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$key] - $stock_setamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    if ($inv['prd'] == "0") {
                        $inv['prd'] = PRD_DB;
                    }
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                } elseif (!isset($ptype[$key])) {
                    $sql = "\n\t\t\t\t\t\tSELECT prd,invnum,descrip,age,odate \n\t\t\t\t\t\tFROM cubit.nons_invoices \n\t\t\t\t\t\tWHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce the invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.nons_invoices \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    if (!isset($inv['odate']) or strlen($inv['odate']) < 1) {
                        $inv['odate'] = $sdate;
                    }
                    // add payment to statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, \n\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "', \n\t\t\t\t\t\t\t'{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', \n\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, \n\t\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', \n\t\t\t\t\t\t\t\t'{$sdate}', 'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                    db_connect();
                    //recordCT($paidamt[$key], $cus['cusnum'],$inv['age'],$accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                } else {
                    /* pos invoices */
                    $sqls = array();
                    for ($i = 1; $i <= 12; ++$i) {
                        $sqls[] = "\n\t\t\t\t\t\t\tSELECT '{$i}' AS prd,invid,invnum,odate \n\t\t\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\tWHERE invid='{$invids[$key]}' AND div='" . USER_DIV . "'";
                    }
                    $sql = implode(" UNION ", $sqls);
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce the invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE \"{$inv['prd']}\".pinvoices \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    // add payment to statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\ttype, div, \n\t\t\t\t\t\t\tallocation_date, docref, allocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($paidamt[$key] - $stock_setamt[$key]) * -1 . "', '{$sdate}', \n\t\t\t\t\t\t\t'Payment for POS Invoice No. {$inv['invnum']}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$inv['odate']}', '{$reference}', '" . abs(($paidamt[$key] - $stock_setamt[$key]) * -1) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\t\tamount, date, \n\t\t\t\t\t\t\t\ttype, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t\t'" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', '{$sdate}', \n\t\t\t\t\t\t\t\t'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for POS Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                    //recordCT($paidamt[$key], $cus['cusnum'],"0",$accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                }
            }
        }
        if (open()) {
            db_conn('cubit');
            $Sl = "SELECT * FROM cubit.open_stmnt WHERE balance>0 AND cusnum='{$cusid}' ORDER BY date";
            $Ri = db_exec($Sl) or errDie("Unable to get open items.");
            //$open_out=$out;
            $ox = "";
            $i = 0;
            while ($od = pg_fetch_array($Ri)) {
                $oid = $od['id'];
                if (!isset($open_amount[$oid]) || $open_amount[$oid] == 0) {
                    continue;
                }
                $ox .= "\n\t\t\t\t\t<input type='hidden' size='20' name='open[{$oid}]' value='{$oid}'>\n\t\t\t\t\t<input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t</tr>";
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$open_amount[$oid]} ::numeric(16,2)) \n\t\t\t\t\tWHERE id = '{$oid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                // record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date, docref, allocation_balance\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cus['cusnum']}', '0', '" . -$open_amount[$oid] . "', '{$sdate}', \n\t\t\t\t\t\t'Payment received', '" . USER_DIV . "', '{$accdate}', '{$reference}', '" . abs($open_amount[$oid]) . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank_acc, $sdate, 0, "Payment received", $open_amount[$oid], "c");
                recordCT($open_amount[$oid], $cus['cusnum'], 0, $accdate);
            }
        }
        // record the payment record
        $cols = grp(m("bankid", $bankid), m("trantype", "deposit"), m("date", $sdate), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheqnum), m("amount", $amt), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference), m("div", USER_DIV));
        $dbobj = new dbUpdate("cashbook", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        $cashbook_id = pglib_lastid("cashbook", "cashid");
        writetrans($bank_acc, $dept['debtacc'], $accdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
    }
    /* start moving invoices */
    // move invoices that are fully paid
    $sql = "SELECT * FROM cubit.invoices WHERE balance='0' AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    while ($x = pg_fetch_array($invbRslt)) {
        if (($prd = $x['prd']) == "0") {
            $prd = PRD_DB;
        }
        // move invoice
        $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
        $dbobj = new dbUpdate("invoices", $prd, $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        // record movement
        $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
        $dbobj->setTable("movinv", "cubit");
        $dbobj->setOpt($cols);
        $dbobj->run();
        $dbobj->free();
        // move invoice items
        $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
        $inv_items->run();
        while ($xi = $inv_items->fetch_array()) {
            $xi['vatcode'] += 0;
            $xi['account'] += 0;
            $xi['del'] += 0;
            $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
            $dbobj->setTable("inv_items", $prd);
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
        }
        /* remove invoice from cubit schema */
        $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
        $dbobj->run();
        $dbobj->setTable("inv_items", "cubit");
        $dbobj->run();
    }
    #do journal for the settlement discount here ... now ...
    if ($setamt > 0) {
        db_conn('core');
        #calculate the settlement vat ... and amt
        if (isset($setvat) and $setvat == 'inc') {
            db_connect();
            $get_vcode = "SELECT * FROM vatcodes WHERE id = '{$setvatcode}' LIMIT 1";
            $run_vcode = db_exec($get_vcode) or errDie("Unable to get vatcode informtion.");
            if (pg_numrows($run_vcode) < 1) {
                return "<li class='err'>Settlement Discount VAT Code Not Set.</li>";
            }
            $vd = pg_fetch_array($run_vcode);
            #vat inc ... recalculate the amts
            $setvatamt = sprint($setamt * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
            $setamt = sprint($setamt - $setvatamt);
            #process the vat amt ...
            writetrans($vatacc, $dept['debtacc'], $accdate, $refnum, $setvatamt, "VAT Received on Settlement Discount (Ref.{$refnum}) for Customer : {$cus['cusname']} {$cus['surname']}");
            vatr($vd['id'], $accdate, "OUTPUT", $vd['code'], $refnum, "VAT for Settlement Discount (Ref.{$refnum}) for Customer : {$cus['cusname']} {$cus['surname']}", ($setamt + $setvatamt) * -1, $setvatamt * -1);
        } else {
            #no vat for set amt ... do nothing
            $setvatamt = 0;
        }
        custledger($cus['cusnum'], $setaccid, $accdate, $refnum, "Settlement Discount (Ref.{$refnum})", $setamt + $setvatamt, "c");
        writetrans($setaccid, $dept['debtacc'], $accdate, $refnum, $setamt, "Settlement Discount (Ref.{$refnum}) For {$cus['cusname']} {$cus['surname']}");
        db_connect();
        #record this paid settlement discount for reporting ...
        $settl_sql = "\n\t\t\tINSERT INTO settlement_cus (\n\t\t\t\tcustomer, amt, setamt, setvatamt, setvat, setvatcode, tdate, sdate, refnum\n\t\t\t) VALUES (\n\t\t\t\t'{$cus['cusnum']}', '{$amt}', '{$setamt}', '{$setvatamt}', '{$setvat}', '{$setvatcode}', '{$accdate}', 'now', '{$refnum}'\n\t\t\t)";
        $run_settl = db_exec($settl_sql) or errDie("Unable to get debtor settlement information.");
    }
    //	$overpay = sprint ($amt - array_sum($paidamt));
    if (!isset($overpay) or $overpay < 0) {
        $overpay = 0.0;
    }
    if ($overpay > 0) {
        recordCT($overpay, $cus['cusnum'], 0, $accdate);
        $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$overpay), m("date", $sdate), m("type", "Payment Received (Receipt " . pglib_lastid("cashbook", "cashid") . ")"), m("div", USER_DIV), m("allocation_date", $accdate), m("docref", $reference));
        $dbobj = new dbUpdate("stmnt", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        custledger($cus['cusnum'], $bank_acc, $sdate, "PAYMENT", "Payment received.", $overpay, "c");
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // status report
    //	$write = "
    //				<table ".TMPL_tblDflts." width='100%'>
    //					<tr>
    //						<th>Bank Receipt</th>
    //					</tr>
    //					<tr class='".bg_class()."'>
    //						<td>Bank Receipt added to cash book.</td>
    //					</tr>
    //				</table>
    //			";
    //
    //	$OUTPUT = "<center>
    //        <table width='90%'>
    //        <tr valign='top'>
    //        	<td width='50%'>$write</td>
    //	        <td align='center'>"
    //				.mkQuickLinks(
    //					ql("bank-pay-add.php", "Add Bank Payment"),
    //					ql("bank-recpt-add.php", "Add Bank Receipt"),
    //					ql("bank-recpt-inv.php", "Add Customer Payment"),
    //					ql("cashbook-view.php", "View Cash Book")
    //				)."
    //			</td>
    //		</tr>
    //		</table>";
    //	return $OUTPUT;
    if (isset($print_recpt) and $print_recpt == "yes") {
        $showreceipt = "printer ('bank/bank-recpt-inv-print.php?recid={$cashbook_id}');";
    } else {
        $showreceipt = "";
    }
    return "\n\t\t<script>\n\t\t\tmove ('../customers-view.php?offset=0&fval=&filter=surname&nozerobal=yes');\n\t\t\t{$showreceipt}\n\t\t</script>";
}
function deny(&$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>");
    }
}
function save_sal($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    # Limit field lengths as per database settings
    $v->isOk($empnum, "string", 0, 20, "Invalid empnum.");
    $v->isOk($saltyp, "string", 1, 2, "Invalid salary type.");
    $v->isOk($paytype, "string", 1, 15, "Invalid pay type.");
    if (isset($allowances)) {
        foreach ($allowances as $key => $value) {
            $v->isOk($allowances[$key], "float", 0, 11, "Invalid allowance amount " . ($key + 1) . ".");
        }
    }
    if (isset($deductid)) {
        foreach ($deductid as $key => $value) {
            $v->isOk($deductid[$key], "num", 1, 9, "Invalid deductions ID.");
        }
    }
    if (isset($deductions)) {
        foreach ($deductions as $key => $value) {
            $v->isOk($deductions[$key], "float", 0, 11, "Invalid deduction amount" . ($key + 1) . ".");
        }
    }
    if (isset($allowid)) {
        foreach ($allowid as $key => $value) {
            $v->isOk($allowid[$key], "num", 1, 9, "Invalid allowance ID.");
        }
    }
    if (isset($allowtax)) {
        foreach ($allowtax as $key => $value) {
            $v->isOk($allowtax[$key], "string", 1, 13, "Invalid allowance tax option" . ($key + 1) . ".");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>{$e['msg']}</li>";
        }
        return "<li class='err'>{$confirmCust}</li>";
    }
    switch ($saltyp) {
        case "m":
            $sal_divisor = 12;
            break;
        case "f":
            $sal_divisor = 26;
            break;
        case "w":
            $sal_divisor = 52;
            break;
        case "h":
            $sal_divisor = 52 * $hpweek;
            break;
    }
    $basic_sal = sprint($basic_sal_annum / $sal_divisor);
    db_connect();
    $sql = "\n\t\tUPDATE employees \n\t\tSET basic_sal='{$basic_sal}', paytype='{$paytype}', payprd_day='{$payprd_day}', basic_sal_annum='{$basic_sal_annum}', \n\t\t\tsal_bonus='{$sal_bonus}', sal_bonus_month='{$sal_bonus_month}', all_travel='{$all_travel}', comp_uif='{$comp_uif}', \n\t\t\tcomp_sdl='{$comp_sdl}', emp_uif='{$emp_uif}', comp_pension='{$comp_pension}', emp_pension='{$emp_pension}', \n\t\t\tcomp_ret='{$comp_ret}', emp_ret='{$emp_ret}', comp_medical='{$comp_medical}', emp_medical='{$emp_medical}', \n\t\t\temp_meddeps='{$emp_meddeps}', comp_provident='{$comp_provident}', emp_provident='{$emp_provident}', \n\t\t\tcomp_other='{$comp_other}', emp_other='{$emp_other}', payprd='{$payprd}', saltyp='{$saltyp}', \n\t\t\tfringe_car1='{$fringe_car1}', fringe_car1_contrib='{$fringe_car1_contrib}', fringe_car1_fuel='{$fringe_car1_fuel}', \n\t\t\tfringe_car1_service='{$fringe_car1_service}', fringe_car2='{$fringe_car2}', \n\t\t\tfringe_car2_contrib='{$fringe_car2_contrib}', fringe_car2_fuel='{$fringe_car2_fuel}', \n\t\t\tfringe_car2_service='{$fringe_car2_service}', flag=NULL \n\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
    $nwEmpRslt = db_exec($sql) or errDie("Unable to update employee information.");
    if (isset($allowid)) {
        # Remove old details
        $sql = "DELETE FROM empallow WHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
        $allowRslt = db_exec($sql);
        # write Allowances to db
        foreach ($allowid as $i => $id) {
            if (empty($allowances[$i]) || $allowances[$i] == 0) {
                continue;
            }
            # Insert new records
            $allowances[$i] += 0;
            $allowances[$i] = sprint($allowances[$i]);
            $sql = "\n\t\t\t\tINSERT INTO empallow (\n\t\t\t\t\tallowid, empnum, type, amount, accid, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$id}', '{$empnum}', '{$allowtype[$i]}', '{$allowances[$i]}', '{$allowaccid[$i]}', '" . USER_DIV . "'\n\t\t\t\t)";
            $allowRslt = db_exec($sql) or errDie("Unable to process Employee allowances in database.");
        }
    }
    if (isset($subsname)) {
        $inssub = new dbUpdate("emp_subsistence", "cubit");
        foreach ($subsname as $sid => $sn) {
            $cols = grp(m("subid", $sid), m("empnum", $empnum), m("amount", $subsamt[$sid]), m("days", $subsdays[$sid]), m("accid", $subsacc[$sid]));
            $inssub->setOpt($cols, wgrp(m("subid", $sid), m("empnum", $empnum)));
            $inssub->run(DB_REPLACE);
        }
    }
    if (isset($deductid)) {
        # Remove old records
        $sql = "DELETE FROM empdeduct WHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
        $deductRslt = db_exec($sql);
        # write Deductions to db
        foreach ($deductid as $i => $id) {
            if (isset($ltsal_checked[$i])) {
                $ltsal = "y";
            } else {
                $ltsal = "n";
            }
            # Insert new records
            if (empty($deductions[$i]) || $deductions[$i] == 0) {
                continue;
            }
            if (empty($comp_deductions[$i])) {
                $comp_deductions[$i] = 0;
            }
            $deductions[$i] += 0;
            $deductions[$i] = sprint($deductions[$i]);
            $comp_deductions[$i] += 0;
            $sql = "\n\t\t\t\tINSERT INTO empdeduct (\n\t\t\t\t\tdedid, empnum, amount, employer_amount, div, type, \n\t\t\t\t\temployer_type, grosdeduct, accid\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$id}', '{$empnum}', '{$deductions[$i]}', '{$comp_deductions[$i]}', '" . USER_DIV . "','{$deducttype[$i]}', \n\t\t\t\t\t'{$deducttype[$i]}', '{$ltsal}', '{$deductaccid[$i]}'\n\t\t\t\t)";
            $deductRslt = db_exec($sql) or errDie("Unable to process Employee deductions in database.");
        }
    }
    if (isset($fringebens)) {
        $sql = "DELETE FROM empfringe WHERE empnum='{$empnum}' AND div='" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Error updating fringe benefits (DEL).");
        foreach ($fringeid as $i => $id) {
            if (empty($fringebens[$i]) || $fringebens[$i] == 0) {
                continue;
            }
            $fringebens[$i] += 0;
            $sql = "\n\t\t\t\tINSERT INTO empfringe (\n\t\t\t\t\tfringeid, empnum, amount, type, accid, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$id}', '{$empnum}', '{$fringebens[$i]}', '{$fringetype[$i]}', '{$fringeexpacc[$i]}', '" . USER_DIV . "'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Error updating fringe benefits (INS#{$id}).");
        }
    }
    //				<script>
    //					parent.opener.location.reload();
    //				</script>
    $display = "\n\t\t<script>\n\t\t\tparent.opener.document.form1.submit();\n\t\t\twindow.close();\n\t\t</script>";
    return $display;
}
function write()
{
    extract($_POST);
    if (isset($back)) {
        return add($_POST);
    }
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    $bank = qryBankAcct($bankid);
    $cols = grp(m("type", "Banking Details Account"), m("label", "BANK_DET"), m("value", $bankid), m("descript", "Bank Account: ({$bank['acctype']}) {$bank['accname']} - {$bank['bankname']}"), m("div", USER_DIV));
    $qry = new dbUpdate("set", "cubit", $cols, "label = 'BANK_DET' AND div = '" . USER_DIV . "'");
    $qry->run(DB_REPLACE);
    $write = "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th>Bank Details Account</th>\n\t</tr>\n\t<tr class='text'>\n\t\t<td>Bank Details Account have been set to Bank Account: ({$bank['acctype']}) {$bank['accname']} - {$bank['bankname']}.</td>\n\t</tr>\n\t</table>" . mkQuickLinks();
    return $write;
}
function import($frm)
{
    /* @var $frm cForm */
    if ($frm->validate("import")) {
        return view($frm);
    }
    /* get field indexes */
    $stkcod = false;
    $price = false;
    foreach ($_REQUEST["fld"] as $fi => $ft) {
        if ($ft != "ignore") {
            ${$ft} = $fi;
        }
    }
    /* import file if all field types specified */
    if ($stkcod === false || $price === false) {
        $frm->setmsg("<li class='err'>Not all field types satisfied</li>");
    } else {
        $qry = new dbSelect("spricelist", "exten", grp(m("cols", "listid"), m("where", "suppid='{$_REQUEST['supid']}'")));
        $qry->run();
        if ($qry->num_rows() <= 0) {
            $suppinfo = qrySupplier($_REQUEST["supid"]);
            $cols = grp(m("suppid", $_REQUEST["supid"]), m("listname", $suppinfo["supname"]), m("div", USER_DIV));
            $upd = new dbUpdate("spricelist", "exten", $cols);
            $upd->run(DB_INSERT);
            $listid = $upd->lastid("listid");
        } else {
            $listid = $qry->fetch_result();
        }
        $upd = new dbDelete("splist_prices", "exten", "listid='{$listid}'");
        $upd->run();
        $upd = new dbUpdate("splist_prices", "exten");
        $invalid_fields = array();
        $nosuch_fields = array();
        $file = ucfs::file("supplist");
        foreach ($file as $rd) {
            $ri = explode(",", $rd);
            $ri[$stkcod] = trim($ri[$stkcod]);
            $ri[$price] = trim($ri[$price]);
            if (cForm::validateValue($ri[$stkcod], "string", 1, 250) || cForm::validateValue($ri[$price], "float", 1, 40)) {
                $invalid_fields[] = $ri[$stkcod];
                continue;
            }
            $stkid = suppStkid($_REQUEST["supid"], $ri[$stkcod]);
            if ($stkid === false) {
                $stkinfo = array("stkid" => "0", "catid" => "0", "prdcls" => "0");
            } else {
                $stkinfo = qryStock($stkid, "stkid, catid, prdcls");
            }
            if (!isset($_REQUEST["vatinc"])) {
                $ri[$price] += $ri[$price] * TAX_VAT / 100;
            }
            $cols = grp(m("listid", $listid), m("stkid", $stkinfo["stkid"]), m("catid", $stkinfo["catid"]), m("clasid", $stkinfo["prdcls"]), m("price", $ri[$price]), m("div", USER_DIV), m("supstkcod", $ri[$stkcod]));
            $upd->setCols($cols);
            $upd->run();
        }
        if (count($invalid_fields) > 0) {
            $msg = "<br />The following items weren't imported because they contain\n\t\t\t\tinvalid values for either the stock code or the price:<br />";
            foreach ($invalid_fields as $v) {
                $msg .= "&nbsp;&nbsp;&nbsp;&nbsp;- {$v}<br />";
            }
        } else {
            $msg = "";
        }
        $frm->setmsg("<li class='err'>Successfully imported new pricelist.{$msg}</li>");
    }
    return view($frm);
}
function write($_POST)
{
    $Out = "";
    #get & send vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
        $Out .= "<input type='hidden' name=\${$key} value='{$value}'>";
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($id, "num", 1, 100, "Invalid stock item id.");
    if (isset($me)) {
        $v->isOk($me, "string", 0, 100, "Invalid bar code.");
    }
    $v->isOk($sharecode, "string", 0, 100, "Invalid shared bar code.");
    # display errors, if any
    if ($v->isError()) {
        return order($_POST, $v->genErrors());
    }
    $cols = grp(m("bar", $sharecode));
    $wh = "stkid='{$id}'";
    $qry = new dbUpdate("stock", "cubit", $cols, $wh);
    $qry->run(DB_UPDATE);
    if (isset($me) && strlen($me) > 0) {
        db_conn("cubit");
        switch (substr($me, strlen($me) - 1, 1)) {
            case "0":
                $tab = "ss0";
                break;
            case "1":
                $tab = "ss1";
                break;
            case "2":
                $tab = "ss2";
                break;
            case "3":
                $tab = "ss3";
                break;
            case "4":
                $tab = "ss4";
                break;
            case "5":
                $tab = "ss5";
                break;
            case "6":
                $tab = "ss6";
                break;
            case "7":
                $tab = "ss7";
                break;
            case "8":
                $tab = "ss8";
                break;
            case "9":
                $tab = "ss9";
                break;
            default:
                return order($_POST, "The code you selected is invalid");
        }
        if (barext_ex($tab, 'code', $me) or strlen($me) == 0) {
            return order($_POST, "The code you selected aready exits in the system.");
        } else {
            $getcheck = "SELECT * FROM " . $tab . " WHERE code = '{$me}' AND active = 'no'";
            $runcheck = db_exec($getcheck) or errDie("Unable to get serial number check");
            if (pg_numrows($runcheck) < 1) {
                $Sl = "INSERT INTO " . $tab . " (code,stock,div) VALUES ('{$me}','{$id}','" . USER_DIV . "')";
                $Rs = db_exec($Sl) or errDie("Unable to update database.", SELF);
            } else {
                $arr = pg_fetch_array($runcheck);
                $Sl = "UPDATE " . $tab . " SET active = 'yes' WHERE code = '{$arr['code']}' AND stock = '{$arr['stock']}' AND div = '{$arr['div']}'";
                $Rs = db_exec($Sl) or errDie("Unable to update database.", SELF);
            }
        }
    }
    return order($_POST);
}
function write($_POST)
{
    # Set mas execution time to 12 hours
    ini_set("max_execution_time", 43200);
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($invids as $key => $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid recuring invoice number.");
        $odate[$key] = mkdate($o_year[$key], $o_month[$key], $o_day[$key]);
        $v->isOk($odate[$key], "date", 1, 1, "Invalid Invoice Date for invoice: {$invid}.");
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $err = $v->genErrors();
        return $err;
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $i = 0;
    $recinv = new dbSelect("rnons_invoices", "cubit");
    $recinv_i = new dbSelect("rnons_inv_items", "cubit");
    $newinv = new dbUpdate("nons_invoices", "cubit");
    $newinv_i = new dbUpdate("nons_inv_items", "cubit");
    foreach ($invids as $key => $invid) {
        /* fetch recurring invoice info */
        $recinv->setOpt(grp(m("where", "invid='{$invid}' AND div='" . USER_DIV . "'")));
        $recinv->run();
        if ($recinv->num_rows() <= 0) {
            continue;
        }
        $inv = $recinv->fetch_array();
        /* create new invoice from recurring invoice */
        $cols = grp(m("accepted", " "), m("sdate", raw("CURRENT_DATE")), m("typ", "inv"), m("cusid", $inv["cusid"]), m("cusname", $inv["cusname"]), m("cusaddr", $inv["cusaddr"]), m("cusvatno", $inv["cusvatno"]), m("cordno", $inv["cordno"]), m("chrgvat", $inv["chrgvat"]), m("terms", $inv["terms"]), m("odate", $odate[$key]), m("subtot", $inv["subtot"]), m("vat", $inv["vat"]), m("total", $inv["total"]), m("balance", $inv["total"]), m("done", "n"), m("prd", PRD_DB), m("div", USER_DIV), m("ctyp", $inv["ctyp"]), m("tval", $inv["tval"]), m("jobid", $invid), m("remarks", $inv["remarks"]));
        $newinv->setOpt($cols);
        $newinv->run(DB_INSERT);
        /* fetch last invoice id */
        $invid = lastinvid();
        /* fetch recurring invoice items */
        $recinv_i->setOpt(grp(m("where", "invid='{$inv['invid']}' AND div='" . USER_DIV . "'")));
        $recinv_i->run();
        /* add items to new non stock invoice */
        while ($stkd = $recinv_i->fetch_array()) {
            $cols = grp(m("invid", $invid), m("qty", $stkd["qty"]), m("unitcost", $stkd["unitcost"]), m("amt", $stkd["amt"]), m("accid", $stkd["account"]), m("description", $stkd["description"]), m("vatex", $stkd["vatex"]), m("div", USER_DIV));
            $newinv_i->setOpt($cols);
            $newinv_i->run(DB_INSERT);
        }
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $OUT = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Recurring Non-stock Invoices Processed</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>New non-stock Invoices have been created from Recurring Invoices</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='rec-invoice-view.php'>View Recurring Invoices</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $OUT;
}
function writeEmp($_POST)
{
    $_POST = var_makesafe($_POST);
    global $_FILES;
    extract($_POST);
    if (isset($back)) {
        return editEmp();
    }
    //------------------------------------ Jean -----------------------------------
    $comp_uif += 0;
    $comp_sdl += 0;
    $comp_provident += 0;
    $emp_provident += 0;
    $emp_uif += 0;
    //-----------------------------------------------------------------------------
    $comp_pension += 0;
    $emp_pension += 0;
    $comp_ret += 0;
    $emp_ret += 0;
    $comp_medical += 0;
    $emp_medical += 0;
    # validate input
    require_lib("validate");
    $v = new validate();
    # Limit field lengths as per database settings
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    $v->isOk($enum, "string", 1, 20, "Invalid emp num");
    $v->isOk($sname, "string", 1, 50, "Invalid surname.");
    $v->isOk($fnames, "string", 1, 50, "Invalid first names.");
    $v->isOk($sex, "string", 1, 1, "Invalid sex.");
    $v->isOk($marital, "string", 0, 10, "Invalid marital status.");
    $v->isOk($designation, "string", 0, 100, "Invalid designation.");
    $v->isOk($resident, "string", 1, 5, "Invalid residential status.");
    $v->isOk($hiredate, "date", 1, 10, "Invalid hire date.");
    $v->isOk($telno, "string", 0, 30, "Invalid telephone no.");
    $v->isOk($email, "email", 0, 50, "Invalid email address.");
    $v->isOk($hpweek, "float", 1, 5, "Invalid hours per week.");
    $v->isOk($novert, "float", 1, 9, "Invalid normal overtime.");
    $v->isOk($hovert, "float", 1, 9, "Invalid holiday overtime.");
    $v->isOk($paytype, "string", 1, 15, "Invalid pay type.");
    $v->isOk($bankname, "string", 0, 50, "Invalid bank name.");
    $v->isOk($bankcode, "string", 0, 8, "Invalid bank code.");
    $v->isOk($bankacctype, "string", 0, 50, "Invalid bank account type.");
    $v->isOk($bankaccno, "num", 0, 50, "Invalid bank account no.");
    $v->isOk($vaclea, "num", 1, 5, "Invalid vacation leave days.");
    $v->isOk($siclea, "num", 1, 5, "Invalid sick leave days.");
    $v->isOk($stdlea, "num", 1, 5, "Invalid study leave days.");
    $v->isOk($res1, "string", 1, 50, "Invalid residential address. (line 1)");
    $v->isOk($res2, "string", 0, 50, "Invalid residential address. (line 2)");
    $v->isOk($res3, "string", 0, 50, "Invalid residential address. (line 3)");
    $v->isOk($res4, "string", 0, 50, "Invalid residential address. (line 4)");
    $v->isOk($pos1, "string", 0, 50, "Invalid postal address. (line 1)");
    $v->isOk($pos2, "string", 0, 50, "Invalid postal address. (line 2)");
    $v->isOk($pcode, "string", 0, 16, "Invalid postal code.");
    $v->isOk($contsname, "string", 0, 50, "Invalid contact surname.");
    $v->isOk($contfnames, "string", 0, 50, "Invalid first names.");
    $v->isOk($contres1, "string", 0, 50, "Invalid contact address. (line 1)");
    $v->isOk($contres2, "string", 0, 50, "Invalid contact address. (line 2)");
    $v->isOk($contres3, "string", 0, 50, "Invalid contact address. (line 3)");
    $v->isOk($conttelno, "string", 0, 30, "Invalid contact telephone no.");
    $v->isOk($idnum . $passportnum, "string", 1, 30, "Invalid id/passport num (VAL).");
    if (!empty($idnum)) {
        $v->isOk($idnum, "string", 6, 30, "Invalid id number.");
    }
    $v->isOk($taxref, "string", 0, 30, "Invalid tax ref no.");
    $v->isOk($department, "string", 0, 50, "Invalid department");
    $v->isOk($occ_cat, "string", 0, 50, "Invalid Occupational Category");
    $v->isOk($occ_level, "string", 0, 50, "Invalid Occupational Level");
    $v->isOk($pos_filled, "string", 0, 50, "Invalid Position Files");
    $v->isOk($temporary, "string", 0, 50, "Invalid Temporary Data");
    $v->isOk($termination_date, "date", 1, 10, "{$termination_date} Invalid termination date.");
    $v->isOk($recruitment_from, "string", 0, 50, "Invalid Recruitment From");
    $v->isOk($employment_reason, "string", 0, 50, "Invalid Employment Reason");
    $v->isOk($union_name, "string", 0, 50, "Invalid Union Name");
    $v->isOk($union_mem_num, "string", 0, 50, "Invalid Union Member Name");
    $v->isOk($union_pos, "string", 0, 50, "Invalid Union Position");
    $v->isOk($race, "string", 0, 50, "Invalid Race");
    $v->isOk($disabled_stat, "string", 0, 50, "Invalid Disabled Status");
    $v->isOk($emp_group, "num", 1, 10, "Invalid Employee Group.");
    $v->isOK($person_nature, "string", 1, 1, "Invalid Nature Of Person Selection.");
    $v->isOK($medical_aid, "num", 1, 4, "Invalid Medical Aid Selected.");
    $v->isOK($medical_aid_number, "string", 0, 25, "Invalid Medical Aid Number.");
    if (strlen($idnum) >= 6) {
        $bd_year = substr($idnum, 0, 2);
        $bd_month = substr($idnum, 2, 2);
        $bd_day = substr($idnum, 4, 2);
        if (!(is_numeric($bd_year) && is_numeric($bd_month) && is_numeric($bd_day) && checkdate($bd_month, $bd_day, $bd_year))) {
            $v->addError("", "Invalid id num (BD).");
        }
    }
    if (isset($allowances)) {
        foreach ($allowances as $key => $value) {
            $v->isOk($allowances[$key], "float", 0, 20, "Invalid allowance amount " . ($key + 1) . ".");
        }
    }
    if (isset($deductid)) {
        foreach ($deductid as $key => $value) {
            $v->isOk($deductid[$key], "num", 1, 20, "Invalid deductions ID.");
        }
    }
    if (isset($deductions)) {
        foreach ($deductions as $key => $value) {
            $v->isOk($deductions[$key], "float", 0, 20, "Invalid deduction amount" . ($key + 1) . ".");
            $v->isOk($comp_deductions[$key], "float", 0, 20, "Invalid deduction employer contribution amount" . ($key + 1) . ".");
        }
    }
    if (isset($allowid)) {
        foreach ($allowid as $key => $value) {
            $v->isOk($allowid[$key], "num", 1, 20, "Invalid allowance ID.");
        }
    }
    if (isset($allowtax)) {
        foreach ($allowtax as $key => $value) {
            $v->isOk($allowtax[$key], "string", 2, 20, "Invalid allowance tax " . ($key + 1) . ".");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>{$e['msg']}</li>";
        }
        return editEmp($confirmCust);
    }
    db_connect();
    # deal with logo image
    if ($changelogo == "yes") {
        if (empty($_FILES["logo"])) {
            return "<li class='err'> Please select an image to upload from your hard drive.</li>";
        }
        if (is_uploaded_file($_FILES["logo"]["tmp_name"])) {
            # Check file ext
            if (preg_match("/(image\\/jpeg|image\\/png|image\\/gif)/", $_FILES["logo"]["type"], $extension)) {
                $type = $_FILES["logo"]["type"];
                // open file in "read, binary" mode
                $img = "";
                $file = fopen($_FILES['logo']['tmp_name'], "rb");
                while (!feof($file)) {
                    // fread is binary safe
                    $img .= fread($file, 1024);
                }
                fclose($file);
                # base 64 encoding
                $img = base64_encode($img);
                db_connect();
                $Sl = "DELETE FROM eimgs WHERE emp='{$empnum}'";
                $Ry = db_exec($Sl) or errDie("Error removing prev imgs.");
                $Sl = "INSERT INTO eimgs (emp,image, imagetype) VALUES ('{$empnum}','{$img}','{$type}')";
                $Ry = db_exec($Sl) or errDie("Unable to upload company logo Image to DB.", SELF);
                # to show IMG
                //$logoimg = "<br><img src='compinfo/getimg.php' width=230 height=47><br><br>";
                //$logo = "compinfo/getimg.php";
            } else {
                return "<li class='err'>Please note that we only accept images of the types PNG,GIF and JPEG.</li>";
            }
        } else {
            return "<li class='err'>Unable to upload file, Please check file permissions.</li>";
        }
    }
    # if data is ok, write to db
    db_connect();
    //------------------------------------ Jean -----------------------------------
    $comp_sdl += 0;
    $comp_uif += 0;
    $comp_provident += 0;
    $emp_provident += 0;
    $emp_uif += 0;
    //-----------------------------------------------------------------------------
    $comp_pension += 0;
    $emp_pension += 0;
    $comp_ret += 0;
    $emp_ret += 0;
    $comp_medical += 0;
    $emp_medical += 0;
    $sal_bonus += 0;
    $all_travel += 0;
    /* FOR AUDITING PURPOSES THESE VALUES HAVE BEEN HARDCODED */
    $comp_sdl = 1;
    $comp_uif = 1;
    $emp_uif = 1;
    /* DONE */
    $basic_sal = sprint($basic_sal);
    if ($resident == "Yes") {
        $resident = "TRUE";
    } else {
        $resident = "FALSE";
    }
    $sql = "\n\t\tUPDATE employees \n\t\tSET idnum='{$idnum}', passportnum='{$passportnum}', sex='{$sex}', sname='{$sname}', fnames='{$fnames}', marital='{$marital}', \n\t\t\tresident='{$resident}', hiredate='{$hiredate}', telno='{$telno}', email='{$email}', basic_sal='{$basic_sal}', \n\t\t\thpweek='{$hpweek}', novert='{$novert}', hovert='{$hovert}', paytype='{$paytype}', taxref='{$taxref}', enum='{$enum}', \n\t\t\tpayprd_day='{$payprd_day}', bankname='{$bankname}', bankcode='{$bankcode}', bankacctype='{$bankacctype}', \n\t\t\tbankaccno='{$bankaccno}', vaclea='{$vaclea}', siclea='{$siclea}', stdlea='{$stdlea}', res1='{$res1}', res2='{$res2}', \n\t\t\tres3='{$res3}', res4='{$res4}', pos1='{$pos1}', pos2='{$pos2}', pcode='{$pcode}', contsname='{$contsname}', \n\t\t\tcontfnames='{$contfnames}', contres1='{$contres1}', contres2='{$contres2}', contres3='{$contres3}', \n\t\t\tconttelno='{$conttelno}', designation='{$designation}', basic_sal_annum='{$basic_sal_annum}', sal_bonus='{$sal_bonus}', \n\t\t\tsal_bonus_month='{$sal_bonus_month}', all_travel='{$all_travel}', comp_uif='{$comp_uif}', comp_sdl='{$comp_sdl}', \n\t\t\temp_uif='{$emp_uif}', comp_pension='{$comp_pension}', emp_pension='{$emp_pension}', comp_ret='{$comp_ret}', \n\t\t\temp_ret='{$emp_ret}', comp_medical='{$comp_medical}', emp_medical='{$emp_medical}', emp_meddeps='{$emp_meddeps}', \n\t\t\tcomp_provident='{$comp_provident}', emp_provident='{$emp_provident}', comp_other='{$comp_other}', \n\t\t\temp_other='{$emp_other}', payprd='{$payprd}', saltyp='{$saltyp}', department = '{$department}', occ_cat = '{$occ_cat}', \n\t\t\tocc_level = '{$occ_level}', pos_filled = '{$pos_filled}', temporary = '{$temporary}', \n\t\t\ttermination_date = '{$termination_date}', recruitment_from = '{$recruitment_from}', \n\t\t\temployment_reason = '{$employment_reason}', union_name = '{$union_name}', union_mem_num = '{$union_mem_num}', \n\t\t\tunion_pos = '{$union_pos}', race = '{$race}', disabled_stat = '{$disabled_stat}', fringe_car1='{$fringe_car1}', \n\t\t\tfringe_car1_contrib='{$fringe_car1_contrib}', fringe_car1_fuel='{$fringe_car1_fuel}', \n\t\t\tfringe_car1_service='{$fringe_car1_service}', fringe_car2='{$fringe_car2}', \n\t\t\tfringe_car2_contrib='{$fringe_car2_contrib}', fringe_car2_fuel='{$fringe_car2_fuel}', \n\t\t\tfringe_car2_service='{$fringe_car2_service}', flag=NULL,prevemp_remun='{$prevemp_remun}', \n\t\t\tprevemp_tax='{$prevemp_tax}', emp_group='{$emp_group}', person_nature = '{$person_nature}', \n\t\t\tmedical_aid = '{$medical_aid}', medical_aid_number = '{$medical_aid_number}', emp_usescales = '{$emp_usescales}' \n\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
    $nwEmpRslt = db_exec($sql) or errDie("Unable to update employee information.");
    //-----------------------------------------------------------------------------
    if (isset($allowid)) {
        # Remove old details
        $sql = "DELETE FROM empallow WHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
        $allowRslt = db_exec($sql);
        # write Allowances to db
        foreach ($allowid as $i => $id) {
            if (empty($allowances[$i]) || $allowances[$i] == 0) {
                continue;
            }
            # Insert new records
            $allowances[$i] += 0;
            $allowances[$i] = sprint($allowances[$i]);
            $sql = "\n\t\t\t\tINSERT INTO empallow (\n\t\t\t\t\tallowid, empnum, type, amount, accid, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$id}', '{$empnum}', '{$allowtype[$i]}', '{$allowances[$i]}', '{$allowaccid[$i]}', '" . USER_DIV . "'\n\t\t\t\t)";
            $allowRslt = db_exec($sql) or errDie("Unable to process Employee allowances in database.");
        }
    }
    if (isset($subsname)) {
        $inssub = new dbUpdate("emp_subsistence", "cubit");
        foreach ($subsname as $sid => $sn) {
            $subsamt[$sid] += 0;
            $cols = grp(m("subid", $sid), m("empnum", $empnum), m("amount", $subsamt[$sid]), m("days", $subsdays[$sid]), m("accid", $subsacc[$sid]));
            $inssub->setOpt($cols, wgrp(m("subid", $sid), m("empnum", $empnum)));
            $inssub->run(DB_REPLACE);
        }
    }
    if (isset($deductid)) {
        # Remove old records
        $sql = "DELETE FROM empdeduct WHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
        $deductRslt = db_exec($sql);
        # write Deductions to db
        foreach ($deductid as $i => $id) {
            if (isset($ltsal_checked[$i])) {
                $ltsal = "y";
            } else {
                $ltsal = "n";
            }
            # Insert new records
            if (empty($deductions[$i]) || $deductions[$i] == 0) {
                continue;
            }
            if (empty($comp_deductions[$i])) {
                $comp_deductions[$i] = 0;
            }
            $deductions[$i] += 0;
            $deductions[$i] = sprint($deductions[$i]);
            $comp_deductions[$i] += 0;
            $sql = "\n\t\t\t\tINSERT INTO empdeduct (\n\t\t\t\t\tdedid, empnum, amount, employer_amount, div, type, \n\t\t\t\t\temployer_type, grosdeduct, accid\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$id}', '{$empnum}', '{$deductions[$i]}', '{$comp_deductions[$i]}', '" . USER_DIV . "', '{$deducttype[$i]}', \n\t\t\t\t\t'{$deducttype[$i]}', '{$ltsal}', '{$deductaccid[$i]}'\n\t\t\t\t)";
            $deductRslt = db_exec($sql) or errDie("Unable to process Employee deductions in database.");
        }
    }
    if (isset($fringeid)) {
        $sql = "DELETE FROM empfringe WHERE empnum='{$empnum}' AND div='" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Error updating fringe benefits (DEL).");
        foreach ($fringeid as $i => $id) {
            if (empty($fringebens[$i]) || $fringebens[$i] == 0) {
                continue;
            }
            $fringebens[$i] += 0;
            $sql = "\n\t\t\t\tINSERT INTO empfringe (\n\t\t\t\t\tfringeid, empnum, amount, type, accid, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$id}', '{$empnum}', '{$fringebens[$i]}', '{$fringetype[$i]}', '{$fringeexpacc[$i]}', '" . USER_DIV . "'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Error updating fringe benefits (INS#{$id}).");
        }
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM costcenters";
    $Ri = db_exec($Sl);
    $i = 0;
    $Sl = "DELETE FROM empc WHERE emp='{$empnum}'";
    $Rl = db_exec($Sl);
    while ($data = pg_fetch_array($Ri)) {
        if ($ct[$data['ccid']] > 0) {
            $Sl = "INSERT INTO empc(cid,emp,amount) VALUES ('{$data['ccid']}','{$empnum}','" . $ct[$data['ccid']] . "')";
            $Rl = db_exec($Sl);
        }
        $i++;
    }
    # Provide some info on status
    $writeEmp = "\n\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t<tr>\n\t\t\t\t<th>Employee details edited</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Employee details for employee number, {$enum}, has been successfully edited.</td>\n\t\t\t</tr>\n\t\t</table>" . mkQuickLinks(ql("../admin-employee-add.php", "Add Employee"));
    return $writeEmp;
}
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 save_statement($stmnt, $tbl_pfx)
{
    $stmnt = clean_html($stmnt);
    $cols = grp(m("gendate", raw("CURRENT_DATE")), m("output", base64_encode($stmnt)), m("div", USER_DIV), m("des", "Saved by " . USER_NAME . " at Year End: " . getFinYear()));
    $stmnt = new dbUpdate("save_{$tbl_pfx}", "core", $cols);
    $stmnt->run(DB_INSERT);
}
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 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 writeEmp($_POST)
{
    $_POST = var_makesafe($_POST);
    global $_FILES;
    extract($_POST);
    $comp_pension += 0;
    $emp_pension += 0;
    $comp_ret += 0;
    $emp_ret += 0;
    $comp_medical += 0;
    $emp_medical += 0;
    # validate input
    require_lib("validate");
    $v = new validate();
    # Limit field lengths as per database settings
    $v->isOk($empnum, "string", 0, 20, "Invalid emp num");
    $v->isOk($sname, "string", 1, 50, "Invalid surname.");
    $v->isOk($fnames, "string", 1, 50, "Invalid first names.");
    $v->isOk($sex, "string", 1, 1, "Invalid sex.");
    $v->isOk($marital, "string", 0, 10, "Invalid marital status.");
    $v->isOk($designation, "string", 0, 100, "Invalid designation.");
    $v->isOk($changelogo, "string", 1, 3, "Invalid image selection.");
    $v->isOk($resident, "string", 1, 5, "Invalid residential status.");
    $v->isOk($hiredate, "date", 1, 10, "Invalid hire date.");
    $v->isOk($telno, "string", 0, 30, "Invalid telephone no.");
    $v->isOk($email, "email", 0, 255, "Invalid email address.");
    $v->isOk($basic_sal, "float", 1, 9, "Invalid basic salary.");
    $v->isOk($hpweek, "float", 1, 5, "Invalid hours per week.");
    $v->isOk($saltyp, "string", 1, 2, "Invalid payment period.");
    $v->isOk($novert, "float", 1, 9, "Invalid normal overtime.");
    $v->isOk($hovert, "float", 1, 9, "Invalid holiday overtime.");
    $v->isOk($paytype, "string", 1, 15, "Invalid pay type.");
    $v->isOk($bankname, "string", 0, 50, "Invalid bank name.");
    $v->isOk($bankcode, "string", 0, 8, "Invalid branch code.");
    $v->isOk($bankacctype, "string", 0, 50, "Invalid bank account type.");
    $v->isOk($bankaccno, "num", 0, 50, "Invalid bank account no.");
    $v->isOk($vaclea, "num", 1, 5, "Invalid vacation leave days.");
    $v->isOk($siclea, "num", 1, 5, "Invalid sick leave days.");
    $v->isOk($stdlea, "num", 1, 5, "Invalid study leave days.");
    $v->isOk($res1, "string", 1, 50, "Invalid residential address. (line 1)");
    $v->isOk($res2, "string", 0, 50, "Invalid residential address. (line 2)");
    $v->isOk($res3, "string", 0, 50, "Invalid residential address. (line 3)");
    $v->isOk($res4, "string", 0, 50, "Invalid residential address. (line 4)");
    $v->isOk($pos1, "string", 0, 50, "Invalid postal address. (line 1)");
    $v->isOk($pos2, "string", 0, 50, "Invalid postal address. (line 2)");
    $v->isOk($pcode, "strin", 0, 16, "Invalid postal code.");
    $v->isOk($contsname, "string", 0, 50, "Invalid contact surname.");
    $v->isOk($contfnames, "string", 0, 50, "Invalid first names.");
    $v->isOk($contres1, "string", 0, 50, "Invalid contact address. (line 1)");
    $v->isOk($contres2, "string", 0, 50, "Invalid contact address. (line 2)");
    $v->isOk($contres3, "string", 0, 50, "Invalid contact address. (line 3)");
    $v->isOk($contres4, "string", 0, 50, "Invalid contact address. (line 4)");
    $v->isOk($conttelno, "string", 0, 30, "Invalid contact telephone no.");
    $v->isOk($idnum . $passportnum, "string", 1, 30, "Invalid id/passport num (VAL).");
    if (!empty($idnum)) {
        $v->isOk($idnum, "string", 6, 30, "Invalid id number.");
    }
    $v->isOk($taxref, "string", 0, 30, "Invalid tax ref no.");
    $v->isOk($department, "string", 0, 50, "Invalid department");
    $v->isOk($occ_cat, "string", 0, 50, "Invalid Occupational Category");
    $v->isOk($occ_level, "string", 0, 50, "Invalid Occupational Level");
    $v->isOk($pos_filled, "string", 0, 50, "Invalid Position Files");
    $v->isOk($temporary, "string", 0, 50, "Invalid Temporary Data");
    $v->isOk($termination_date, "date", 1, 10, "{$termination_date} Invalid termination date.");
    $v->isOk($recruitment_from, "string", 0, 50, "Invalid Recruitment From");
    $v->isOk($employment_reason, "string", 0, 50, "Invalid Employment Reason");
    $v->isOk($union_name, "string", 0, 50, "Invalid Union Name");
    $v->isOk($union_mem_num, "string", 0, 50, "Invalid Union Member Name");
    $v->isOk($union_pos, "string", 0, 50, "Invalid Union Position");
    $v->isOk($race, "string", 0, 50, "Invalid Race");
    $v->isOk($disabled_stat, "string", 0, 50, "Invalid Disabled Status");
    if (strlen($idnum) >= 6) {
        $bd_year = substr($idnum, 0, 2);
        $bd_month = substr($idnum, 2, 2);
        $bd_day = substr($idnum, 4, 2);
        if (!(is_numeric($bd_year) && is_numeric($bd_month) && is_numeric($bd_day) && checkdate($bd_month, $bd_day, $bd_year))) {
            $v->addError("", "Invalid id num (BD).");
        }
    }
    if (isset($allowances)) {
        foreach ($allowances as $key => $value) {
            $v->isOk($allowances[$key], "float", 0, 20, "Invalid allowance amount " . ($key + 1) . ".");
        }
    }
    if (isset($deductid)) {
        foreach ($deductid as $key => $value) {
            $v->isOk($deductid[$key], "num", 1, 20, "Invalid deductions ID.");
        }
    }
    if (isset($deductions)) {
        foreach ($deductions as $key => $value) {
            $v->isOk($deductions[$key], "float", 0, 20, "Invalid deduction amount" . ($key + 1) . ".");
        }
    }
    if (isset($allowid)) {
        foreach ($allowid as $key => $value) {
            $v->isOk($allowid[$key], "num", 1, 20, "Invalid allowance ID.");
        }
    }
    if (isset($allowtax)) {
        foreach ($allowtax as $key => $value) {
            $v->isOk($allowtax[$key], "string", 2, 20, "Invalid allowance tax " . ($key + 1) . ".");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>{$e['msg']}</li>";
        }
        print $confirmCust;
        print "<br>ERROR";
        die;
    }
    $basic_sal = sprint($basic_sal);
    $expacc_provident = gethook("accnum", "salacc", "name", "providentexpense");
    $expacc_ret = gethook("accnum", "salacc", "name", "retireexpense");
    $expacc_pension = gethook("accnum", "salacc", "name", "pensionexpense");
    $expacc_uif = gethook("accnum", "salacc", "name", "uifexp");
    $expacc_medical = gethook("accnum", "salacc", "name", "medicalexpense");
    $expacc_salwages = gethook("accnum", "salacc", "name", "salaries");
    $expacc_sdl = gethook("accnum", "salacc", "name", "sdlexp");
    $expacc_reimburs = 0;
    //gethook("accnum", "salacc", "name", "allreimburs");
    /* FOR AUDITING PURPOSES THESE VALUES HAVE BEEN HARDCODED */
    $comp_sdl = 1;
    $comp_uif = 1;
    $emp_uif = 1;
    /* DONE */
    if ($resident == "Yes") {
        $resident = "TRUE";
    } else {
        $resident = "FALSE";
    }
    db_conn("cubit");
    $sql = "INSERT INTO cubit.employees (sname, fnames, sex, marital, resident, hiredate, telno, email, basic_sal, saltyp, hpweek, novert, hovert, payprd,payprd_day,\n\t\t\t\tpaytype, bankname, bankcode, bankacctype, bankaccno, vaclea, siclea, stdlea, res1, res2, res3, res4, pos1, pos2, pcode, contsname, contfnames, contres1,\n\t\t\t\tcontres2, contres3, conttelno, div,idnum, passportnum, taxref,enum,designation,balance,comp_pension,emp_pension,comp_ret,emp_ret,comp_medical,emp_medical,\n\t\t\t\temp_meddeps,sal_bonus, sal_bonus_month, basic_sal_annum, all_travel, comp_uif, comp_sdl, comp_other, comp_provident, emp_uif, emp_other, emp_provident,\n\t\t\t\texpacc_provident, expacc_ret, expacc_pension, expacc_uif, expacc_medical, expacc_other, expacc_salwages, expacc_sdl, expacc_reimburs, department, occ_cat, occ_level,\n\t\t\t\tpos_filled, temporary, termination_date, recruitment_from, employment_reason, union_name, union_mem_num, union_pos, race, disabled_stat,\n\t\t\t\tfringe_car1, fringe_car1_contrib, fringe_car1_fuel, fringe_car1_service,\n\t\t\t\tfringe_car2, fringe_car2_contrib, fringe_car2_fuel, fringe_car2_service,\n\t\t\t\tprevemp_remun, prevemp_tax, cyear)\n\t\t\tVALUES ('{$sname}', '{$fnames}', '{$sex}', '{$marital}', '{$resident}', '{$hiredate}', '{$telno}',\n\t\t\t\t'{$email}', '{$basic_sal}', '{$saltyp}', '{$hpweek}', '{$novert}', '{$hovert}', '{$payprd}','{$payprd_day}', '{$paytype}', '{$bankname}', '{$bankcode}', '{$bankacctype}', '{$bankaccno}', '{$vaclea}',\n\t\t\t\t'{$siclea}', '{$stdlea}', '{$res1}', '{$res2}', '{$res3}', '{$res4}', '{$pos1}', '{$pos2}', '{$pcode}', '{$contsname}', '{$contfnames}', '{$contres1}', '{$contres2}', '{$contres3}', '{$conttelno}',\n\t\t\t\t'" . USER_DIV . "','{$idnum}', '{$passportnum}', '{$taxref}','{$empnum}','{$designation}',0,'{$comp_pension}','{$emp_pension}','{$comp_ret}','{$emp_ret}','{$comp_medical}','{$emp_medical}','{$emp_meddeps}',\n\t\t\t\t'{$sal_bonus}', '{$sal_bonus_month}', '{$basic_sal_annum}', '{$all_travel}', '{$comp_uif}', '{$comp_sdl}', '{$comp_other}', '{$comp_provident}', '{$emp_uif}', '{$emp_other}', '{$emp_provident}',\n\t\t\t\t'{$expacc_provident}', '{$expacc_ret}', '{$expacc_pension}', '{$expacc_uif}', '{$expacc_medical}', '0', '{$expacc_salwages}', '{$expacc_sdl}', '{$expacc_reimburs}', '{$department}', '{$occ_cat}', '{$occ_level}',\n\t\t\t\t'{$pos_filled}', '{$temporary}', '{$termination_date}', '{$recruitment_from}', '{$employment_reason}', '{$union_name}', '{$union_mem_num}', '{$union_pos}', '{$race}', '{$disabled_stat}',\n\t\t\t\t'{$fringe_car1}', '{$fringe_car1_contrib}', '{$fringe_car1_fuel}', '{$fringe_car1_service}',\n\t\t\t\t'{$fringe_car2}', '{$fringe_car2_contrib}', '{$fringe_car2_fuel}', '{$fringe_car2_service}',\n\t\t\t\t'{$prevemp_remun}', '{$prevemp_tax}', '" . EMP_YEAR . "')";
    $nwEmpRslt = db_exec($sql) or errDie("Unable to add new employee.");
    if ($empnum == "") {
        $not = "Yes";
    } else {
        $not = "No";
    }
    $empnum = pglib_lastid("employees", "empnum");
    if (isset($allowid)) {
        # Remove old details
        $sql = "DELETE FROM empallow WHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
        $allowRslt = db_exec($sql);
        # write Allowances to db
        foreach ($allowid as $i => $id) {
            if (empty($allowances[$i]) || $allowances[$i] == 0) {
                continue;
            }
            # Insert new records
            $sql = "INSERT INTO empallow (allowid, empnum, type, amount, accid, div) VALUES ('{$id}', '{$empnum}','{$allowtype[$i]}', '{$allowances[$i]}', '{$allowaccid[$i]}', '" . USER_DIV . "')";
            $allowRslt = db_exec($sql) or errDie("Unable to process Employee allowances in database.");
        }
        # delete empallow with zeros on the amount
        $sql = "DELETE FROM empallow WHERE amount=0 AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql);
    }
    if (isset($subsname)) {
        $inssub = new dbUpdate("emp_subsistence", "cubit");
        foreach ($subsname as $sid => $sn) {
            if ($subsamt[$sid] == 0) {
                continue;
            }
            $cols = grp(m("subid", $sid), m("empnum", $empnum), m("amount", $subsamt[$sid]), m("days", $subsdays[$sid]), m("accid", $subsacc[$sid]));
            $inssub->setOpt($cols);
            $inssub->run(DB_INSERT);
        }
    }
    if (isset($deductid)) {
        # write Deductions to db
        foreach ($deductid as $i => $id) {
            $sql = "SELECT * FROM empdeduct WHERE dedid='{$id}' AND empnum='{$empnum}'";
            $rslt = db_exec($sql) or errDie("Error writing deduction.");
            if (empty($deductions[$i]) || $deductions[$i] == 0) {
                continue;
            }
            //$deductions[$i] = 0;
            if (empty($comp_deductions[$i])) {
                $comp_deductions[$i] = 0;
            }
            if (pg_num_rows($rslt) > 0) {
                $sql = "UPDATE empdeduct SET amount='{$deductions[$i]}'";
            } else {
                $sql = "INSERT INTO empdeduct (dedid, empnum, amount,\n\t\t\t\t\t\t\temployer_amount, employer_type, div, type, accid)\n\t\t\t\t\t\tVALUES ('{$id}', '{$empnum}', '{$deductions[$i]}', '{$comp_deductions[$i]}',\n\t\t\t\t\t\t\t'{$deducttype[$i]}', '" . USER_DIV . "', '{$deducttype[$i]}', '{$deductaccid[$i]}')";
            }
            $rslt = db_exec($sql) or errDie("Unable to process Employee deductions in database.");
        }
    }
    if (isset($fringebens)) {
        foreach ($fringeid as $i => $id) {
            if (empty($fringebens[$i]) || $fringebens[$i] == 0) {
                continue;
            }
            $sql = "SELECT * FROM empfringe WHERE fringeid='{$id}' AND empnum='{$empnum}'";
            $rslt = db_exec($sql) or errDie("Error writing fringe benefit.");
            if (pg_num_rows($rslt) > 0) {
                $sql = "UPDATE empfringe SET amount='{$fringebens[$i]}'";
            } else {
                $sql = "INSERT INTO empfringe (fringeid, empnum, amount, type, accid, div)\n\t\t\t\t\t\tVALUES('{$id}', '{$empnum}', '{$fringebens[$i]}', '{$fringetype[$i]}', '{$fringeexpacc[$i]}', '" . USER_DIV . "')";
            }
            $rslt = db_exec($sql) or errDie("Error writing fringe benefit.");
        }
    }
    # deal with logo image
    if ($changelogo == "yes") {
        if (empty($_FILES["logo"])) {
            return "<li class=err> Please select an image to upload from your hard drive.";
        }
        if (is_uploaded_file($_FILES["logo"]["tmp_name"])) {
            # Check file ext
            if (preg_match("/(image\\/jpeg|image\\/png|image\\/gif)/", $_FILES["logo"]["type"], $extension)) {
                $type = $_FILES["logo"]["type"];
                // open file in "read, binary" mode
                $img = "";
                $file = fopen($_FILES['logo']['tmp_name'], "rb");
                while (!feof($file)) {
                    // fread is binary safe
                    $img .= fread($file, 1024);
                }
                fclose($file);
                # base 64 encoding
                $img = base64_encode($img);
                db_connect();
                $Sl = "INSERT INTO eimgs (emp,image, imagetype) VALUES('{$empnum}','{$img}','{$type}')";
                $Ry = db_exec($Sl) or errDie("Unable to upload company logo Image to DB.", SELF);
                # to show IMG
                //$logoimg = "<br><img src='compinfo/getimg.php' width=230 height=47><br><br>";
                //$logo = "compinfo/getimg.php";
            } else {
                return "<li class='err'>Please note that we only accept images of the types PNG,GIF and JPEG.";
            }
        } else {
            return "Unable to upload file, Please check file permissions.";
        }
    }
    if ($not == "Yes") {
        $Sl = "UPDATE employees SET enum='{$empnum}' WHERE empnum='{$empnum}'";
        $Ry = db_exec($Sl) or errDie("unable to update employees.");
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM costcenters";
    $Ri = db_exec($Sl);
    $Sl = "DELETE FROM empc WHERE emp='{$empnum}'";
    $Rl = db_exec($Sl);
    while ($data = pg_fetch_array($Ri)) {
        if ($ct[$data['ccid']] > 0) {
            $Sl = "INSERT INTO empc(cid,emp,amount) VALUES ('{$data['ccid']}','{$empnum}','" . $ct[$data['ccid']] . "')";
            $Rl = db_exec($Sl);
        }
    }
    print ".";
}
function cp2($id, $amount, $description, $contra, $refnum, $date, $cheque = 0, $bankid)
{
    $cheque += 0;
    $sdate = date("Y-m-d");
    $accdate = $date;
    if ($accdate == 0) {
        $accdate = date("Y-m-d");
    }
    $cus = qryCustomer($id, "cusnum, deptid, cusname, surname");
    $dept = qryDepartment($cus["deptid"], "debtacc");
    // 	db_connect();
    //
    // 	$Sl = "SELECT cusnum,deptid,cusname,surname FROM customers WHERE cusnum = '$id' AND div = '".USER_DIV."'";
    // 	$Ri = db_exec($Sl) or errDie("Unable to get data.");
    // 	$cus = pg_fetch_array($Ri);
    db_conn('core');
    $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
    $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
    if (pg_numrows($Rx) < 1) {
        return "Invalid bank acc.";
    }
    $link = pg_fetch_array($Rx);
    #######################################################################################################
    ########################################### COMPILE ###################################################
    #######################################################################################################
    $out = $amount;
    $invs_arr = array();
    // Connect to database
    db_connect();
    #####################[ GET OUTSTANDING INVOICES ]######################
    $sql = "\n\t\tSELECT invnum, invid, balance, terms, odate \n\t\tFROM invoices \n\t\tWHERE cusnum = '{$id}' AND printed = 'y' AND balance>0 AND div = '" . USER_DIV . "' ORDER BY odate ASC";
    $prnInvRslt = db_exec($sql);
    while (($inv = pg_fetch_array($prnInvRslt)) && $out > 0) {
        $invs_arr[] = array("s", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
    }
    #####################[ GET OUTSTANDING NON STOCK INVOICES ]######################
    $sql = "\n\t\tSELECT invnum, invid, balance, odate \n\t\tFROM nons_invoices \n\t\tWHERE cusid='{$id}' AND done='y' AND balance>0 AND div='" . USER_DIV . "' ORDER BY odate ASC";
    $prnInvRslt = db_exec($sql);
    while (($inv = pg_fetch_array($prnInvRslt)) && $out > 0) {
        $invs_arr[] = array("n", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
    }
    $out = sprint($out);
    #####################[ GET OUTSTANDING POS INVOICES ]######################
    $sqls = array();
    for ($i = 1; $i <= 12; ++$i) {
        $sqls[] = "\n\t\t\tSELECT invnum, invid, balance, odate \n\t\t\tFROM \"{$i}\".pinvoices \n\t\t\tWHERE cusnum='{$id}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "'";
    }
    $sql = implode(" UNION ", $sqls);
    $prnInvRslt = db_exec($sql);
    while ($inv = pg_fetch_array($prnInvRslt)) {
        $invs_arr[] = array("p", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
    }
    #compile results into an array we can sort by date
    $search_arr = array();
    foreach ($invs_arr as $key => $array) {
        $search_arr[$key] = $array[1];
    }
    #sort array by date
    asort($search_arr);
    #add sorted invoices to payment listing
    foreach ($search_arr as $key => $date) {
        $arr = $invs_arr[$key];
        if ($arr[0] == "s") {
            db_connect();
            $get_sql = "\n\t\t\t\tSELECT invnum, invid, balance, terms, odate \n\t\t\t\tFROM invoices \n\t\t\t\tWHERE cusnum = '{$id}' AND printed = 'y' AND balance>0 AND div = '" . USER_DIV . "' AND invid = '{$arr['2']}'  LIMIT 1";
            $run_sql = db_exec($get_sql) or errDie("Unable to get stock invoice information.");
            if (pg_numrows($run_sql) > 0) {
                $inv = pg_fetch_array($run_sql);
                $invid = $inv['invid'];
                $val = allocamt($out, $inv["balance"]);
                if ($val == 0.0) {
                    continue;
                }
                $inv['invnum'] += 0;
                // reduce invoice balance
                $sql = "\n\t\t\t\t\tUPDATE cubit.invoices \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\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\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$id}','{$inv['invnum']}', '" . ($val - $val * 2) . "', '{$accdate}', \n\t\t\t\t\t\t'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $link['accnum'], $accdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $val, "c");
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                if ($inv['prd'] == "0") {
                    $inv['prd'] = PRD_DB;
                }
                $invprds .= "|{$inv['prd']}";
                $rages .= "|0";
                $invidsers .= " - {$inv['invnum']}";
            }
        } elseif ($arr[0] == "n") {
            db_connect();
            $get_sql = "\n\t\t\t\tSELECT invnum, invid, balance, odate \n\t\t\t\tFROM nons_invoices \n\t\t\t\tWHERE cusid='{$id}' AND done='y' AND balance>0 AND div='" . USER_DIV . "' AND invid = '{$arr['2']}' LIMIT 1";
            $run_sql = db_exec($get_sql) or errDie("Unable to get non stock information.");
            if (pg_numrows($run_sql) > 0) {
                $inv = pg_fetch_array($run_sql);
                $invid = $inv['invid'];
                $val = allocamt($out, $inv["balance"]);
                if ($val == 0.0) {
                    continue;
                }
                $inv['invnum'] += 0;
                # reduce the money that has been paid
                $sql = "\n\t\t\t\t\tUPDATE cubit.nons_invoices \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\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\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, \n\t\t\t\t\t\tdiv, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$id}', '{$inv['invnum']}', '" . ($val - $val * 2) . "', '{$accdate}', \n\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', \n\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $link['accnum'], $accdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $val, "c");
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                $invprds .= "|0";
                $rages .= "|{$inv['age']}";
                $invidsers .= " - {$inv['invnum']}";
            }
        } else {
            db_connect();
            $sqls = array();
            for ($i = 1; $i <= 12; ++$i) {
                $sqls[] = "\n\t\t\t\t\tSELECT invnum, invid, balance, odate, '{$i}' AS prd  \n\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\tWHERE cusnum='{$id}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "' AND invid = '{$arr['2']}'";
            }
            $get_sql = implode(" UNION ", $sqls);
            $run_sql = db_exec($get_sql) or errDie("Unable to get pos invoice information.");
            if (pg_numrows($run_sql) > 0) {
                $inv = pg_fetch_array($run_sql);
                $invid = $inv['invid'];
                $val = allocamt($out, $inv["balance"]);
                if ($val == 0.0) {
                    continue;
                }
                // reduce the invoice balance
                $sql = "\n\t\t\t\t\tUPDATE \"{$inv['prd']}\".pinvoices \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\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\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($val - $val * 2) . "', '{$accdate}', \n\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $link['accnum'], $accdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']}", $val, "c");
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                $invprds .= "|{$inv['prd']}";
                $rages .= "|0";
                $invidsers .= " - {$inv['invnum']}";
            }
        }
    }
    #if there is any amount unallocated, it goes to general transaction
    $confirm .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='6'><b>A general transaction will credit the client's account with " . CUR . " {$out} </b></td>\n\t\t</tr>";
    vsprint($out);
    $confirm .= "<input type='hidden' name='out' value='{$out}'>";
    ###############################################################################################################################
    ###############################################################################################################################
    ###############################################################################################################################
    #######################################################################################################
    ########################################### PROCESS ###################################################
    #######################################################################################################
    # update the customer (make balance less)
    $sql = "\n\t\tUPDATE cubit.customers \n\t\tSET balance = (balance - '{$amount}'::numeric(13,2)) \n\t\tWHERE cusnum = '{$id}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $cols = grp(m("bankid", $bankid), m("trantype", "deposit"), m("date", $accdate), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheque), m("amount", $amount), 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();
    writetrans($link['accnum'], $dept['debtacc'], $accdate, $refnum, $amount, "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='{$id}'"), 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<tr class='" . bg_class() . "'>\n\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<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t<td>{$od['date']}</td>\n\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</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<tr class='" . bg_class() . "'>\n\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<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t<td>{$od['date']}</td>\n\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</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 = "\n\t\t\t\t\tINSERT INTO cubit.open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, balance, date, type, st, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cus['cusnum']}', '0', '-{$out}', '-{$out}', '{$accdate}', 'Payment Received', 'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            }
            $out = $bout;
        }
        if ($out > 0) {
            recordCT($out, $cus['cusnum'], $accdate, 0);
            $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$out), m("date", $accdate), 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'], $link['accnum'], $accdate, "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();
    }
}