function write_details($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($branch_ip, "url", 1, 50, "Invalid Branch IP.");
    $v->isOk($branch_company, "url", 4, 4, "Invalid Branch Company Code.");
    $v->isOk($branch_username, "string", 1, 50, "Invalid Branch Username.");
    //	$v->isOk ($branch_password, "url", 1, 50, "Invalid Branch Password.");
    //	$v->isOk ($branch_passwordconfirm, "url", 1, 50, "Invalid Branch Password.");
    //	$v->isOk ($branch_ip, "url", 1, 50, "Invalid Branch IP.");
    if ($branch_password != $branch_passwordconfirm) {
        $v->addError($branch_password, "Passwords do not match.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return get_details($_POST, $confirmCust);
    }
    db_connect();
    $add_sql = "\n\t\tINSERT INTO branches_data (\n\t\t\tbranch_name, branch_desc, branch_contact, branch_ip, \n\t\t\tdate_added, last_online, branch_username, branch_password, \n\t\t\tlast_login_from, branch_localuser, branch_company\n\t\t) VALUES (\n\t\t\t'{$branch_name}', '{$branch_desc}', '{$branch_contact}', '{$branch_ip}', \n\t\t\t'now', '1990-01-01', '{$branch_username}', md5('{$branch_password}'), \n\t\t\t'1990-01-01', '{$branch_localuser}', '{$branch_company}'\n\t\t)";
    $run_add = pg_exec($add_sql) or errDie("Unable to add branch information.");
    $display = "\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Branch Added</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Branch Has Been Added.</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t";
    return $display;
}
function confirm($_POST)
{
    extract($_POST);
    require_lib("validate");
    $v = new validate();
    $v->isOk("{$retrtries}", "num", 0, 3, "Invalid value for tries.");
    $v->isOk("{$retrmins}", "num", 0, 3, "Invalid value for minutes.");
    if ($retrtries != 0 && $retrmins == 0) {
        $v->addError('', "Tries needs a value");
    } elseif ($retrmins != 0 && $retrtries == 0) {
        $v->addError('', "Minutes needs a value");
    }
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>{$e['msg']}</li>";
        }
        return enter($confirm);
    }
    $OUTPUT = "<form method=post action='" . SELF . "'>\n\n\t<input type=hidden name=key value='write'>\n\t<input type=hidden name=retrtries value='{$retrtries}'>\n\t<input type=hidden name=retrminutes value='{$retrmins}'>\n\n\t<table border=0 cellspacing='" . TMPL_tblCellSpacing . "' cellpadding='" . TMPL_tblCellPadding . "'>\n\t\t<th>Setting</th>\n\t\t<th>Value</th>\n\t\t<tr class='bg-odd'>\n\t\t\t<td>Login retries:</td>\n\t\t\t<td>{$retrtries}</td>\n\t\t</tr>\n\t\t<tr class='bg-even'>\n\t\t\t<td>Blocked Time:</td>\n\t\t\t<td>{$retrmins}</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td align=right colspan=2><input type=submit value='Write &raquo'></td>\n\t\t</tr>\n\t\t<tr><td>&nbsp;</td></tr>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>\n\t</form>";
    require 'template.php';
}
function write($_POST)
{
    extract($_POST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($assetid, "num", 0, 9, "Invalid stock id (dropdown)");
    if ($assetid == 0) {
        $v->addError(0, "Please select an asset");
    }
    $v->isOk($cusnum, "num", 0, 9, "Invalid customer number (dropdown)");
    $v->isOk($description, "string", 1, 255, "Invalid description.");
    if ($cusnum == 0) {
        $v->addError(0, "Please select a customer.");
    }
    // Display Errors
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>{$e['msg']}</li>";
        }
        return enter($confirm);
    }
    // See which stock selection we made
    $sql = "SELECT * FROM cubit.assets WHERE id='{$assetid}'";
    $stkRslt = db_exec($sql) or errDie("Unable to retrieve stock from Cubit.");
    $stock = pg_fetch_array($stkRslt);
    $sql = "INSERT INTO workshop (asset_id, stkcod, cusnum, serno, description, notes,\n\t\t\t\tstatus, cdate, active, e_date)\n\t\t\tVALUES ('{$assetid}', '{$stock['des']}', '{$cusnum}', '{$stock['serial']}', '{$description}',\n\t\t\t\t'" . base64_encode($notes) . "', 'Present', current_date, 'true',\n\t\t\t\t'{$ex_date}')";
    $wsRslt = db_exec($sql) or errDie("Unable to insert workshop data into Cubit.");
    $sql = "INSERT INTO hire.service_history(asset_id, description)\n\t\t\tVALUES ('{$assetid}', '{$stock['des']}')";
    db_exec($sql) or errDie("Unable to add to service history.");
    if (pg_affected_rows($wsRslt) == 0) {
        return $OUTPUT = "<center><li class=err>Could not be added to the workshop</li></center>";
    } else {
        $refnum = pglib_lastid("workshop", "refnum");
        return $OUTPUT = "<li>Successfully added to workshop</li> <script>printer(\"" . SELF . "?key=receipt&cusnum={$cusnum}&refnum={$refnum}&description={$description}&conditions={$conditions}\");</script>";
    }
}
function write_data($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($id, "num", 1, 9, "ID Field (hidden)");
    $v->isOk($surname, "string", 1, 100, "Last name");
    $v->isOk($name, "string", 0, 100, "First name");
    $v->isOk($account_id, "num", 0, 9, "Account ID (hidden)");
    $v->isOk($account_type, "string", 0, 100, "Account type (hidden)");
    $v->isOk($lead_source, "string", 0, 100, "Lead Source");
    $v->isOk($title, "string", 0, 100, "Title");
    $v->isOk($department, "string", 0, 100, "Department");
    $v->isOk($tell, "string", 0, 100, "Home Phone");
    $v->isOk($cell, "string", 0, 100, "Mobile Phone");
    $v->isOk($fax, "string", 0, 100, "Fax");
    $v->isOk($tell_office, "string", 0, 100, "Office Phone");
    $v->isOk($tell_other, "string", 0, 100, "Other Phone");
    $v->isOk($email, "string", 0, 100, "Email");
    $v->isOk($email_other, "string", 0, 100, "Other Email");
    $v->isOk($assistant, "string", 0, 100, "Assistant");
    $v->isOk($assistant_phone, "string", 0, 100, "Assistant Phone");
    $v->isOk($padd, "string", 0, 250, "Physical Address");
    $v->isOk($padd_city, "string", 0, 100, "Physical Address: City");
    $v->isOk($padd_state, "string", 0, 100, "Physical Address: State/Province");
    $v->isOk($padd_code, "string", 0, 100, "Physical Address: Postal Code");
    $v->isOk($padd_country, "string", 0, 100, "Physical Address: Country");
    $v->isOk($hadd, "string", 0, 250, "Postal Address");
    $v->isOk($hadd_city, "string", 0, 100, "Postal Address: City");
    $v->isOk($hadd_state, "string", 0, 100, "Postal Address: State/Province");
    $v->isOk($hadd_code, "string", 0, 100, "Postal Address: Postal Code");
    $v->isOk($hadd_country, "string", 0, 100, "Postal Address: Country");
    $v->isOk($description, "string", 0, 100, "Description");
    $v->isOk($website, "string", 0, 255, "Website");
    $v->isOk($religion, "string", 0, 100, "Religion");
    $v->isOk($race, "string", 0, 100, "Race");
    $v->isOk($gender, "string", 0, 6, "Gender");
    $v->isOk($Con, "string", 2, 3, "Invalid private.");
    $v->isOk($salespn, "num", 1, 9, "Sales person.");
    $v->isOk($team_id, "num", 1, 9, "Team");
    if (!empty($ncdate_day) || !empty($ncdate_month) || !empty($ncdate_year)) {
        $v->isOk($ncdate_day, "num", 1, 2, "Next contact date (Day)");
        $v->isOk($ncdate_month, "num", 1, 2, "Next contact date (Month)");
        $v->isOk($ncdate_year, "num", 4, 4, "Next contact date (Year)");
        $ncdate = ", ncdate = '{$ncdate_year}-{$ncdate_month}-{$ncdate_day}'";
    } else {
        $ncdate = "";
    }
    $birthdate = "{$bf_year}-{$bf_month}-{$bf_day}";
    if ($v->isOk($birthdate, "string", 1, 100, "Birthdate")) {
        if (!checkdate($bf_month, $bf_day, $bf_year)) {
            $v->addError("_OTHER", "Invalid birthdate. No such date exists.");
        }
    }
    $birthdate_description = date("d F Y", mktime(0, 0, 0, $bf_day, $bf_month, $bf_year));
    # display errors, if any
    if ($v->isError()) {
        $err = "The following field value errors occured:<br>";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            if ($e["value"] == "_OTHER") {
                $err .= "<li class='err'>{$e['msg']}</li>";
            } else {
                $err .= "<li class='err'>Invalid characters: {$e['msg']}</li>";
            }
        }
        return get_data($_POST, $err);
    }
    db_conn('crm');
    if (!pglib_transaction("BEGIN")) {
        return "<li class='err'>Unable to edit lead(TB)</li>";
    }
    $Sl = "SELECT * FROM leads WHERE id='{$id}'";
    $Ry = db_exec($Sl) or errDie("Unable to get lead details.");
    if (pg_num_rows($Ry) < 1) {
        return "Invalid lead.";
    }
    $cdata = pg_fetch_array($Ry);
    if ($account_type == "Customer") {
        db_conn("cubit");
        $sql = "SELECT surname FROM customers WHERE cusnum='{$account_id}'";
        $rslt = db_exec($sql) or errDie("Error reading account name (customers)");
        if (pg_num_rows($rslt) > 0) {
            $accountname = pg_fetch_result($rslt, 0, 0);
        } else {
            $account_id = 0;
            $accountname = "";
            $account_type = "";
        }
    } else {
        if ($account_type == "Supplier") {
            db_conn("cubit");
            $sql = "SELECT supname FROM suppliers WHERE supid='{$account_id}'";
            $rslt = db_exec($sql) or errDie("Error reading account name (suppliers)");
            if (pg_num_rows($rslt) > 0) {
                $accountname = pg_fetch_result($rslt, 0, 0);
            } else {
                $account_id = 0;
                $accountname = "";
                $account_type = "";
            }
        } else {
            $accountname = "";
        }
    }
    # write to db
    db_conn("crm");
    $Sql = "\r\n\t\tUPDATE leads \r\n\t\tSET surname='{$surname}', name='{$name}', accountname='{$accountname}', account_id='{$account_id}', \r\n\t\t\taccount_type='{$account_type}', lead_source='{$lead_source}', title='{$title}', department='{$department}', \r\n\t\t\tbirthdate='{$birthdate}', tell='{$tell}', cell='{$cell}', fax='{$fax}', tell_office='{$tell_office}', \r\n\t\t\ttell_other='{$tell_other}', email='{$email}', email_other='{$email_other}', assistant='{$assistant}', \r\n\t\t\tassistant_phone='{$assistant_phone}', padd='{$padd}', padd_city='{$padd_city}', padd_state='{$padd_state}', \r\n\t\t\tpadd_code='{$padd_code}', padd_country='{$padd_country}', hadd='{$hadd}', hadd_city='{$hadd_city}', \r\n\t\t\thadd_state='{$hadd_state}', hadd_code='{$hadd_code}', hadd_country='{$hadd_country}', description='{$description}', \r\n\t\t\twebsite='{$website}', religion='{$religion}', race='{$race}', gender='{$gender}', con='{$Con}', salespid='{$salespn}', \r\n\t\t\tteam_id='{$team_id}' {$ncdate}\r\n\t\tWHERE id='{$id}'";
    // Add entry to today
    if (!empty($ncdate_year) && !empty($ncdate_month) && !empty($ncdate_day)) {
        $contact_date = "{$ncdate_year}-{$ncdate_month}-{$ncdate_day}";
        addTodayEntry("Leads", $id, $contact_date, "Contact {$surname}");
    }
    $Rslt = db_exec($Sql) or errDie("Unable to access database.");
    $Data = pg_fetch_array($Rslt);
    db_conn("cubit");
    if ($cdata['supp_id'] != 0) {
        $Sl = "UPDATE suppliers SET supname='{$surname}',tel='{$tell}',fax='{$fax}',email='{$email}',supaddr='{$padd} \n {$hadd}' WHERE supid='{$cdata['supp_id']}'";
        $Ry = db_exec($Sl) or errDie("Unable to update supplier.");
    }
    if ($cdata['cust_id'] != 0) {
        $Sl = "UPDATE customers SET surname='{$surname}',tel='{$tell}',fax='{$fax}',email='{$email}',paddr1='{$padd}',addr1='{$hadd}' WHERE cusnum='{$cdata['cust_id']}'";
        $Ry = db_exec($Sl) or errDie("Unable to update customers.");
    }
    if (!pglib_transaction("COMMIT")) {
        return "<li class='err'>Unable to edit lead. (TC)</li>";
    }
    $write_data = "\r\n\t\t<table " . TMPL_tblDflts . " width='50%'>\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Lead modified</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>{$surname} has been modified.</td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t\t<p>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Quick Links</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='leads_list.php'>List leads</a></td>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='../main.php'>Main Menu</a></td>\r\n\t\t\t</tr>\r\n\t\t</table>";
    return $write_data;
}
function validate($data)
{
    extract($data);
    require_lib("validate");
    $v = new validate();
    $v->isOk($pricelist, "num", 1, 20, "Invalid pricelist selection.");
    $v->isOk($category, "num", 1, 20, "Invalid category selection.");
    $v->isOk($classification, "num", 1, 20, "Invalid classification selection.");
    $v->isOk($increase, "float", 1, 20, "Invalid increase percentage.");
    $v->isOk($decrease, "float", 1, 20, "Invalid decrease percentage.");
    if (is_numeric($pricelist) && $pricelist) {
        $sql = "SELECT listid FROM exten.pricelist WHERE listid='{$pricelist}'";
        $pricelist_rslt = db_exec($sql) or errDie("Unable to retrieve pricelist.");
        if (!pg_num_rows($pricelist_rslt)) {
            $v->addError("", "Selected pricelist does not exist.");
        }
    }
    if (is_numeric($category) && $category) {
        $sql = "SELECT catid FROM cubit.stockcat WHERE catid='{$category}'";
        $category_rslt = db_exec($sql) or errDie("Unable to retrieve category.");
        if (!pg_num_rows($category_rslt)) {
            $v->addError("", "Selected category does not exist.");
        }
    }
    if (is_numeric($classification) && $classification) {
        $sql = "SELECT clasid FROM cubit.stockclass WHERE clasid='{$classification}'";
        $classification_rslt = db_exec($sql) or errDie("Unable to retrieve classification.");
        if (!pg_num_rows($classification_rslt)) {
            $v->addError("", "Selected classification does not exist.");
        }
    }
    if ($v->isError()) {
        return enter($v->genErrors());
    }
    return true;
}
function write()
{
    extract($_REQUEST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $sndate = "{$ninv_year}-{$ninv_month}-{$ninv_day}";
    if (!checkdate($ninv_month, $ninv_day, $ninv_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    pglib_transaction("BEGIN");
    // Get invoice info
    $sql = "SELECT * FROM cubit.nons_invoices WHERE invid='{$invid}' AND div='" . USER_DIV . "'";
    $inv_rslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($inv_rslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($inv_rslt);
    $TOTAL = $inv["subtot"] + $inv["vat"];
    $notenum = pglib_lastid("cubit.nons_inv_notes", "noteid");
    $notenum++;
    // Add to the non stock credit notes
    $sql = "\r\n\t\tINSERT INTO cubit.nons_inv_notes (\r\n\t\t\tinvid, invnum, cusname, cusaddr, cusvatno, chrgvat, \r\n\t\t\tdate, subtot, vat, total, username, prd, notenum, ctyp, \r\n\t\t\tremarks, div\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['chrgvat']}', \r\n\t\t\t'{$sndate}', '{$inv['subtot']}', '{$inv['vat']}', '{$TOTAL}', '" . USER_NAME . "', '" . PRD_DB . "', '{$notenum}', '{$inv['ctyp']}', \r\n\t\t\t'{$inv['remarks']}', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to save credit note.");
    $noteid = pglib_lastid("cubit.nons_inv_notes", "noteid");
    $sql = "SELECT count(id) FROM cubit.nons_inv_items WHERE invid='{$invid}'";
    $count_rslt = db_exec($sql) or errDie("Unable to retrieve amount of items.");
    $item_count = pg_fetch_result($count_rslt, 0);
    $i = 0;
    $page = 0;
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM cubit.nons_inv_items WHERE invid='{$invid}' AND id='{$id}'";
        $item_rslt = db_exec($sql) or errDie("Unable to retrieve item.");
        $item_data = pg_fetch_array($item_rslt);
        if ($item_data['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        // Time for a new page ??
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $products[$page][] = "\r\n\t\t\t<tr valign='top'>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>\r\n\t\t\t\t\t{$ex} {$item_data['description']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>\r\n\t\t\t\t\t{$item_data['qty']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000' align='right' nowrap>\r\n\t\t\t\t\t" . CUR . " {$item_data['unitcost']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$item_data['amt']}&nbsp;</td>\r\n\t\t\t</tr>";
        $i++;
        // Create credit note item
        $sql = "\r\n\t\t\tINSERT INTO cubit.nons_note_items (\r\n\t\t\t\tnoteid, qty, description, amt, unitcost, \r\n\t\t\t\tvatcode\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$noteid}', '{$qtys[$key]}', '{$item_data['description']}', '{$amts[$key]}', '{$item_data['unitcost']}', \r\n\t\t\t\t'{$item_data['vatex']}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to create credit note item.");
        $sql = "SELECT grpid FROM cubit.assets WHERE id='{$item_data['asset_id']}'";
        $group_rslt = db_exec($sql) or errDie("Unable to retrieve group.");
        $group_id = pg_fetch_result($group_rslt, 0);
        $discount = $inv["discount"] / $item_count;
        $amt = $item_data["amt"];
        // Update royalty report and detail report
        $sql = "\r\n\t\t\tINSERT INTO hire.revenue (\r\n\t\t\t\tgroup_id, asset_id, total, discount, credit\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$group_id}', '{$item_data['asset_id']}', '-{$amt}', '-{$discount}', '1'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to update revenue.");
        $i++;
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t</tr>";
        }
    }
    // Retrieve customer debt account
    $sql = "\r\n\t\tSELECT debtacc FROM exten.departments \r\n\t\t\tLEFT JOIN cubit.customers ON departments.deptid=customers.deptid\r\n\t\tWHERE cusnum='{$inv['cusid']}'";
    $dept_rslt = db_exec($sql) or errDie("Unable to retrieve departments.");
    $debtacc = pg_fetch_result($dept_rslt, 0);
    $hireacc = $inv["accid"];
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "vat");
    $refnum = getrefnum();
    writetrans($hireacc, $debtacc, $sndate, $refnum, $inv["subtot"], "Non-Stock Invoice No. {$inv['invnum']} Credit Note No. {$noteid} Customer\r\n\t\t{$inv['cusname']}");
    if ($inv["vat"] != 0) {
        writetrans($vatacc, $debtacc, $sndate, $refnum, $inv["vat"], "Non-Stock Invoice No. {$inv['invnum']} Credit Note No. {$noteid} VAT.\r\n\t\tCustomer {$inv['cusname']}");
    }
    // Record on the statement
    $sql = "\r\n\t\tINSERT INTO cubit.stmnt (\r\n\t\t\tcusnum, invid, amount, date, type, \r\n\t\t\tdiv\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['cusid']}', '{$noteid}', '-{$TOTAL}', '{$sndate}', 'Non-Stock Credit Note, for invoice {$inv['invnum']}', \r\n\t\t\t'" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to insert to customer statement.");
    // Update the customer (Make the balance less)
    $sql = "UPDATE cubit.customers SET balance=(balance-'{$TOTAL}') WHERE cusnum='{$inv['cusid']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Update the customer (Make the balance less)
    $sql = "UPDATE cubit.open_stmnt SET balance=(balance-'{$TOTAL}') WHERE cusnum='{$inv['cusid']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Create ledger record
    custledger($inv["cusid"], $hireacc, $sndate, $noteid, "Non-Stock Credit Note {$noteid}", $TOTAL, "c");
    custCT($inv["total"], $inv["cusid"], $inv["odate"]);
    // Update non-stock invoice
    $sql = "UPDATE cubit.nons_invoices SET balance=(balance-'{$TOTAL}') WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to update non-stock invoice.");
    $sql = "\r\n\t\tINSERT INTO cubit.salesrec (\r\n\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\r\n\t\t) VALUES (\r\n\t\t\t'{$sndate}', '{$noteid}', '{$notenum}', '0', '{$inv['vat']}', '{$TOTAL}', 'nnon', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to record in sales.");
    $sql = "\r\n\t\tINSERT INTO cubit.sj (\r\n\t\t\tcid, name, des, date, \r\n\t\t\texl, vat, inc, div\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['cusid']}', '{$inv['cusname']}', 'Credit Note: {$noteid} Invoice {$inv['invnum']}', '{$sndate}', \r\n\t\t\t'-" . ($TOTAL - $inv["vat"]) . "', '{$inv['vat']}', '" . -sprint($TOTAL) . "', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to record in sj.");
    $sql = "UPDATE cubit.nons_invoices SET accepted='note' WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to update invoice.");
    com_invoice($inv["salespn"], -($TOTAL - $inv["vat"]), 0, $inv["invnum"], $sndate);
    $cc = "\r\n\t\t<script>\r\n\t\t\tCostCenter('ct', 'Credit Note', '{$sndate}',\r\n\t\t\t'Non Stock Credit Note No.{$noteid}', '" . ($TOTAL - $inv["vat"]) . "', '');\r\n\t   </script>";
    // Reverse the amounts on the coastal reports -----------------------------
    $sql = "UPDATE hire.assets_hired SET value=0 WHERE invid='{$inv['hire_invid']}'";
    db_exec($sql) or errDie("Unable to update asset hired records.");
    // Vat
    $sql = "SELECT id FROM cubit.vatcodes WHERE code='01'";
    $vd_rslt = db_exec($sql) or errDie("Unable to retrieve vatcodes.");
    $vd_id = pg_fetch_result($vd_rslt, 0);
    vatr($vd_id, $sndate, "OUTPUT", "01", $refnum, "Non-Stock Sales, invoice No.{$inv['invnum']}", $TOTAL, $inv["vat"]);
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank.");
    $bank_data = pg_fetch_array($bank_rslt);
    // Retrieve customer information
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
    $cust_data = pg_fetch_array($cust_rslt);
    if ($inv['cusid'] == "0") {
        $cust_data['surname'] = $inv['cusname'];
        $cust_data['addr1'] = $inv['cusaddr'];
        $cust_data['paddr1'] = $inv['cusaddr'];
    }
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $details .= "\r\n\t\t\t<center>\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td align='left' rowspan='2'><img src='../compinfo/getimg.php' width='230' height='47'></td>\r\n\t\t\t\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t\t\t\t<td align='right'><font size='5'><b>Tax Credit Note</b></font></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Credit Note No:</b> {$noteid}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$inv['invnum']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td align='center'><font size='4'><b>Credit Note To:</b></font></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cust_data['surname']}</b></td>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\r\n\t\t\t\t\t\t\t\t<td>&nbsp</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000' align='right'><b>Unit Price</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t{$products_out}\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td>{$remarks}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t\t\t\t<td><b>Trade Discount:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['discount']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['subtot']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['vat']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " " . sprint($TOTAL) . "</b></td>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>";
    }
    pglib_transaction("COMMIT");
    $OUTPUT = $details;
    require "../tmpl-print.php";
}
function write_req($_POST)
{
    global $_SESSION;
    # get vars
    extract($_POST);
    $user = $_SESSION["USER_NAME"];
    # validate input
    require_lib("validate");
    $v = new validate();
    if (!isset($to)) {
        $v->addError("", "No user specified");
    } else {
        foreach ($to as $arr => $arrval) {
            $v->isOk($arrval, "string", 1, 200, "Invalid recipient: {$arrval}");
        }
    }
    //	$v->isOk ($des,"string", 1,200, "Invalid message.");
    $v->isOk($des, "text", 1, 200, "Invalid message.");
    $v->isOk($user, "string", 1, 200, "Invalid user.");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $confirmCust . get_req();
    }
    db_conn('cubit');
    // if should send to all, clear the $to list, and add all users
    // it is cleared just incase sum1 selected All option together with another one
    // since this could cause the same message sent to the same users twice!!!!
    if (in_array("_ALL_", $to)) {
        $to = "";
        $rslt = db_exec("SELECT username FROM users");
        // if users found
        if (pg_num_rows($rslt) > 0) {
            while ($row = pg_fetch_array($rslt)) {
                $to[] = $row["username"];
            }
        }
    }
    # write to db
    // create the list of users the messages should get sent to
    $msg_results = "";
    foreach ($to as $arr => $arrval) {
        $Sql = "\n\t\t\tINSERT INTO req (\n\t\t\t\tsender, recipient, message, timesent, viewed\n\t\t\t) VALUES (\n\t\t\t\t'{$user}', '{$arrval}', '{$des}', CURRENT_TIMESTAMP, 0\n\t\t\t)";
        $Rslt = db_exec($Sql) or errDie("Unable to add to database.", SELF);
        if (pg_cmdtuples($Rslt) < 1) {
            return "Unable to access database.";
        } else {
            // if it isn't noticed that person has new messages, notify him
            $rslt = db_exec("SELECT * from req_new WHERE for_user='******' ");
            if (pg_num_rows($rslt) == 0) {
                db_exec("INSERT INTO req_new VALUES('{$arrval}')");
            }
            $msg_results .= "<tr class='datacell'><td>Your message has been sent to {$arrval}</td></tr>";
        }
    }
    $write_req = "\n\t\t<table cellpadding='2' cellspacing='0' class='shtable'>\n\t\t\t<tr>\n\t\t\t\t<th>Message proccessed</th>\n\t\t\t</tr>\n\t\t\t<tr class='even'>\n\t\t\t\t<td>{$msg_results}</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table cellpadding='2' cellspacing='0' class='shtable'>\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='odd'>\n\t\t\t\t<td><a href='" . SELF . "'>Send another message</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='odd'>\n\t\t\t\t<td><a href='view_req.php'>View Messages</a></td>\n\t\t\t</tr>\n\t\t</table>";
    return $write_req;
}
function write($_POST)
{
    #get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $sdate = $syear . "-" . $smon . "-" . $sday;
    if (!checkdate($smon, $sday, $syear)) {
        $v->addError($sdate, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    // check the invoice details
    $v->isOK($cusname, "string", 1, 100, "Invalid customer name");
    $v->isOK($cusaddr, "string", 1, 100, "Invalid customer address");
    $v->isOK($cusvatno, "string", 1, 50, "Invalid customer vat number");
    if ($chrgvat != "yes" && $chrgvat != "no") {
        $v->addError($chrgvat, "Invalid vat option");
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($des[$keys], "string", 1, 255, "Invalid Description.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 10, "Invalid  Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- invoices Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    # check if purchase has been printed
    if ($inv['done'] == "y") {
        $error = "<li class=err> Error : invoice number <b>{$invid}</b> has already been printed.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # insert purchase to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # remove old items
    $sql = "DELETE FROM nons_inv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF);
    /* -- End remove old items -- */
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod)) {
                if (in_array($keys, $remprod)) {
                    # skip product (wonder if $keys still align)
                    $amt[$keys] = 0;
                    continue;
                } else {
                    # Calculate amount
                    $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                    # format ddate
                    $ddate[$keys] = "{$dyear[$keys]}-{$dmon[$keys]}-{$dday[$keys]}";
                    # insert purchase items
                    $sql = "INSERT INTO nons_inv_items(invid, qty, amt, unitcost, description, div)\n\t\t\t\t\t\t\tVALUES('{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}', '" . USER_DIV . "')";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                }
            } else {
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                # insert purchase items
                $sql = "INSERT INTO nons_inv_items(invid, qty, amt, unitcost, description, div)\n\t\t\t\t\t\tVALUES('{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}', '" . USER_DIV . "')";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = " | <input name=doneBtn type=submit value='Done'>";
        }
    } else {
        $_POST["done"] = "";
    }
    /* --- Clac --- */
    # calculate subtot
    if (isset($amt)) {
        $TOTAL = array_sum($amt);
    } else {
        $TOTAL = 0.0;
    }
    # if vat is not included
    $VATP = TAX_VAT;
    if ($chrgvat == "yes") {
        $SUBTOT = sprintf("%0.2f", $TOTAL * 100 / (100 + $VATP));
    } else {
        $SUBTOT = $TOTAL;
    }
    // compute the sub total (total - vat), done this way because the specified price already includes vat
    $VAT = $TOTAL - $SUBTOT;
    /* --- End Clac --- */
    # insert purchase to DB
    $sql = "UPDATE nons_invoices SET\n\t\t\t\tcusname = '{$cusname}', cusaddr = '{$cusaddr}', cusvatno = '{$cusvatno}', chrgvat = '{$chrgvat}', sdate = '{$sdate}',\n\t\t\t\tsubtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', remarks = '{$remarks}'\n\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (!isset($doneBtn)) {
        return details($_POST);
    } else {
        $rslt = db_exec($sql) or errDie("Unable to update invoices status in Cubit.", SELF);
        // Final Laytout
        $write = "\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t\t<tr><th>New Non-Stock Invoices</th></tr>\n\t\t\t<tr class='bg-even'><td>Non-Stock Invoices for Customer <b>{$cusname}</b> has been recorded.</td></tr>\n\t\t</table>\n\t\t<p>\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t\t<tr><th>Quick Links</th></tr>\n\t\t\t<tr class='bg-odd'><td><a href='nons-invoice-view.php'>View Non-Stock Invoices</a></td></tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t<tr class='bg-odd'><td><a href='main.php'>Main Menu</a></td></tr>\n\t\t</table>";
        return $write;
    }
}
function alloc($_POST, $err = "")
{
    extract($_POST);
    if (isset($back)) {
        if (isset($e)) {
            header("Location: cashbook-entry.php");
            exit;
        }
        return sel_cus($_POST);
    }
    if (isset($print_recpt) and strlen($print_recpt) > 0) {
        $send_print = "<input type='hidden' name='print_recpt' value='{$print_recpt}'>";
    } else {
        $send_print = "";
    }
    if (isset($bulk_pay) and strlen($bulk_pay) > 0) {
        $send_bulk = "<input type='hidden' name='bulk_pay' value='yes'>";
    } else {
        $send_bulk = "";
    }
    $all = 0;
    $date_arr = explode("-", $tdate);
    $date_year = $date_arr[0];
    $date_month = $date_arr[1];
    $date_day = $date_arr[2];
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Select Bank Account.");
    $v->isOk($date_day, "num", 1, 2, "Invalid Date day.");
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($date_month, "num", 1, 2, "Invalid Date month.");
    $v->isOk($date_year, "num", 1, 4, "Invalid Date Year.");
    $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, 10, "Invalid customer number.");
    if (strlen($date_year) != 4) {
        $v->isOk($bankname, "num", 1, 1, "Invalid Date year.");
    }
    if ($amt < 0.01) {
        $v->addError($amt, "Amount too small.");
    }
    $date = $date_day . "-" . $date_month . "-" . $date_year;
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        $confirm .= "<br>" . "<input type='button' onClick='history.back();' value='&laquo Correction'>";
        return $confirm;
        //.alloc($_POST);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    // bank account name
    if ($bankid == "0" or ($bank = qryBankAcct($bankid, "accname, bankname")) === false) {
        $bank['accname'] = "Cash";
        $bank['bankname'] = "";
    }
    // customer name
    $cus = qryCustomer($cusid, "cusname, surname");
    if ($print_recpt == "yes") {
        $show_print_recpt = "Yes";
    } else {
        $show_print_recpt = "No";
    }
    $confirm = "\n\t\t<h3>New Bank Receipt</h3>\n\t\t{$err}\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t<input type='hidden' name='accnum' value=''>\n\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t\t<input type='hidden' name='date' value='{$date}'>\n\t\t\t<input type='hidden' name='all' value='{$all}'>\n\t\t\t<input type='hidden' name='cusid' value='{$cusid}'>\n\t\t\t<input type='hidden' name='date_day' value='{$date_day}'>\n\t\t\t<input type='hidden' name='date_month' value='{$date_month}'>\n\t\t\t<input type='hidden' name='date_year' value='{$date_year}'>\n\t\t\t<input type='hidden' name='descript' value='{$descript}'>\n\t\t\t<input type='hidden' name='reference' value='{$reference}'>\n\t\t\t<input type='hidden' name='cheqnum' value='{$cheqnum}'>\n\t\t\t<input type='hidden' name='amt' value='{$amt}'>\n\t\t\t{$send_bulk}\n\t\t\t{$send_print}\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Field</th>\n\t\t\t\t<th>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Account</td>\n\t\t\t\t<td>{$bank['accname']} - {$bank['bankname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Date</td>\n\t\t\t\t<td valign='center'>{$date}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Received from</td>\n\t\t\t\t<td valign='center'>{$cus['cusname']} {$cus['surname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Description</td>\n\t\t\t\t<td valign='center'>" . nl2br($descript) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Reference</td>\n\t\t\t\t<td valign='center'>{$reference}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Cheque Number</td>\n\t\t\t\t<td valign='center'>{$cheqnum}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Amount</td>\n\t\t\t\t<td valign='center'>" . CUR . " {$amt}</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Print Receipt</td>\n\t\t\t\t<td>{$show_print_recpt}</td>\n\t\t\t</tr>";
    /* OPTION 1 : AUTO ALLOCATE (allocate) */
    #we need a new why of allocating this ... stock,nonstock,pos order is counter productive
    #so, we get them all into an array, and sort that ...
    if ($all == 0) {
        $out = $amt;
        $invs_arr = array();
        // Connect to database
        db_connect();
        #####################[ GET OUTSTANDING INVOICES ]######################
        $sql = "SELECT invnum, invid, balance, terms, odate FROM invoices WHERE cusnum = '{$cusid}' 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 = "SELECT invnum, invid, balance, odate FROM nons_invoices WHERE cusid='{$cusid}' 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\t\tSELECT invnum, invid, balance, odate \n\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\tWHERE cusnum='{$cusid}' 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']}");
        }
        if (isset($invs_arr) and is_array($invs_arr)) {
            $confirm .= "\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Type</th>\n\t\t\t\t\t<th>Invoice</th>\n\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t<th></th>\n\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t<th>Amount</th>\n\t\t\t\t</tr>";
        }
        #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") {
                $get_sql = "SELECT invnum, invid, balance, terms, odate FROM invoices WHERE cusnum = '{$cusid}' 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"]);
                    $confirm .= "\n\t\t\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' size='10' value='{$val}'>\n\t\t\t\t\t\t<input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t<td>Stock Invoice</td>\n\t\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t</tr>";
                }
            } elseif ($arr[0] == "n") {
                //sdate as
                $get_sql = "SELECT invnum, invid, balance, odate FROM nons_invoices WHERE cusid='{$cusid}' 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"]);
                    $confirm .= "\n\t\t\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' value='{$val}'>\n\t\t\t\t\t\t<input type='hidden' name='itype[{$invid}]' value='Yes'>\n\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t<td>Non Stock Invoice</td>\n\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t</tr>";
                }
            } else {
                $sqls = array();
                for ($i = 1; $i <= 12; ++$i) {
                    $sqls[] = "\n\t\t\t\t\t\tSELECT invnum, invid, balance, odate \n\t\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\t\tWHERE cusnum='{$cusid}' 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"]);
                    $confirm .= "\n\t\t\t\t\t\t<input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' size='10' value='{$val}'>\n\t\t\t\t\t\t<input type='hidden' name='ptype[{$invid}]' value='YnYn'>\n\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t<td>POS Invoice</td>\n\t\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t</tr>";
                }
            }
        }
        #if there is any amount unallocated, it goes to general transaction
        $confirm .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='6'><b>A general transaction will credit the client's account with " . CUR . " {$out} </b></td>\n\t\t\t</tr>";
    }
    vsprint($out);
    $confirm .= "\n\t\t\t<input type='hidden' name='out' value='{$out}'>\n\t\t\t<tr>\n\t\t\t\t<td><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t\t<td align='right'><input type='submit' value='Confirm &raquo'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>" . mkQuickLinks(ql("../core/trans-new.php", "Journal Transactions"), ql("../customers-view.php", "View Customers"));
    return $confirm;
}
function confirm($_POST)
{
    extract($_POST);
    if (isset($back)) {
        return method($cusid);
    }
    //	$date = "$date_day-$date_month-$date_year";
    $amt = sprint(array_sum($paidamt));
    $setamt = sprint(array_sum($stock_setamt));
    if (!isset($print_recpt)) {
        $print_recpt = "";
    }
    if (!isset($descript) or strlen($descript) < 1) {
        $descript = $reference;
    }
    if (!isset($out1)) {
        $out1 = '';
    }
    if (!isset($out2)) {
        $out2 = '';
    }
    if (!isset($out3)) {
        $out3 = '';
    }
    if (!isset($out4)) {
        $out4 = '';
    }
    if (!isset($out5)) {
        $out5 = '';
    }
    $date = "{$date_year}-{$date_month}-{$date_day}";
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($descript, "string", 1, 255, "Invalid Description.");
    $v->isOk($reference, "string", 1, 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($out, "float", 1, 40, "Invalid out amount.");
    $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).");
    $v->isOk($cusid, "num", 1, 10, "Invalid customer number.");
    $v->isOk($overpay, "float", 1, 40, "Invalid Unallocated Amount.");
    $v->isOk($print_recpt, "string", 0, 10, "Invalid Print Receipt Setting.");
    if ($amt + $overpay <= 0) {
        $v->addError(0, "Invalid Amount Allocated To Receipt.");
    }
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            if ($paidamt[$key] < 0.01) {
                continue;
            }
            if (!isset($stock_setamt[$key]) or strlen($stock_setamt[$key]) < 1) {
                $stock_setamt[$key] = 0;
            }
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No. [{$key}]");
            $v->isOk($paidamt[$key], "float", 1, 40, "Invalid amount to be paid. [{$key}]");
            $v->isOk($stock_setamt[$key], "float", 1, 40, "Invalid Settlement Discount Amount");
        }
    }
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['OUT1'] = $out1 + 0;
        $_POST['OUT2'] = $out2 + 0;
        $_POST['OUT3'] = $out3 + 0;
        $_POST['OUT4'] = $out4 + 0;
        $_POST['OUT5'] = $out5 + 0;
        return $confirm . alloc($_POST);
    }
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    $out += 0;
    $OUT1 = $out1 + 0;
    $OUT2 = $out2 + 0;
    $OUT3 = $out3 + 0;
    $OUT4 = $out4 + 0;
    $OUT5 = $out5 + 0;
    $tot = 0;
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            if ($paidamt[$key] < 0.01) {
                continue;
            }
            $tot += $paidamt[$key];
        }
    }
    if (isset($open_amount)) {
        $tot += array_sum($open_amount);
    }
    $tot = sprint($tot);
    $amt = sprint($amt);
    $out = sprint($out);
    if (sprint($tot + $out + $out1 + $out2 + $out3 + $out4 + $out5 - $amt) > sprint(0)) {
        $_POST['OUT1'] = $OUT1;
        $_POST['OUT2'] = $OUT2;
        $_POST['OUT3'] = $OUT3;
        $_POST['OUT4'] = $OUT4;
        $_POST['OUT5'] = $OUT5;
        return "<li class='err'>The total amount for invoices is greater than the amount received.\n\t\t\tPlease check the details.</li>" . alloc($_POST);
    }
    if (sprint($setamt) > 0) {
        if (array_sum($stock_setamt) != $setamt) {
            return "<li class='err'>The total settlement amount for invoices is not equal to the amount received.\n\t\t\tPlease check the details.</li>" . alloc($_POST);
        }
    }
    if (isset($bout)) {
        $out = $bout;
    }
    if (!isset($overpay)) {
        $overpay = 0;
    }
    $overpay = sprint($overpay);
    #generate a receipt number
    $receiptnumber = divlastid("receipt");
    $confirm = "\n\t\t<h3>New Bank Receipt</h3>\n\t\t<h4>Confirm entry (Please check the details)</h4>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='write'>\n\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t\t<input type='hidden' name='date' value='{$date}'>\n\t\t\t<input type='hidden' name='cusid' value='{$cusid}'>\n\t\t\t<input type='hidden' name='descript' value='{$descript}'>\n\t\t\t<input type='hidden' name='reference' value='{$reference}'>\n\t\t\t<input type='hidden' name='cheqnum' value='{$cheqnum}'>\n\t\t\t<input type='hidden' name='all' value='{$all}'>\n\t\t\t<input type='hidden' name='out' value='{$out}'>\n\t\t\t<input type='hidden' name='date_day' value='{$date_day}'>\n\t\t\t<input type='hidden' name='date_month' value='{$date_month}'>\n\t\t\t<input type='hidden' name='date_year' value='{$date_year}'>\n\t\t\t<input type='hidden' name='overpay' value='{$overpay}'>\n\t\t\t<input type='hidden' name='OUT1' value='{$OUT1}'>\n\t\t\t<input type='hidden' name='OUT2' value='{$OUT2}'>\n\t\t\t<input type='hidden' name='OUT3' value='{$OUT3}'>\n\t\t\t<input type='hidden' name='OUT4' value='{$OUT4}'>\n\t\t\t<input type='hidden' name='OUT5' value='{$OUT5}'>\n\t\t\t<input type='hidden' name='amt' value='{$amt}'>\n\t\t\t<input type='hidden' name='setamt' value='{$setamt}'>\n\t\t\t<input type='hidden' name='setvat' value='{$setvat}'>\n\t\t\t<input type='hidden' name='setvatcode' value='{$setvatcode}'>\n\t\t\t<input type='hidden' name='print_recpt' value='{$print_recpt}'>\n\t\t<table " . TMPL_tblDflts . ">";
    /* bank account name */
    if ($bankid == "0" or ($bank = qryBankAcct($bankid, "accname, bankname")) === false) {
        $bank['accname'] = "Cash";
        $bank['bankname'] = "";
    }
    /* customer name */
    $cus = qryCustomer($cusid, "accno, cusname, surname");
    if ($setvat == "inc") {
        $showsetvat = "VAT Inclusive";
    } else {
        $showsetvat = "No VAT";
    }
    //	$overpay = sprint ($amt - array_sum($paidamt));
    $overpay = sprint($overpay);
    if ($overpay < 0) {
        $overpay = 0.0;
    }
    if ($print_recpt == "yes") {
        $show_print_recpt = "Yes";
    } else {
        $show_print_recpt = "No";
    }
    $confirm .= "\n\t\t<tr>\n\t\t\t<th>Field</th>\n\t\t\t<th>Value</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Account</td>\n\t\t\t<td>{$bank['accname']} - {$bank['bankname']}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Payment Date</td>\n\t\t\t<td valign='center'>{$date}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Received from</td>\n\t\t\t<td valign='center'>{$cus['accno']} - {$cus['cusname']} {$cus['surname']}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Description</td>\n\t\t\t<td valign='center'>{$descript}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Reference</td>\n\t\t\t<td valign='center'>{$reference}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Cheque Number</td>\n\t\t\t<td valign='center'>{$cheqnum}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Amount</td>\n\t\t\t<td valign='center'>" . CUR . " {$amt}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Settlement Discount</td>\n\t\t\t<td valign='center'>" . CUR . " {$setamt} {$showsetvat}</td>\n\t\t</tr>\n\t\t" . TBL_BR . "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Print Receipt</td>\n\t\t\t<td>{$show_print_recpt}</td>\n\t\t</tr>\n\t\t" . TBL_BR . "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='5'><b>A general transaction will credit the client's account with " . CUR . " {$overpay} </b></td>\n\t\t</tr>";
    if (sprint($setamt) > 0) {
        $doset = TRUE;
    } else {
        $doset = FALSE;
    }
    /* OPTION 3 : ALLOCATE TO EACH INVOICE (confirm) */
    if ($all == 2) {
        if ($doset) {
            $showsethead = "<th>Settlement</th>";
        } else {
            $showsethead = "";
        }
        // Layout
        $confirm .= "\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><h3>Invoices</h3></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Invoice Number</th>\n\t\t\t\t<th>Outstanding amount</th>\n\t\t\t\t<th>Terms</th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t\t{$showsethead}\n\t\t\t</tr>";
        $i = 0;
        foreach ($invids as $key => $value) {
            if ($paidamt[$key] < 0.01) {
                continue;
            }
            $paidamt[$key] = sprint($paidamt[$key]);
            $ii = $invids[$key];
            if (!isset($itype[$key]) && !isset($ptype[$key])) {
                /* STOCK INVOICE ! */
                db_connect();
                $sql = "SELECT invnum,invid,balance,terms,odate FROM invoices\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to access database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class='err'> -S- Invalid ord number {$invids[$key]}.</li>";
                }
                $inv = pg_fetch_array($invRslt);
                $invid = $inv['invid'];
                #handle warnings ...
                if ($paidamt[$invid] + $stock_setamt[$invid] < sprint($inv['balance'])) {
                    $warning = "<td><li class='err'>Paying Less Than Total Amount.</li></td>";
                } elseif ($paidamt[$invid] + $stock_setamt[$invid] > sprint($inv['balance'])) {
                    $warning = "<td><li class='err'>Paying More Than Total Amount Outstanding.</li></td>";
                } else {
                    $warning = "";
                }
                if ($doset) {
                    if (!isset($stock_setamt[$invid])) {
                        $stock_setamt[$invid] = "";
                    }
                    $showset = "<td>" . CUR . " " . sprint($stock_setamt[$invid]) . "</td>";
                } else {
                    $showset = "<td></td>";
                }
                $confirm .= "\n\t\t\t\t\t<input type='hidden' name='paidamt[{$key}]' size='7' value='{$paidamt[$invid]}'>\n\t\t\t\t\t<input type='hidden' name='stock_setamt[{$key}]' value='{$stock_setamt[$invid]}'>\n\t\t\t\t\t<input type='hidden' size='20' name='invids[{$key}]' value='{$inv['invid']}'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$paidamt[$key]}</td>\n\t\t\t\t\t\t{$showset}\n\t\t\t\t\t\t{$warning}\n\t\t\t\t\t</tr>";
            } else {
                if (!isset($ptype[$key])) {
                    /* NON STOCK INVOICE ! */
                    db_connect();
                    $sql = "SELECT invnum,invid,balance,sdate as odate FROM nons_invoices\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to access database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'> -N- Invalid ord number {$invids[$key]}.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    $invid = "i" . $inv['invid'];
                    #handle warnings ...
                    if ($paidamt[$invid] + $stock_setamt[$invid] < sprint($inv['balance'])) {
                        $warning = "<td><li class='err'>Paying Less Than Total Amount.</li></td>";
                    } elseif ($paidamt[$invid] + $stock_setamt[$invid] > sprint($inv['balance'])) {
                        $warning = "<td><li class='err'>Paying More Than Total Amount Outstanding.</li></td>";
                    } else {
                        $warning = "";
                    }
                    if ($doset) {
                        if (!isset($stock_setamt[$invid])) {
                            $stock_setamt[$invid] = "";
                        }
                        $showset = "<td>" . CUR . " " . sprint($stock_setamt[$invid]) . "</td>";
                    } else {
                        $showset = "<td></td>";
                    }
                    $confirm .= "\n\t\t\t\t\t<input type='hidden' size='20' name='invids[{$key}]' value='{$inv['invid']}'>\n\t\t\t\t\t<input type='hidden' name='paidamt[{$key}]' size='7' value='" . $paidamt[$key] . "'>\n\t\t\t\t\t<input type='hidden' name='stock_setamt[{$key}]' value='{$stock_setamt[$key]}'>\n\t\t\t\t\t<input type='hidden' name='itype[{$key}]' value='PcP'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t<td>" . CUR . " " . $paidamt[$key] . "</td>\n\t\t\t\t\t\t{$showset}\n\t\t\t\t\t\t{$warning}\n\t\t\t\t\t</tr>";
                } else {
                    /* POS INVOICE ! */
                    $sqls = array();
                    for ($i = 1; $i <= 12; ++$i) {
                        $sqls[] = "SELECT invnum,invid,balance,odate FROM \"{$i}\".pinvoices WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    }
                    $sql = implode(" UNION ", $sqls);
                    // (1jun07) only checks the current prd ??????
                    //				db_conn(PRD_DB);
                    //				$sql = "SELECT invnum,invid,balance,odate FROM pinvoices
                    //						WHERE invid = '$invids[$key]' AND div = '".USER_DIV."'";
                    $invRslt = db_exec($sql) or errDie("Unable to access database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'> -P- Invalid ord number {$invids[$key]}.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    $invid = "p" . $inv['invid'];
                    #handle warnings ...
                    if ($paidamt[$invid] + $stock_setamt[$invid] < sprint($inv['balance'])) {
                        $warning = "<td><li class='err'>Paying Less Than Total Amount.</li></td>";
                    } elseif ($paidamt[$invid] + $stock_setamt[$invid] > sprint($inv['balance'])) {
                        $warning = "<td><li class='err'>Paying More Than Total Amount Outstanding.</li></td>";
                    } else {
                        $warning = "";
                    }
                    if ($doset) {
                        if (!isset($stock_setamt[$invid])) {
                            $stock_setamt[$invid] = "";
                        }
                        $showset = "<td>" . CUR . " " . sprint($stock_setamt[$invid]) . "</td>";
                    } else {
                        $showset = "<td></td>";
                    }
                    $confirm .= "\n\t\t\t\t\t<input type='hidden' size='20' name='invids[{$key}]' value='{$inv['invid']}'>\n\t\t\t\t\t<input type='hidden' name='paidamt[{$key}]' size='7' value='" . $paidamt[$key] . "'>\n\t\t\t\t\t<input type='hidden' name='stock_setamt[{$key}]' value='{$stock_setamt[$key]}'>\n\t\t\t\t\t<input type='hidden' name='ptype[{$key}]' value='PcP'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t<td>" . CUR . " " . $paidamt[$key] . "</td>\n\t\t\t\t\t\t{$showset}\n\t\t\t\t\t\t{$warning}\n\t\t\t\t\t</tr>";
                }
            }
        }
        if (open()) {
            db_conn('cubit');
            $Sl = "SELECT * FROM open_stmnt WHERE balance>0 AND cusnum='{$cusid}' ORDER BY date";
            $Ri = db_exec($Sl) or errDie("Unable to get open items.");
            //$open_out=$out;
            $ox = "";
            $i = 0;
            while ($od = pg_fetch_array($Ri)) {
                $oid = $od['id'];
                if (!isset($open_amount[$oid]) || $open_amount[$oid] == 0) {
                    continue;
                }
                $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>";
                $i++;
            }
            $confirm .= "\n\t\t\t\t<tr><td colspan='2'><br></td></tr>\n\t\t\t\t<tr><td colspan='2'>\n\t\t\t\t\t<h3>Outstanding Transactions</h3></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t<th>Amount</th>\n\t\t\t\t</tr>\n\t\t\t\t{$ox}";
        }
    }
    vsprint($out);
    vsprint($out1);
    vsprint($out2);
    vsprint($out3);
    vsprint($out4);
    vsprint($out5);
    /*
    	<tr>
    		<td colspan='5' align='right'><input type='submit' name='batch' value='Add To Batch'></td>
    	</tr>
    */
    $confirm .= "\n\t\t<input type='hidden' name='out1' value='{$out1}'>\n\t\t<input type='hidden' name='out2' value='{$out2}'>\n\t\t<input type='hidden' name='out3' value='{$out3}'>\n\t\t<input type='hidden' name='out4' value='{$out4}'>\n\t\t<input type='hidden' name='out5' value='{$out5}'>\n\t\t" . TBL_BR . "\n\t\t<tr>\n\t\t\t<td><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t<td align='right' colspan='4'><input type='submit' value='Write &raquo'></td>\n\t\t</tr>\n\t\t</table>\n\t\t</form>" . mkQuickLinks(ql("../core/trans-new.php", "Journal Transactions"), ql("../customers-view.php", "View Customers"));
    return $confirm;
}
function alloc($_POST)
{
    extract($_POST);
    if (isset($back)) {
        if (isset($e)) {
            header("Location: cashbook-entry.php");
            exit;
        }
        return sel_cus($_POST);
    }
    $passon = "";
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    for ($i = 0; $i < $rec_amount; $i++) {
        if (!isset($descript[$i]) or !isset($reference[$i]) or !isset($setamt[$i]) or empty($descript[$i]) or empty($reference[$i]) or empty($setamt[$i])) {
            continue;
        }
        $v->isOk($bankid[$i], "num", 1, 30, "Select Bank Account.");
        $v->isOk($date_day[$i], "num", 1, 2, "Invalid Date day.");
        $v->isOk($date_month[$i], "num", 1, 2, "Invalid Date month.");
        $v->isOk($date_year[$i], "num", 1, 4, "Invalid Date Year.");
        $v->isOk($descript[$i], "string", 0, 255, "Invalid Description.");
        $v->isOk($reference[$i], "string", 0, 50, "Invalid Reference Name/Number.");
        $v->isOk($cheqnum[$i], "num", 0, 30, "Invalid Cheque number.");
        $v->isOk($amt[$i], "float", 1, 40, "Invalid amount.");
        $v->isOk($setamt[$i], "float", 1, 40, "Invalid Settlement Amount.");
        $v->isOk($setvat[$i], "string", 1, 10, "Invalid Settlement VAT Option.");
        $v->isOk($setvatcode[$i], "string", 1, 40, "Invalid Settlement VAT code");
        $v->isOk($cusid[$i], "num", 1, 10, "Invalid customer number.");
        if (strlen($date_year[$i]) != 4) {
            $v->isOk($bankname, "num", 1, 1, "Invalid Date year.");
        }
        if ($amt < 0.01) {
            $v->addError($amt[$i], "Amount too small.");
        }
        $date[$i] = $date_day[$i] . "-" . $date_month[$i] . "-" . $date_year[$i];
        if (!checkdate($date_month[$i], $date_day[$i], $date_year[$i])) {
            $v->isOk($date[$i], "num", 1, 1, "Invalid date.");
        }
        // bank account name
        if (($bank = qryBankAcct($bankid[$i], "accname, bankname")) === false) {
            $bank[$i]['accname'] = "Cash";
            $bank[$i]['bankname'] = "";
        }
        // customer name
        $cus[$i] = qryCustomer($cusid[$i], "cusnum, cusname, surname");
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . method($_POST);
    }
    //	<input type='hidden' name='bankid' value='$bankid'>
    $cust_arr = array();
    $confirm = "\n\t\t<h3>New Bank Receipt</h3>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t<input type='hidden' name='accnum' value=''>\n\t\t\t<input type='hidden' name='rec_amount' value='{$rec_amount}'>\n\t\t\t<input type='hidden' name='all' value='{$all}'>\n\t\t<table " . TMPL_tblDflts . ">";
    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;
        }
        $cus0 = $cus[$t]['cusnum'];
        $cus1 = $cus[$t]['cusname'];
        $cus2 = $cus[$t]['surname'];
        // we dont do this ...
        //		$amt[$t] = $amt[$t] + $setamt[$t];
        $amt[$t] = sprint($amt[$t]);
        $setamt[$t] = sprint($setamt[$t]);
        if ($setvat[$t] == "inc") {
            $showsetvat = "VAT Inclusive";
        } else {
            $showsetvat = "No VAT";
        }
        $confirm .= "\n\t\t\t<tr>\n\t\t\t\t<th>Field</th>\n\t\t\t\t<th>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Account</td>\n\t\t\t\t<td>{$bank['accname']} - {$bank['bankname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Date</td>\n\t\t\t\t<td valign='center'>{$date[$t]}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Received from</td>\n\t\t\t\t<td valign='center'>{$cus1} {$cus2}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Description</td>\n\t\t\t\t<td valign='center'>" . nl2br($descript[$t]) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Reference</td>\n\t\t\t\t<td valign='center'>{$reference[$t]}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Cheque Number</td>\n\t\t\t\t<td valign='center'>{$cheqnum[$t]}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Amount</td>\n\t\t\t\t<td valign='center'>" . CUR . " {$amt[$t]}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Settlement Discount</td>\n\t\t\t\t<td valign='center'>" . CUR . " {$setamt[$t]} {$showsetvat}</td>\n\t\t\t</tr>";
        /* OPTION 1 : AUTO ALLOCATE (allocate) */
        if ($all == 0) {
            $out[$t] = $amt[$t];
            $invs_arr = array();
            // Connect to database
            db_connect();
            #####################[ GET OUTSTANDING INVOICES ]######################
            $sql = "SELECT invnum, invid, balance, terms, odate FROM invoices WHERE cusnum = '{$cusid[$t]}' 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 = "SELECT invnum, invid, balance, odate FROM nons_invoices WHERE cusid='{$cusid[$t]}' 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']}");
            }
            #####################[ GET OUTSTANDING POS INVOICES ]######################
            $sqls = array();
            for ($i = 1; $i <= 12; ++$i) {
                $sqls[] = "\n\t\t\t\t\tSELECT invnum, invid, balance, odate \n\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\tWHERE cusnum='{$cusid[$t]}' 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']}");
            }
            if (isset($invs_arr) and is_array($invs_arr)) {
                $confirm .= "\n\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Type</th>\n\t\t\t\t\t\t<th>Invoice</th>\n\t\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t\t<th></th>\n\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t<th>Amount</th>\n\t\t\t\t\t</tr>";
            }
            #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) {
                $arr = $invs_arr[$key];
                if ($arr[0] == "s") {
                    $get_sql = "SELECT invnum, invid, balance, terms, odate FROM invoices WHERE cusnum = '{$cusid[$t]}' 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'];
                        if (in_array($invid, $cust_arr[$cus0])) {
                            continue;
                        } else {
                            $val = allocamt($out[$t], $inv["balance"]);
                            if ($val > 0) {
                                $cust_arr[$cus0][] = $invid;
                            } else {
                                continue;
                            }
                        }
                        $confirm .= "\n\t\t\t\t\t\t\t<input type='hidden' name='paidamt[{$t}][{$invid}]' size='10' value='{$val}'>\n\t\t\t\t\t\t\t<input type='hidden' size='20' name='invids[{$t}][{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t\t<td>Stock Invoice</td>\n\t\t\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t\t</tr>";
                    }
                } elseif ($arr[0] == "n") {
                    $get_sql = "SELECT invnum, invid, balance, odate FROM nons_invoices WHERE cusid='{$cusid[$t]}' 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'];
                        if (in_array($invid, $cust_arr[$cus0])) {
                            continue;
                        } else {
                            $val = allocamt($out[$t], $inv["balance"]);
                            if ($val > 0) {
                                $cust_arr[$cus0][] = $invid;
                            } else {
                                continue;
                            }
                        }
                        $confirm .= "\n\t\t\t\t\t\t\t<input type='hidden' name='paidamt[{$t}][{$invid}]' value='{$val}'>\n\t\t\t\t\t\t\t<input type='hidden' name='itype[{$t}][{$invid}]' value='Yes'>\n\t\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t\t<td>Non Stock Invoice</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='invids[{$t}][{$invid}]' value='{$inv['invid']}'>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t\t</tr>";
                    }
                } else {
                    $sqls = array();
                    for ($i = 1; $i <= 12; ++$i) {
                        $sqls[] = "\n\t\t\t\t\t\t\tSELECT invnum, invid, balance, odate \n\t\t\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\tWHERE cusnum='{$cusid[$t]}' 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'];
                        if (in_array($invid, $cust_arr[$cus0])) {
                            continue;
                        } else {
                            $val = allocamt($out[$t], $inv["balance"]);
                            if ($val > 0) {
                                $cust_arr[$cus0][] = $invid;
                            } else {
                                continue;
                            }
                        }
                        $confirm .= "\n\t\t\t\t\t\t\t<input type='hidden' size='20' name='invids[{$t}][{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t\t\t<input type='hidden' name='paidamt[{$t}][{$invid}]' size='10' value='{$val}'>\n\t\t\t\t\t\t\t<input type='hidden' name='ptype[{$t}][{$invid}]' value='YnYn'>\n\t\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t\t<td>POS Invoice</td>\n\t\t\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t\t</tr>";
                    }
                    $out[$t] = sprint($out[$t]);
                }
            }
        }
        if ($out[$t] > 0) {
            $out[$t] = sprint($out[$t]);
            $confirm .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='4'><b>A general transaction will credit the client's account with " . CUR . " {$out[$t]} </b></td>\n\t\t\t\t</tr>";
        }
        $confirm .= TBL_BR . TBL_BR . TBL_BR;
    }
    for ($i = 0; $i < $rec_amount; $i++) {
        $passon .= "\n\t\t\t<input type='hidden' name='bankid[{$i}]' value='{$bankid[$i]}'>\n\t\t\t<input type='hidden' name='date[{$i}]' value='{$date[$i]}'>\n\t\t\t<input type='hidden' name='cusid[{$i}]' value='{$cusid[$i]}'>\n\t\t\t<input type='hidden' name='date_day[{$i}]' value='{$date_day[$i]}'>\n\t\t\t<input type='hidden' name='date_month[{$i}]' value='{$date_month[$i]}'>\n\t\t\t<input type='hidden' name='date_year[{$i}]' value='{$date_year[$i]}'>\n\t\t\t<input type='hidden' name='descript[{$i}]' value='{$descript[$i]}'>\n\t\t\t<input type='hidden' name='reference[{$i}]' value='{$reference[$i]}'>\n\t\t\t<input type='hidden' name='cheqnum[{$i}]' value='{$cheqnum[$i]}'>\n\t\t\t<input type='hidden' name='amt[{$i}]' value='{$amt[$i]}'>\n\t\t\t<input type='hidden' name='setamt[{$i}]' value='{$setamt[$i]}'>\n\t\t\t<input type='hidden' name='setvat[{$i}]' value='{$setvat[$i]}'>\n\t\t\t<input type='hidden' name='setvatcode[{$i}]' value='{$setvatcode[$i]}'>\n\t\t\t<input type='hidden' name='out[{$i}]' value='{$out[$i]}'>";
    }
    $confirm .= "\n\t\t\t{$passon}\n\t\t\t<tr>\n\t\t\t\t<td><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t\t<td align='right'><input type='submit' value='Confirm &raquo'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>" . mkQuickLinks(ql("trans-new.php", "Journal Transactions"), ql("../customers-view.php", "View Customers"));
    return $confirm;
}
function write($_GET)
{
    $showvat = TRUE;
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice number.");
    $sndate = $ninv_year . "-" . $ninv_month . "-" . $ninv_day;
    if (!checkdate($ninv_month, $ninv_day, $ninv_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    $td = $sndate;
    foreach ($ids as $key => $id) {
        $v->isOk($id, "num", 1, 20, "Invalid Item number.");
        $v->isOk($qtys[$key], "float", 1, 20, "Invalid Item quantity.");
        $v->isOk($amts[$key], "float", 1, 20, "Invalid Item amount.");
    }
    $v->isOk($subtot, "float", 1, 20, "Invalid sub-total amount.");
    $v->isOk($vat, "float", 1, 20, "Invalid vat amount.");
    $v->isOk($total, "float", 1, 20, "Invalid total amount.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM hire.hire_nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    db_conn("hire");
    $noteid = pglib_lastid("hire_nons_inv_notes", "noteid");
    $noteid++;
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* --- Start Products Display --- */
    $refnum = getrefnum();
    /*refnum*/
    $real_noteid = divlastid('note', USER_DIV);
    $vattot = 0;
    $amttot = 0;
    db_connect();
    # Products layout
    $products = array();
    $i = 0;
    $page = 0;
    foreach ($ids as $key => $id) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $sql = "SELECT * FROM hire.hire_nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $temp = $stkd['vatex'];
        if ($vd['zero'] == "Yes") {
            $stkd['vatex'] = "y";
        }
        $t = $inv['chrgvat'];
        //	$VATP = TAX_VAT;
        $VATP = $vd['vat_amount'];
        $stkacc = $stkd['accid'];
        # keep records for transactions
        if (isset($totstkamt[$stkacc])) {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] += $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] += vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($stkd['amt'] - vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        } else {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] = $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] = vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($amts[$key] - vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        }
        #add this entry's vat to a total
        $vattot = $vattot + $va;
        vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.", -vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']) - $va, -$va);
        $inv['chrgvat'] = $t;
        $sql = "UPDATE hire.hire_nons_inv_items SET rqty = (rqty + '{$qtys[$key]}') WHERE id = '{$stkd['id']}'";
        $sRslt = db_exec($sql);
        if ($stkd['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        $stkd['vatex'] = $temp;
        #add this entry's amt to a total
        $amttot = $amttot + $amts[$key];
        $sql = "INSERT INTO hire.hire_nons_note_items(noteid, qty, description, amt, unitcost, vatcode) VALUES('{$noteid}', '{$qtys[$key]}', '{$stkd['description']}', '{$amts[$key]}', '{$stkd['unitcost']}', '{$stkd['vatex']}')";
        $stkdRslt = db_exec($sql);
        #the credit note entry will get any remark entered here ? so we dont update the invoice entry ...
        //	db_conn("cubit");
        //	$sql = "UPDATE nons_invoices SET remarks='$remarks' WHERE invid='$invid'";
        //	$rslt = db_exec($sql) or errDie("Unable to save the comments to Cubit.");
        $products[$page][] = "\r\n\t\t\t\t\t\t<tr valign='top'>\r\n\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$stkd['description']}&nbsp;</td>\r\n\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$qtys[$key]}&nbsp;</td>\r\n\t\t\t\t\t\t\t<td style='border-right: 2px solid #000' align='right' nowrap>" . CUR . " {$stkd['unitcost']}&nbsp;</td>\r\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$amts[$key]}&nbsp;</td>\r\n\t\t\t\t\t\t</tr>";
        $i++;
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\r\n\t\t\t\t \t\t\t<tr>\r\n\t\t\t\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t \t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t \t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($subtot);
    $VAT = sprint($vat);
    $TOTAL = sprint($total);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "vat");
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    // print $inv['ctyp']; exit;
    db_connect();
    $tot_post = 0;
    # bank  % cust
    if ($inv['ctyp'] == 's') {
        $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cus = pg_fetch_array($custRslt);
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<li class=err>Department not Found.";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $tpp = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            $tot_post += $wamt;
            writetrans($stkacc, $dept['debtacc'], $td, $refnum, $wamt, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.");
        }
        if ($VAT != 0) {
            $tot_post += $VAT;
            writetrans($vatacc, $dept['debtacc'], $td, $refnum, $VAT, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT. Customer {$inv['cusname']}.");
        }
        $tot_dif = sprint($tot_post - $TOTAL);
        if ($tot_dif > 0) {
            writetrans($dept['debtacc'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($varacc, $dept['debtacc'], $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        }
    } elseif ($inv['ctyp'] == 'b') {
        $dept['debtacc'] = getbankaccid($inv['accid']);
        $amounts = "";
        $accids = "";
        $vats = "";
        $chrgvats = "";
        $gamt = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            # Cook vars
            $amounts .= "|{$wamt}";
            $accids .= "|{$stkacc}";
            $vats .= "|0";
            $chrgvats .= "|no";
            # Debit Customer and Credit stock
            $tot_post += $wamt;
            writetrans($stkacc, $dept['debtacc'], $td, $refnum, $wamt, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid}.");
        }
        # Debit bank and credit the account involved
        if ($VAT != 0) {
            # Cook vars
            $amounts .= "|{$VAT}";
            $accids .= "|{$vatacc}";
            $vats .= "|0";
            $chrgvats .= "|no";
            $tot_post += $VAT;
            writetrans($vatacc, $dept['debtacc'], $td, $refnum, $VAT, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT.");
        }
    } else {
        $cusacc = $inv['accid'];
        $sdate = date("Y-m-d");
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            # Debit Customer and Credit stock
            $tot_post += $wamt;
            writetrans($stkacc, $cusacc, $td, $refnum, $wamt, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid}.");
            pettyrec($cusacc, $td, "dt", "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid}.", $wamt, "Account Sale Credit note");
        }
        # Debit bank and credit the account involved
        $tot_post += $VAT;
        writetrans($vatacc, $cusacc, $td, $refnum, $VAT, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT.");
        pettyrec($cusacc, $td, "dt", "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT.", $VAT, "Account Sale Credit note VAT");
        $tot_dif = sprint($tot_post - $TOTAL);
        if ($tot_dif > 0) {
            writetrans($cusacc, $varacc, $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($varacc, $cusacc, $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        }
    }
    $sdate = date("Y-m-d");
    db_connect();
    if ($inv['ctyp'] == 's') {
        # Record the payment on the statement
        $sql = "\r\n\t\t\tINSERT INTO stmnt \r\n\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \r\n\t\t\tVALUES \r\n\t\t\t\t('{$inv['cusid']}', '{$real_noteid}', '-{$TOTAL}','{$td}', 'Non Stock Credit Note, for invoice {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance less)
        $sql = "UPDATE customers SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Update the customer (make balance less)
        $sql = "UPDATE open_stmnt SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Make ledge record
        custledger($inv['cusid'], $stkacc, $td, $real_noteid, "Non Stock Credit note {$real_noteid}", $TOTAL, "c");
        #record entry for age analysis ...
        #this function seems a little ... broken
        //custfCT($TOTAL, $inv['cusid'], $inv['age']);
        #lets rather use the system wide function and send it the invoice transaction date to do the entry for that age
        custCT($TOTAL, $inv['cusid'], $inv['odate']);
    } elseif ($inv['ctyp'] == 'cb') {
        $date = date("Y-m-d");
        # Record the Receipt record
        db_connect();
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accids, amounts,  chrgvats, vats, div,accinv) VALUES ('{$inv['jobid']}', 'withdrawal', '{$td}', '{$inv['cusname']}', 'Nons Stock Credit note for invoice {$inv['invnum']}', '0', '{$TOTAL}', 'no', '', '0', '{$inv['chrgvat']}', '0', '" . USER_DIV . "','{$stkacc}')";
        die($sql);
        $Rslt = db_exec($sql) or errDie("Unable to add bank Receipt to database.", SELF);
    }
    db_connect();
    $sql = "UPDATE hire.hire_nons_invoices SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
    # write note
    $sql = "INSERT INTO hire.hire_nons_inv_notes(invid, invnum, cusname, cusaddr, cusvatno, chrgvat, date, subtot, vat, total, username, prd, notenum, ctyp, remarks, div)";
    $sql .= " VALUES('{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['chrgvat']}', '{$td}', {$SUBTOT}, {$VAT}, {$TOTAL}, '" . USER_NAME . "', '" . PRD_DB . "', '{$real_noteid}', '{$inv['ctyp']}', '{$remarks}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to create template Non-Stock Invoice.", SELF);
    # write note items
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM hire.hire_nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $nstk = pg_fetch_array($stkdRslt);
    }
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\r\n\tVALUES('{$td}', '{$noteid}', '{$real_noteid}', '0', '{$VAT}', '{$TOTAL}', 'nnon', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\r\n\t('{$inv['cusid']}','{$inv['cusname']}','Credit Note: {$real_noteid}, Invoice {$inv['invnum']}','{$td}','" . -sprint($TOTAL - $VAT) . "','-{$VAT}','" . -sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    com_invoice($inv['salespn'], -($TOTAL - $VAT), 0, $inv['invnum'], $td);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $cc = "<script> CostCenter('ct', 'Credit Note', '{$td}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($TOTAL - $VAT) . "', ''); </script>";
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company information from Cubit.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    db_conn("cubit");
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank information from Cubit.");
    $bank_data = pg_fetch_array($bank_rslt);
    // Retrieve customer information
    db_conn("cubit");
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
    $cust_data = pg_fetch_array($cust_rslt);
    if ($inv['cusid'] == "0") {
        $cust_data['surname'] = $inv['cusname'];
        $cust_data['addr1'] = $inv['cusaddr'];
        $cust_data['paddr1'] = $inv['cusaddr'];
    }
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;\r\n\t";
    // 	$nolr_borders = "
    // 		border-top: 2px solid #000;
    // 		border-left: none;
    // 		border-right: none;
    // 		border-bottom: none;
    // 	";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $vattot = sprint($vattot);
        $amttot = sprint($amttot);
        $details .= "<center>\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='left' rowspan='2'><img src='compinfo/getimg.php' width=230 height=47></td>\r\n\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Credit Note</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t</tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Credit Note No:</b> {$real_noteid}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$inv['invnum']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='center'><font size='4'><b>Credit Note To:</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cust_data['surname']}</b></td>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\r\n\t\t\t\t\t<td>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000' align='right'><b>Unit Price</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$products_out}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$remarks}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$SUBTOT}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$VAT}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$TOTAL}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t<tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\t\t";
    }
    #fix teh date
    $date_arr = explode("-", $date);
    $cdate = "{$date_arr['2']}-{$date_arr['1']}-{$date_arr['0']}";
    // Retrieve template settings from Cubit
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve the template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        $OUTPUT = "\r\n\t\t\t<script>\r\n\t\t\t\tCostCenter('ct', 'Credit Note', '{$cdate}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($TOTAL - $VAT) . "', '');\r\n\t\t\t</script>\r\n\t\t\t{$details}";
        require "tmpl-print.php";
    } else {
        $OUTPUT = "\r\n\t\t\t<script>\r\n\t\t\t\tCostCenter('ct', 'Credit Note', '{$cdate}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($TOTAL - $VAT) . "', '');\r\n\t\t\t\tmove(\"{$template}?noteid={$noteid}&type=nonsnote\");\r\n\t\t\t</script>";
        require "template.php";
    }
}
function write_data($_POST)
{
    $date = date("Y-m-d");
    # get vars
    extract($_POST);
    if (isset($back)) {
        return get_data("");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($surname, "string", 1, 100, "Last name");
    $v->isOk($name, "string", 0, 100, "First name");
    $v->isOk($accountname, "string", 0, 100, "Account");
    $v->isOk($account_id, "num", 0, 9, "Account ID (hidden)");
    $v->isOk($account_type, "string", 0, 100, "Account type (hidden)");
    $v->isOk($lead_source, "string", 0, 100, "Lead Source");
    $v->isOk($title, "string", 0, 100, "Title");
    $v->isOk($department, "string", 0, 100, "Department");
    $v->isOk($tell, "string", 0, 100, "Home Phone");
    $v->isOk($cell, "string", 0, 100, "Mobile Phone");
    $v->isOk($fax, "string", 0, 100, "Fax");
    $v->isOk($tell_office, "string", 0, 100, "Office Phone");
    $v->isOk($tell_other, "string", 0, 100, "Other Phone");
    $v->isOk($email, "string", 0, 100, "Email");
    $v->isOk($email_other, "string", 0, 100, "Other Email");
    $v->isOk($assistant, "string", 0, 100, "Assistant");
    $v->isOk($assistant_phone, "string", 0, 100, "Assistant Phone");
    $v->isOk($padd, "string", 0, 250, "Physical Address");
    $v->isOk($padd_city, "string", 0, 100, "Physical Address: City");
    $v->isOk($padd_state, "string", 0, 100, "Physical Address: State/Province");
    $v->isOk($padd_code, "string", 0, 100, "Physical Address: Postal Code");
    $v->isOk($padd_country, "string", 0, 100, "Physical Address: Country");
    $v->isOk($hadd, "string", 0, 250, "Postal Address");
    $v->isOk($hadd_city, "string", 0, 100, "Postal Address: City");
    $v->isOk($hadd_state, "string", 0, 100, "Postal Address: State/Province");
    $v->isOk($hadd_code, "string", 0, 100, "Postal Address: Postal Code");
    $v->isOk($hadd_country, "string", 0, 100, "Postal Address: Country");
    $v->isOk($description, "string", 0, 100, "Description");
    $v->isOk($website, "string", 0, 255, "Website");
    $v->isOk($religion, "string", 0, 100, "Religion");
    $v->isOk($race, "string", 0, 100, "Race");
    $v->isOk($gender, "string", 0, 6, "Gender");
    $v->isOk($salespn, "num", 1, 9, "Sales person.");
    $v->isOK($team_id, "num", 1, 9, "Team.");
    if (!empty($ncdate_day) || !empty($ncdate_month) || !empty($ncdate_year)) {
        $v->isOk($ncdate_day, "num", 1, 2, "Next contact date (Day)");
        $v->isOk($ncdate_month, "num", 1, 2, "Next contact day (Month)");
        $v->isOk($ncdate_year, "num", 4, 4, "Next contact day (Year)");
        $ncdate_col = ", ncdate";
        $ncdate = ", '{$ncdate_year}-{$ncdate_month}-{$ncdate_day}'";
    } else {
        $ncdate_col = "";
        $ncdate = "";
    }
    $v->isOk($Con, "string", 2, 3, "Invalid private.");
    $birthdate = "{$bf_year}-{$bf_month}-{$bf_day}";
    if ($v->isOk($birthdate, "string", 1, 100, "Birthdate")) {
        if (!checkdate($bf_month, $bf_day, $bf_year)) {
            $v->addError("_OTHER", "Invalid birthdate. No such date exists.");
        }
    }
    $birthdate_description = date("d F Y", mktime(0, 0, 0, $bf_day, $bf_month, $bf_year));
    $assigned_to = USER_NAME;
    $assigned_to_id = USER_ID;
    # display errors, if any
    if ($v->isError()) {
        $err = "The following field value errors occured:<br>";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            if ($e["value"] == "_OTHER") {
                $err .= "<li class='err'>{$e['msg']}</li>";
            } else {
                $err .= "<li class='err'>Invalid characters: {$e['msg']}</li>";
            }
        }
        return get_data($err);
    }
    db_conn('cubit');
    if (!pglib_transaction("BEGIN")) {
        return "<li class='err'>Unable to add lead to database. (TB)</li>";
    }
    if (isset($supacc)) {
        $supacc = remval($supacc);
        $sql = "\r\n\t\t\tINSERT INTO  suppliers (\r\n\t\t\t\tdeptid, supno, supname, location, fcid, currency, vatnum, supaddr, contname, tel, fax, \r\n\t\t\t\temail, url, listid, bankname, branname, brancode, bankaccno, balance, fbalance, div\r\n\t\t\t) VALUES (\r\n\t\t\t\t'2', '{$supacc}', '{$surname}', 'loc', '2', 'R', '', '{$hadd} \n {$padd}', '', '{$tell}', '{$fax}', \r\n\t\t\t\t'{$email}', '', '2', '', '', '', '', 0, 0, '" . USER_DIV . "'\r\n\t\t\t)";
        $supRslt = db_exec($sql) or errDie("Unable to add supplier to the system.", SELF);
        if (pg_cmdtuples($supRslt) < 1) {
            return "<li class='err'>Unable to add supplier to database.</li>";
        }
        if (($supp_id = pglib_lastid("suppliers", "supid")) == 0) {
            return "<li class='err'>Unable to add supplier to lead list.</li>";
        }
        $accountname = $surname;
        $account_type = "Supplier";
        $account_id = $supp_id;
    } else {
        $supp_id = 0;
    }
    if (isset($cusacc)) {
        $cusacc = remval($cusacc);
        $sql = "\r\n\t\t\tINSERT INTO customers (\r\n\t\t\t\tdeptid, accno, surname, title, init, location, fcid, currency, category, class, addr1, paddr1, vatnum, \r\n\t\t\t\tcontname, bustel, tel, cellno, fax, email, url, traddisc, setdisc, pricelist, chrgint, overdue, \r\n\t\t\t\tintrate, chrgvat, credterm, odate, credlimit, blocked, balance, div,deptname,classname,catname\r\n\t\t\t) VALUES (\r\n\t\t\t\t'2', '{$cusacc}', '{$surname}', '', '', 'loc', '2', 'R', '2', '2', '{$hadd}', '{$padd}', '', \r\n\t\t\t\t'', '', '{$tell}', '{$cell}', '{$fax}', '{$email}', '', '0', '0', '2', 'yes', '0', '0', 'yes', \r\n\t\t\t\t'0', '{$date}', '0', 'no', '0', '" . USER_DIV . "','Ledger 1','General','General'\r\n\t\t\t)";
        $custRslt = db_exec($sql) or errDie("Unable to add customer to system.", SELF);
        if (pg_cmdtuples($custRslt) < 1) {
            return "<li class='err'>Unable to add customer to database.";
        }
        if (($cust_id = pglib_lastid("customers", "cusnum")) == 0) {
            return "<li class='err'>Unable to add customer to lead list.</li>";
        }
        $accountname = $surname;
        $account_type = "Customer";
        $account_id = $cust_id;
    } else {
        $cust_id = 0;
    }
    # write to db
    db_conn("crm");
    $sql = "\r\n\t\tINSERT INTO leads (\r\n\t\t\tsurname, name, accountname, account_id, account_type, lead_source, title, department, \r\n\t\t\tbirthdate, tell, cell, fax, tell_office, tell_other, email, email_other, assistant, \r\n\t\t\tassistant_phone, padd, padd_city, padd_state, padd_code, padd_country, hadd, hadd_city, \r\n\t\t\thadd_state, hadd_code, hadd_country, description, website, religion, race, gender, \r\n\t\t\tref, date, con, by, div, supp_id, cust_id, assigned_to, \r\n\t\t\tassigned_to_id {$ncdate_col}, salespid, team_id\r\n\t\t) VALUES (\r\n\t\t\t'{$surname}', '{$name}', '{$accountname}', '{$account_id}', '{$account_type}', '{$lead_source}', '{$title}', '{$department}', \r\n\t\t\t'{$birthdate}', '{$tell}', '{$cell}', '{$fax}', '{$tell_office}', '{$tell_other}', '{$email}', '{$email_other}', '{$assistant}', \r\n\t\t\t'{$assistant_phone}', '{$padd}', '{$padd_city}', '{$padd_state}', '{$padd_code}', '{$padd_country}', '{$hadd}', '{$hadd_city}', \r\n\t\t\t'{$hadd_state}', '{$hadd_code}', '{$hadd_country}', '{$description}', '{$website}', '{$religion}', '{$race}', '{$gender}', \r\n\t\t\t'', CURRENT_DATE, '{$Con}', '" . USER_NAME . "', '" . USER_DIV . "', '{$supp_id}', '{$cust_id}', '{$assigned_to}', \r\n\t\t\t'{$assigned_to_id}' {$ncdate}, '{$salespn}', '{$team_id}'\r\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to add lead to database.");
    $lead_id = pglib_lastid("leads", "id");
    // Add entry to today
    if (!empty($ncdate_year) && !empty($ncdate_month) && !empty($ncdate_day)) {
        $contact_date = "{$ncdate_year}-{$ncdate_month}-{$ncdate_day}";
        addTodayEntry("Leads", $lead_id, $contact_date, "Contact {$surname}");
    }
    if (!pglib_transaction("COMMIT")) {
        return "<li class='err'>Unable to add lead to database. (TC)</li>";
    }
    if (isset($crm)) {
        header("Location: crm/tokens-new.php?value={$surname}");
        exit;
    }
    $write_data = "\r\n\t\t<table " . TMPL_tblDflts . " width='50%'>\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Lead added</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='datacell'>\r\n\t\t\t\t<td>{$surname} has been added to Cubit.</td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t\t<p>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Quick Links</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='" . SELF . "'>Add another lead</a></td>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='../crmsystem/leads_list.php'>View Leads</a></td>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='../main.php'>Main Menu</a></td>\r\n\t\t\t</tr>\r\n\t\t</table>";
    return $write_data;
}
function confirm()
{
    global $_GET;
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($empnum, "num", 1, 9, "Invalid employee selected.");
    $v->isOk($expacc_pension, "string", 1, 3, "Invalid pension account.");
    $v->isOk($expacc_provident, "string", 1, 3, "Invalid provident account.");
    $v->isOk($expacc_medical, "string", 1, 3, "Invalid medical account.");
    $v->isOk($expacc_ret, "string", 1, 3, "Invalid retirement annuity account.");
    $v->isOk($expacc_uif, "string", 1, 3, "Invalid uif account.");
    $v->isOk($expacc_salwages, "string", 1, 3, "Invalid salaries and wages account.");
    $v->isOk($expacc_sdl, "string", 1, 3, "Invalid sdl account.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return slctAcc($confirm);
    }
    $fields = array("Pension" => "pension", "Provident" => "provident", "UIF" => "uif", "Medical Aid" => "medical", "Retirement Annuity" => "ret", "Salaries & Wages" => "salwages", "SDL" => "sdl");
    foreach ($fields as $fdesc => $fn) {
        if (isb(${"expacc_{$fn}"})) {
            $v->addError("", "Account is blocked for: {$fdesc}");
        }
        $rslt = get("core", "accname", "accounts", "accid", ${"expacc_{$fn}"});
        ${"name_{$fn}"} = pg_fetch_result($rslt, 0, 0);
    }
    $emp_ded = "";
    if (isset($dedaccs) && is_array($dedaccs)) {
        foreach ($dedaccs as $key => $value) {
            if (!$v->isOk($key . $value, "string", 2, 20, "")) {
                continue;
            }
            // salded
            db_conn("cubit");
            $sql = "SELECT salded.deduction FROM salded, empdeduct\n\t\t\t\t\tWHERE salded.id=empdeduct.dedid AND empdeduct.id='{$key}'";
            $rslt = db_exec($sql);
            $salded = pg_fetch_array($rslt);
            if (isb($value)) {
                $v->addError("", "Account is blocked for: {$salded['deduction']}");
            }
            // accounts
            $name_ded = pg_fetch_result(get("core", "accname", "accounts", "accid", $value), 0, 0);
            $emp_ded .= "\n\t\t\t<input type='hidden' name='dedaccs[{$key}]' value='{$value}'>\n\t\t\t<tr bgcolor=" . bgcolorg() . ">\n\t\t\t\t<td>{$salded['deduction']}</td>\n\t\t\t\t<td>{$name_ded}</td>\n\t\t\t</tr>";
        }
    }
    $emp_allow = "";
    if (isset($allowaccs) && is_array($allowaccs)) {
        foreach ($allowaccs as $key => $value) {
            if (!$v->isOk($key . $value, "string", 2, 20, "")) {
                continue;
            }
            // salded
            db_conn("cubit");
            $sql = "SELECT allowances.allowance FROM allowances, empallow\n\t\t\t\t\tWHERE allowances.id=empallow.allowid AND empallow.id='{$key}'";
            $rslt = db_exec($sql);
            $allowinfo = pg_fetch_array($rslt);
            if (isb($value)) {
                $v->addError("", "Account is blocked for: {$allowinfo['allowance']}");
            }
            // accounts
            $name_allow = pg_fetch_result(get("core", "accname", "accounts", "accid", $value), 0, 0);
            $emp_allow .= "\n\t\t\t<input type='hidden' name='allowaccs[{$key}]' value='{$value}'>\n\t\t\t<tr bgcolor=" . bgcolorg() . ">\n\t\t\t\t<td>{$allowinfo['allowance']}</td>\n\t\t\t\t<td>{$name_allow}</td>\n\t\t\t</tr>";
        }
    }
    // display account block errors if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return slctAcc($confirm);
    }
    $confirm = "\n\t\t<h3>Company Contributions to Employee Deductions Expense Accounts</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<form action='" . SELF . "' method='GET'>\n\t\t\t<input type='hidden' name='key' value='write'>\n\t\t\t<input type='hidden' name='empnum' value='{$empnum}'>";
    foreach ($fields as $fn) {
        $confirm .= "<input type='hidden' name='expacc_{$fn}' value='" . ${"expacc_{$fn}"} . "'>";
    }
    $confirm .= "\n\t\t\t<tr>\n\t\t\t\t<th>Field</th>\n\t\t\t\t<th>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Salaries and Wages</td>\n\t\t\t\t<td>{$name_salwages}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Pension Fund</td>\n\t\t\t\t<td>{$name_pension}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Provident Fund</td>\n\t\t\t\t<td>{$name_provident}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Retirement Annuity Fund</td>\n\t\t\t\t<td>{$name_ret}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Medical Aid</td>\n\t\t\t\t<td>{$name_medical}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>UIF</td>\n\t\t\t\t<td>{$name_uif}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Skills Development Levy</td>\n\t\t\t\t<td>{$name_sdl}</td>\n\t\t\t</tr>\n\t\t\t{$emp_ded}\n\t\t\t<tr><th colspan='2'>Allowances</th></tr>\n\t\t\t{$emp_allow}\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input type='button' value='&laquo Back' onClick='javascript:history.back()'></td>\n\t\t\t\t<td align='right'><input type='submit' value='Add Link &raquo'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>" . mkQuickLinks(ql("../admin-employee-add.php", "Add Employee"), ql("../admin-employee-view.php", "View Employees"));
    return $confirm;
}
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 confirm($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($stkid, "num", 1, 50, "Invalid stock id.");
    if (!ext_isUnique(ext_remBlnk($sers))) {
        $v->isOk("error", "num", 1, 1, "Error : Serial numbers must be unique.");
    }
    foreach ($sers as $key => $serno) {
        if (strlen($serno) > 0) {
            $v->isOk($serno, "string", 1, 20, "Error : Invalid Serial number.");
            if (preg_match("/[-\\/\\'\"]/", $serno)) {
                $v->addError(0, "Error: Serial number cannot contain any of the following characters - / \\ ' \"");
            }
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
    }
    db_connect();
    $sql = "SELECT stkid, stkcod, stkdes, units FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
    $stk = pg_fetch_array($stkRslt);
    // Layout
    $confirm = "\r\n\t\t<h3>Confirm Serial Numbers</h3>\r\n\t\t<form action='" . SELF . "' method='POST'>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<input type='hidden' name='key' value='write'>\r\n\t\t\t<input type='hidden' name='stkid' value='{$stkid}'>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>Stock</td>\r\n\t\t\t\t<td align='center'>{$stk['stkcod']} {$stk['stkdes']}</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr><td><br></td></tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td align='right'><input type='button' value='Back' onclick='javascript:history.back();'></td>\r\n\t\t\t\t<td valign='left'><input type='submit' value='Write &raquo;'></td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<th colspan='2'>Serial Numbers</th>\r\n\t\t\t</tr>";
    foreach ($sers as $key => $serno) {
        if (strlen($serno) < 1) {
            continue;
        }
        $confirm .= "\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td align='center' colspan='2'><input type='hidden' name='sers[]' size='20' value='{$serno}'>{$serno}</td>\r\n\t\t\t\t</tr>";
    }
    $confirm .= "\r\n\t\t\t\t<tr><td><br></td></tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='right'><input type='button' value='Back' onclick='javascript:history.back();'></td>\r\n\t\t\t\t\t<td valign='left'><input type='submit' value='Write &raquo;'></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</form>\r\n\t\t\t<p>\r\n\t\t\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th>Quick Links</th>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><a href='pricelist-view.php'>View Price Lists</a></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>";
    return $confirm;
}
function writeLoan($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    $v->isOk($loanid, "num", 1, 20, "Invalid loan ID.");
    $v->isOk($loanamt, "float", 1, 10, "Invalid loan amount.");
    $v->isOk($loanint, "float", 1, 5, "Invalid loan interest.");
    $v->isOk($loanperiod, "num", 1, 3, "Invalid payback period.");
    $v->isOk($loaninstall, "float", 1, 10, "Invalid monthly installment.");
    $v->isOk($fringebenefit, "float", 1, 10, "Invalid fringe benefit amount.");
    $v->isOk($accid, "num", 1, 9, "Invalid bank account selected.");
    $v->isOk($account, "num", 1, 9, "Invalid contra account selected.");
    $v->isOk($loan_account, "num", 1, 9, "Invalid loan account selected.");
    $v->isOk($loan_type, "num", 1, 9, "Invalid loan type selected.");
    $ldate = mkdate($lyear, $lmonth, $lday);
    $v->isOk($ldate, "date", 1, 1, "Invalid loan date.");
    $archdate = mkdate($arch_year, $arch_month, $arch_day);
    $v->isOk($archdate, "date", 1, 1, "Invalid approval/denial date.");
    if (!checkdate($lmonth, $lday, $lyear)) {
        $v->addError("", "Invalid date.");
    }
    if ($account > 0 && isb($account) || isb($loan_account)) {
        $v->addError("", "Main accounts blocked. Please select sub accounts.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return enterLoan($confirmCust);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($ldate) >= strtotime($blocked_date_from) and strtotime($ldate) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($archdate) >= strtotime($blocked_date_from) and strtotime($archdate) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    # get employee details
    db_connect();
    $sql = "SELECT * FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "'";
    $empRslt = db_exec($sql) or errDie("Unable to select employees from database.");
    if (pg_numrows($empRslt) < 1) {
        return "Invalid employee ID.";
    }
    $myEmp = pg_fetch_array($empRslt);
    if (!isset($deny)) {
        # check for previous loan
        $sql = "SELECT empnum FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "' AND gotloan='t'::bool";
        $chkRslt = db_exec($sql) or errDie("Unable to check existing loans for employee.");
        if (pg_numrows($chkRslt) > 0) {
            return "<li class='err'>Loan already exists for employee number: {$empnum}.</li>";
        }
    }
    $date = date("Y-m-d");
    pglib_transaction("BEGIN");
    $totamount = sprint($loanperiod * $loaninstall);
    $loanint_amt = $totamount - $loanamt;
    $sql = "\n\t\tINSERT INTO emp_loanarchive (\n\t\t\tempnum, loanamt, loaninstall, loanint, loanperiod, loandate, archdate, loan_type, \n\t\t\tdiv, status\n\t\t) VALUES (\n\t\t\t'{$empnum}', '{$totamount}', '{$loaninstall}', '{$loanint}', '{$loanperiod}', '{$ldate}', '{$archdate}', '{$loan_type}', \n\t\t\t'" . USER_DIV . "', '" . (isset($deny) ? "D" : "A") . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to pre archive loan.");
    $loanaid = pglib_lastid('emp_loanarchive', 'id');
    $rem_sql = "DELETE FROM loan_requests WHERE id = '{$loanid}'";
    $run_rem = db_exec($rem_sql) or errDie("Unable to get loan requests information.");
    if (!isset($deny)) {
        $refnum = getrefnum();
        if ($accid > 0) {
            $bankacc = getbankaccid($accid);
        }
        if ($account > 0) {
            $bankacc = $account;
        }
        writetrans($loan_account, $bankacc, $archdate, $refnum, $loanamt, "Loan granted to employee {$myEmp['fnames']} {$myEmp['sname']}.");
        if ($accid > 0) {
            banktrans($accid, "withdrawal", $archdate, "{$myEmp['fnames']} {$myEmp['sname']}", "Loan granted to employee {$myEmp['fnames']} {$myEmp['sname']}.", 0, $loanamt, $loan_account);
        }
        # write to db
        $sql = "\n\t\t\tUPDATE cubit.employees \n\t\t\tSET loanamt = '{$totamount}', loanint = '{$loanint}', loanint_amt = '{$loanint_amt}', loanint_unpaid = '{$loanint_amt}', \n\t\t\t\tloanperiod = '{$loanperiod}', loaninstall = '{$loaninstall}', gotloan = 't'::bool, loanpayslip = '{$loanamt}', \n\t\t\t\tloanfringe = '{$fringebenefit}', loandate = '{$archdate}', expacc_loan = '{$loan_account}', \n\t\t\t\tloanamt_tot = '{$totamount}', loanid = '{$loanaid}' \n\t\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
        $loanRslt = db_exec($sql) or errDie("Unable to add loan to system.", SELF);
        if (pg_cmdtuples($loanRslt) < 1) {
            return "Unable to add loan to system.";
        }
    }
    pglib_transaction("COMMIT");
    $OUT = "<table " . TMPL_tblDflts . ">";
    if (isset($deny)) {
        $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<th>Loan Denied And Request Archived.</th>\n\t\t\t</tr>";
    } else {
        $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<th>Loan Granted And Added To System</th>\n\t\t\t</tr>";
    }
    $OUT .= "\n\t\t<tr class='datacell'>\n\t\t\t<td>Loan information successfully updated.</td>\n\t\t</tr>\n\t\t" . TBL_BR;
    if (!isset($deny)) {
        $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<td><input type='button' onclick=\"document.location='../reporting/loan_approval.php?id={$loanaid}'\" value='Generate Approval Report'></td>\n\t\t\t</tr>";
    }
    $OUT .= "\n\t\t</table><br>" . mkQuickLinks(ql("loan_apply.php", "Add Loan Application"), ql("loan_apply_view.php", "View Loan Applications"), ql("../admin-employee-add.php", "Add Employee"), ql("../admin-employee-view.php", "View Employees"));
    return $OUT;
}
function write($_POST)
{
    extract($_POST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($stkid, "num", 0, 9, "Invalid stock id (dropdown)");
    $v->isOk($stkname, "string", 0, 255, "Invalid stock name (input field)");
    $v->isOk($cusnum, "num", 0, 9, "Invalid customer number (dropdown)");
    $v->isOk($serno, "string", 0, 255, "Invalid serial number.");
    $v->isOk($description, "string", 1, 255, "Invalid description.");
    if ($stkid != 0 && !empty($stkname)) {
        $v->addError(0, "Please use either stock dropdown or stock input, not both.");
    }
    if ($stkid == 0 && empty($stkname)) {
        $v->addError(0, "Please select stock from the dropdown or input field.");
    }
    if ($cusnum == 0) {
        $v->addError(0, "Please select a customer.");
    }
    // Display Errors
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return enter($confirm);
    }
    // See which stock selection we made
    if ($stkid != 0) {
        db_conn("cubit");
        $sql = "SELECT stkcod FROM stock WHERE stkid='{$stkid}'";
        $stkRslt = db_exec($sql) or errDie("Unable to retrieve stock from Cubit.");
        $stkcod = pg_fetch_result($stkRslt, 0);
    } else {
        $stkcod = $stkname;
    }
    $sql = "INSERT INTO workshop (stkcod, cusnum, serno, description, notes, status, cdate, active) VALUES ('{$stkcod}', '{$cusnum}', '{$serno}', '{$description}', '" . base64_encode($notes) . "', 'Present', current_date, 'true')";
    $wsRslt = db_exec($sql) or errDie("Unable to insert workshop data into Cubit.");
    if (pg_affected_rows($wsRslt) == 0) {
        return $OUTPUT = "<center><li class='err'>Could not be added to the workshop</li></center>";
    } else {
        $refnum = pglib_lastid("workshop", "refnum");
        return $OUTPUT = "<li>Successfully added to workshop</li> <script>printer(\"" . SELF . "?key=receipt&cusnum={$cusnum}&refnum={$refnum}&description={$description}&conditions={$conditions}&serno={$serno}\");</script>";
    }
}
function write($_POST)
{
    #get vars
    extract($_POST);
    if (isset($cusnum) && customer_overdue($cusnum)) {
        return details($_POST, "<li class='err'>Customer is overdue, account blocked!</li>");
    }
    $pcredit += 0;
    $pcash += 0;
    $pcheque += 0;
    $pcc += 0;
    $deptid += 0;
    db_conn('cubit');
    if (isset($printsales)) {
        $Sl = "SELECT * FROM settings WHERE constant='PSALES'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('PSALES','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='PSALES' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='PSALES' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    //$it+=0;
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($client)) {
        $v->isOk($client, "string", 0, 20, "Invalid Customer.");
    } else {
        $client = "";
    }
    if (isset($vatnum)) {
        $v->isOk($vatnum, "string", 0, 30, "Invalid VAT Number.");
    } else {
        $vatnum = "";
    }
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($telno, "string", 0, 20, "Invalid Customer Telephone Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($ordno, "string", 0, 20, "Invalid sales order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($pinv_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($pinv_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($pinv_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day;
    if (!checkdate($pinv_month, $pinv_day, $pinv_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day;
    if (!checkdate($pinv_month, $pinv_day, $pinv_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        if (!ext_isUnique(ext_remBlnk($sernos))) {
            //$v->isOk ($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # check is serial no was selected
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            if (is_numeric($stkid)) {
                $sql = "SELECT units, stkcod FROM cubit.stock WHERE stkid='{$stkid}'";
                $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
                list($stock_units, $stock_code) = pg_fetch_array($stock_rslt);
                if ($qtys[$keys] > $stock_units) {
                    $v->addError(0, "Not enough stock available for {$stock_code}");
                }
            }
            # check if serial is selected
            if (ext_isSerial("stock", "stkid", $stkid) && !isset($sernos[$keys])) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number (2): <b>" . ($keys + 1) . "</b>");
            } elseif (ext_isSerial("stock", "stkid", $stkid) && strlen($sernos[$keys]) <= 0 && strlen($sernos_ss[$keys]) <= 0) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number (1): <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>.");
            if ($disc[$keys] > $unitcost[$keys]) {
                $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost.");
            }
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    $cusnum += 0;
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    $des = remval($des);
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return details($_POST, $err);
    }
    if (strlen($client) < 1) {
        $client = "Cash Sale";
    }
    if (strlen($vatnum) < 1) {
        $vatnum = "";
    }
    $_POST['client'] = $client;
    $_POST['vatnum'] = $vatnum;
    $_POST['telno'] = $telno;
    $_POST['cordno'] = $cordno;
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['traddisc'] = $traddisc;
    $inv['chrgvat'] = $chrgvat;
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $traddisc += 0;
    $delchrg += 0;
    $vatamount = 0;
    $showvat = TRUE;
    # insert invoice to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # get selected stock in this invoice
    $sql = "SELECT * FROM pinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(alloc + qty)
        $sql = "UPDATE stock SET alloc = (alloc - '{$stkt['qty']}')  WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if (strlen($stkt['serno']) > 0) {
            ext_unresvSer($stkt['serno'], $stkt['stkid']);
        }
    }
    # remove old items
    $sql = "DELETE FROM pinv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            /* set the serial ss field for serials selected from list */
            if ($sernos_ss[$keys] == "*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*") {
                $sernos_ss[$keys] = $sernos[$keys];
            }
            if (isset($remprod) && in_array($keys, $remprod)) {
                if ($sernos[$keys] == $sernos_ss[$keys] && $sernos_ss[$keys] != "") {
                    $chr = substr($sernos[$keys], strlen($sernos[$keys]) - 1, 1);
                    $tab = "ss{$chr}";
                    /* mark barcoded item as unavailable */
                    $sql = "UPDATE " . $tab . " SET active='yes' WHERE code = '{$sernos[$keys]}' AND div = '" . USER_DIV . "'";
                    db_exec($sql);
                }
            } else {
                if (isset($accounts[$keys]) && $accounts[$keys] != 0) {
                    $accounts[$keys] += 0;
                    # Get selamt from selected stock
                    db_conn('core');
                    $Sl = "SELECT * FROM accounts WHERE accid='{$accounts[$keys]}'";
                    $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                    $ad = pg_fetch_array($Ri);
                    $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                    $Ri = db_exec($Sl);
                    if (pg_num_rows($Ri) < 1) {
                        return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                    }
                    $vd = pg_fetch_array($Ri);
                    if ($vd['zero'] == "Yes") {
                        $excluding = "y";
                    } else {
                        $excluding = "";
                    }
                    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                        $showvat = FALSE;
                    }
                    $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                    $vrs = explode("|", $vr);
                    $ivat = $vrs[0];
                    $iamount = $vrs[1];
                    $vatamount += $ivat;
                    # Check Tax Excempt
                    if ($vd['zero'] == "Yes") {
                        $taxex += $amt[$keys];
                        $exvat = "y";
                    } else {
                        $exvat = "n";
                    }
                    //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                    $vatcodes[$keys] += 0;
                    $accounts[$keys] += 0;
                    $descriptions[$keys] = remval($descriptions[$keys]);
                    $wtd = $whids[$keys];
                    # insert invoice items
                    $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost,\n\t\t\t\t\t\t\t\tamt, disc, discp, ss, serno, div,vatcode,description,\n\t\t\t\t\t\t\t\taccount)\n\t\t\t\t\t\t\tVALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}',\n\t\t\t\t\t\t\t\t'{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}',\n\t\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '', '','" . USER_DIV . "',\n\t\t\t\t\t\t\t\t'{$vatcodes[$keys]}','{$descriptions[$keys]}',\n\t\t\t\t\t\t\t\t'{$accounts[$keys]}')";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                } else {
                    # get selamt from selected stock
                    $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                    $stkRslt = db_exec($sql);
                    $stk = pg_fetch_array($stkRslt);
                    # Calculate the Discount discount
                    if ($disc[$keys] < 1) {
                        if ($discp[$keys] > 0) {
                            $disc[$keys] = $discp[$keys] / 100 * $unitcost[$keys];
                        }
                    } else {
                        $discp[$keys] = $disc[$keys] * 100 / $unitcost[$keys];
                    }
                    # Calculate amount
                    $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]);
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                    $Ri = db_exec($Sl);
                    if (pg_num_rows($Ri) < 1) {
                        return details($_POST, "<li class=err>Please select the vatcode for all your items.</li>");
                    }
                    $vd = pg_fetch_array($Ri);
                    if ($vd['zero'] == "Yes") {
                        $excluding = "y";
                    } else {
                        $excluding = "";
                    }
                    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                        $showvat = FALSE;
                    }
                    $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                    $vrs = explode("|", $vr);
                    $ivat = $vrs[0];
                    $iamount = $vrs[1];
                    $vatamount += $ivat;
                    # Check Tax Excempt
                    if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                        $taxex += $amt[$keys];
                        $exvat = "y";
                    } else {
                        $exvat = "n";
                    }
                    $wtd = $whids[$keys];
                    # insert invoice items
                    $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty,\n\t\t\t\t\t\t\t\tunitcost, amt, disc, discp, ss, serno, div,vatcode)\n\t\t\t\t\t\t\tVALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}',\n\t\t\t\t\t\t\t\t'{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}',\n\t\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '{$sernos_ss[$keys]}', '{$sernos[$keys]}',\n\t\t\t\t\t\t\t\t'" . USER_DIV . "','{$vatcodes[$keys]}')";
                    // $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, div) VALUES('$invid', '$whids[$keys]', '$stkids[$keys]', '$qtys[$keys]', '$unitcost[$keys]','$amt[$keys]', '$disc[$keys]', '$discp[$keys]', '".USER_DIV."')";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                    if (strlen($sernos[$keys]) > 0) {
                        ext_resvSer($sernos[$keys], $stk['stkid']);
                    }
                    # update stock(alloc + qty)
                    $sql = "UPDATE stock SET alloc = (alloc + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                    $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
                }
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Process'>";
        }
    } else {
        $_POST["done"] = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$delvat}'";
    $Ri = db_exec($Sl);
    // 		/*if(pg_num_rows($Ri)>0) {
    // 			*/$taxex += $delchrg;
    // 		}
    $vd = pg_fetch_array($Ri);
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    $_POST['showvat'] = $showvat;
    $vr = vatcalc($delchrg, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $vatamount += $ivat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        // 			$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = sprint($vatamount);
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        // 			$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = sprint($vatamount);
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    $Sl = "SELECT * FROM posround";
    $Ri = db_exec($Sl);
    $data = pg_fetch_array($Ri);
    if ($data['setting'] == "5cent") {
        if (sprint(floor(sprint($TOTAL / 0.05))) != sprint($TOTAL / 0.05)) {
            $otot = $TOTAL;
            $nTOTAL = sprint(sprint(floor($TOTAL / 0.05)) * 0.05);
            $rounding = $otot - $nTOTAL;
        } else {
            $rounding = 0;
        }
    } else {
        $rounding = 0;
    }
    //print sprint(floor($TOTAL/0.05));
    #get accno if invoice is on credit
    if ($cusnum != "0") {
        $get_acc = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
        $run_acc = db_exec($get_acc) or errDie("Unable to get customer information");
        if (pg_numrows($run_acc) < 1) {
            $accno = "";
        } else {
            $arr = pg_fetch_array($run_acc);
            $cusacc = $arr['accno'];
        }
    } else {
        $cusacc = "";
    }
    //	die($cusnum);
    # insert invoice to DB
    $sql = "UPDATE pinvoices SET pcredit='{$pcredit}',cusnum='{$cusnum}',delvat='{$delvat}',rounding='{$rounding}',pcash='{$pcash}',pcheque='{$pcheque}',\n\t\tpcc='{$pcc}',deptid='{$deptid}',deptname = '{$dept['deptname']}', cusname = '{$client}', cordno = '{$cordno}', ordno = '{$ordno}',chrgvat = '{$chrgvat}',\n\t\tsalespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}',\n\t\tbalance = '{$pcredit}', comm = '{$comm}', discount='{$traddiscmt}', delivery='{$delexvat}', vatnum='{$vatnum}', cusacc = '{$cusacc}', telno='{$telno}'\n\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM pinv_data WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF);
    # put in new data
    $sql = "INSERT INTO pinv_data(invid, dept, customer, div) VALUES('{$invid}', '{$dept['deptname']}', '{$client}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice data to Cubit.", SELF);
    # commit updatin
    if (strlen($bar) > 0) {
        /* check if there a stock item with global barcode matching input barcode */
        $sql = "SELECT * FROM stock WHERE bar='{$bar}' AND div = '" . USER_DIV . "'";
        $barRslt = db_exec($sql);
        if (pg_num_rows($barRslt) <= 0) {
            /* fetch last character of barcode */
            $chr = substr($bar, strlen($bar) - 1, 1);
            /* invalid barcode */
            if (!is_numeric($chr)) {
                return details($_POST, "The code you selected is invalid");
            }
            /* which barcode table to scan for stock id */
            $tab = "ss{$chr}";
            $stid = barext_dbget($tab, 'code', $bar, 'stock');
            $stab = "serial{$chr}";
            $sstid = serext_dbget($stab, 'serno', $bar, 'stkid');
            /* non-existing barcode, check for serial number */
            if ($stid <= 0) {
                if ($sstid <= 0) {
                    return details($_POST, "<li class='err'>The serial number/bar code you selected is not in the system or is not available.</li>");
                }
                if (serext_dbnum($stab, 'serno', $bar, 'stkid') > 1) {
                    return details($_POST, "<li class='err'>Duplicate serial numbers found, please scan barcode or select stock item.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $stab . " SET rsvd='y' WHERE serno='{$bar}'";
                db_exec($sql);
                $serno_bar = "{$bar}";
                $stid = $sstid;
            } else {
                if ($sstid > 0) {
                    return details($_POST, "<li class='err'>A serial and barcode with same value, please scan other value or select product manually.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $tab . " SET active='no' WHERE code='{$bar}' AND div='" . USER_DIV . "'";
                db_exec($sql);
                $serno_bar = "{$bar}";
            }
            /* fetch stock row for selected item */
            $sql = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $barRslt = db_exec($sql);
        } else {
            $serno_bar = "";
        }
        $s = pg_fetch_array($barRslt);
        /* allocate stock item */
        $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$s['stkid']}' AND div = '" . USER_DIV . "'";
        db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost, amt,\n\t\t\t\t\tdisc, discp, ss, serno, div)\n\t\t\t\tVALUES('{$invid}', '{$s['whid']}', '{$s['stkid']}', '1','{$s['selamt']}',\n\t\t\t\t\t'{$s['selamt']}', '0', '0','{$bar}', '{$serno_bar}', '" . USER_DIV . "')";
        db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($doneBtn)) {
        # check if stock was selected(yes = put done button)
        db_connect();
        $sql = "SELECT stkid FROM pinv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
        $crslt = db_exec($sql);
        if (pg_numrows($crslt) < 1) {
            $error = "<li class='err'> Error : Invoice number has no items.";
            return details($_POST, $error);
        }
        $TOTAL = sprint($TOTAL - $rounding);
        #check for credit limit
        if ($cusnum != "0") {
            #customer is selected ... get info
            $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND location != 'int' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to view customer");
            if (pg_numrows($custRslt) < 1) {
                $cust['balance'] = "0";
                $cust['creditlimit'] = "0";
            } else {
                $cust = pg_fetch_array($custRslt);
            }
            #customer is set check for response
            if ($pcredit + $cust['balance'] > $cust['credlimit']) {
                #limit reached ... check for block
                db_conn("cubit");
                $get_check = "SELECT value FROM set WHERE label = 'CUST_INV_WARN' LIMIT 1";
                $run_check = db_exec($get_check) or errDie("Unable to get credit limit response setting");
                if (pg_numrows($run_check) < 1) {
                    #no setting ? do nothing ....
                } else {
                    $sarr = pg_fetch_array($run_check);
                    if ($sarr['value'] == "block") {
                        #block account ...
                        return details($_POST, "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " " . sprint($cust["credlimit"]) . "</b> has been exceeded.</li>");
                    }
                }
                # Check permissions
                if (!perm("invoice-limit-override.php")) {
                    return details($_POST, "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " " . sprint($cust["credlimit"]) . "</b> has been exceeded.</li>");
                }
            }
        }
        if ($pcash + $pcheque + $pcc + $pcredit < $TOTAL) {
            return details($_POST, "<li class='err'>The total of all the payments is less than the invoice total</li>");
        }
        $change = sprint(sprint($pcash + $pcheque + $pcc + $pcredit) - sprint($TOTAL));
        $pcash = sprint($pcash - $change);
        if ($pcash < 0) {
            $pcash = 0;
        }
        if (sprint($pcash + $pcheque + $pcc + $pcredit) != sprint($TOTAL)) {
            return details($_POST, "<li class='err'>The total of all the payments is not equal to the invoice total.<br>\n\t\t\t(You can only overpay with cash)</li>");
        }
        # insert quote to DB
        $sql = "UPDATE pinvoices SET done = 'y' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice status in Cubit.", SELF);
        # print the invoice
        $OUTPUT = "\n\t\t\t\t\t<script>printer2('pos-invoice-print.php?invid={$invid}');</script>\n\t\t\t\t\t<input type='button' value='Create New POS Invoice' onClick=\"move('pos-invoice-new-no-neg.php');\">";
        require "template.php";
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>New Point of Sale Invoice Saved</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Invoice for <b>{$client}</b> has been saved.</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='pos-invoice-new-no-neg.php'>New Point of Sale Invoice</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-list.php'>View Point of Sale Invoices</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
        return $write;
    } elseif (isset($cancel)) {
        // Final Laytout
        $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>New Point of Sale Invoice Saved</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Invoice for <b>{$client}</b> has been saved.</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='pos-invoice-new-no-neg.php'>New Point of Sale Invoice</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-list.php'>View Point of Sale Invoices</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        return details($_POST);
    }
    /* --- End button Listeners --- */
}
function write($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $prd += 0;
    $v->isOk($purid, "num", 1, 20, "Invalid Invoice number.");
    $sndate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    $td = $sndate;
    foreach ($ids as $key => $id) {
        $v->isOk($id, "num", 1, 20, "Invalid Item number.");
        $v->isOk($qtys[$key], "num", 1, 20, "Invalid Item quantity.");
        //$v->isOk ($amts[$key], "float", 1, 20, "Invalid Item amount.");
    }
    //$v->isOk ($subtot, "float", 1, 20, "Invalid sub-total amount.");
    //$v->isOk ($vat, "float", 1, 20, "Invalid vat amount.");
    //$v->isOk ($total, "float", 1, 20, "Invalid total amount.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($sndate) >= strtotime($blocked_date_from) and strtotime($sndate) <= 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>";
    }
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    db_conn($prd);
    # Get invoice info
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found{$sql}</i>";
    }
    $inv = pg_fetch_array($invRslt);
    db_conn("cubit");
    $sql = "SELECT * FROM nons_purchasesn";
    $purRslt = db_exec($sql) or errDie("Unable to get Non-Stock Order information");
    if (pg_numrows($purRslt) < 1) {
        $noteid = 2;
    } else {
        $noteid = pglib_lastid("nons_purchasesn", "id");
        $noteid++;
    }
    $refnum = getrefnum();
    db_conn("cubit");
    if ($inv['spurnum'] > 0) {
        if ($inv['ctyp'] == "sup") {
            $inv['ctyp'] = 's';
            $inv['supid'] = $inv['typeid'];
        } elseif ($inv['ctyp'] == "led") {
            $inv['ctyp'] = 'c';
            $inv['deptid'] = $inv['typeid'];
        } else {
            $inv['ctyp'] = 'p';
        }
    }
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    if ($inv['ctyp'] == 's') {
        $sql = "SELECT * FROM suppliers WHERE supid = '{$inv['supid']}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cus = pg_fetch_array($custRslt);
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql) or errDie("Unable to get details.");
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<li class=err>Department not Found.";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
    } elseif ($inv['ctyp'] == 'c') {
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql) or errDie("Unable to get details.");
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<li class=err>Department not Found.";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $dept['credacc'] = $dept['pca'];
    } elseif ($inv['ctyp'] == 'cb') {
        $bankid = $inv['supid'];
        $bankid += 0;
        db_conn("cubit");
        $sql = "SELECT * FROM bankacct WHERE bankid = '{$bankid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class=err> Bank not Found.";
            $confirm .= "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $deptd = pg_fetch_array($deptRslt);
        }
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $rd = db_exec($Sl) or errDie("Unable to get data.");
        $data = pg_fetch_array($rd);
        $BA = $data['accnum'];
        $dept['credacc'] = $BA;
    } elseif ($inv['ctyp'] == 'p') {
        core_connect();
        # Get Petty cash account
        $cashacc = gethook("accnum", "bankacc", "name", "Petty Cash");
        # Get account name for thy lame User's Sake
        $accRslt = get("core", "*", "accounts", "accid", $cashacc);
        if (pg_numrows($accRslt) < 1) {
            return "<li class='err'> Petty Cash Account not found.</li>";
        }
        $acc = pg_fetch_array($accRslt);
        $dept['credacc'] = $cashacc;
        //$supacc = "$acc[topacc]/$acc[accnum] - $acc[accname]";
        //$hide = "<input type=hidden name=supacc value='$cashacc'><input type=hidden name=ctyp value='$ctyp'>";
    }
    db_conn($prd);
    /* --- Start Products Display --- */
    $tot_post = 0;
    # Products layout
    $products = "";
    $resub = 0;
    $revat = 0;
    foreach ($ids as $key => $id) {
        db_conn($prd);
        $sql = "SELECT * FROM nons_pur_items  WHERE purid = '{$purid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        $stkacc = $stkd['accid'];
        # keep records for transactions
        $sql = "UPDATE nons_pur_items SET rqty = (rqty + '{$qtys[$key]}') WHERE id = '{$stkd['id']}'";
        $sRslt = db_exec($sql);
        # Calculate cost amount bought
        $amt[$key] = $qtys[$key] * $unitcost[$key];
        /* delivery charge */
        # Calculate percentage from subtotal
        $perc[$key] = $amt[$key] / $SUBTOTAL * 100;
        # Get percentage from shipping charges
        $shipc[$key] = $perc[$key] / 100 * $shipchrg;
        # add delivery charges
        $amt[$key] += $shipc[$key];
        /* end delivery charge */
        # the subtotal + delivery charges
        $resub += $amt[$key];
        # calculate vat
        $svat[$key] = svat($amt[$key], $stkd['amt'], $stkd['svat']);
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        vatr($vd['id'], $td, "INPUT", $vd['code'], $refnum, "VAT for Non-Stock purchase No. {$inv['purnum']} returned", $amt[$key], $svat[$key]);
        # received vat
        $revat += $svat[$key];
        # make amount vat free
        // 		if($inv['vatinc'] == "yes"){
        // 			$amt[$key] = ($amt[$key] - $svat[$key]);
        // 		}
        $amts[$key] = $stkd['unitcost'] * $qtys[$key];
        $nv = sprint($stkd['svat'] / $stkd['qty'] * $qtys[$key]);
        if ($inv['vatinc'] != "no") {
            $aev = $amts[$key] - $nv;
        } else {
            $aev = $amts[$key];
        }
        $stkd['accid'] += 0;
        db_conn('cubit');
        $sql = "\n\t\t\tINSERT INTO nons_pur_itemsn (\n\t\t\t\tnoteid, qty, description, amt, unitcost, svat, div, \n\t\t\t\tcod, des, ddate, accid\n\t\t\t) VALUES (\n\t\t\t\t'{$noteid}', '{$qtys[$key]}', '{$stkd['des']}', '{$amts[$key]}', '{$stkd['unitcost']}', '{$stkd['svat']}', '" . USER_DIV . "', \n\t\t\t\t'{$stkd['cod']}', '{$stkd['des']}', '{$stkd['ddate']}', '{$stkd['accid']}'\n\t\t\t)";
        $stkdRslt = db_exec($sql) or errDie("Unable to insert note items.");
        if ($inv['ctyp'] == 'ac') {
            $dept['credacc'] = $inv['mpurid'];
        }
        //$sql = "INSERT INTO nons_pur_itemsn(noteid, cod, des, qty, unitcost, amt, svat, ddate, accid, div) VALUES('$nid', '$stktc[cod]', '$stktc[des]', '$qtys[$key]', '$stktc[unitcost]', '$stktc[amt]', '$stktc[svat]', '$stktc[ddate]', '$stktc[accid]', '".USER_DIV."')";
        if ($inv['spurprd'] == 0) {
            $tot_post += $aev;
            writetrans($dept['credacc'], $stkacc, $td, $refnum, $aev, "Non-Stock purchase No. {$inv['purnum']} returned, Supplier {$inv['supplier']}.");
        }
    }
    $supacc = $dept['credacc'];
    $tot_post = 0;
    $pur = $inv;
    if ($inv['spurprd'] > 0) {
        $retot = $TOTAL;
        $vatamt = $VAT;
        db_conn($pur['spurprd']);
        # Get purchase info
        $sql = "SELECT * FROM purchases WHERE purnum = '{$pur['spurnum']}' AND div = '" . USER_DIV . "'";
        $spurRslt = db_exec($sql) or errDie("Unable to get purchase information");
        if (pg_numrows($spurRslt) < 1) {
            return "<li> - purchase Not Found</li>";
        }
        $spur = pg_fetch_array($spurRslt);
        db_conn($pur['spurprd']);
        # Get selected stock
        $sql = "SELECT * FROM pur_items WHERE purid = '{$spur['purid']}' AND div = '" . USER_DIV . "'";
        $sstkdRslt = db_exec($sql);
        while ($sstk = pg_fetch_array($sstkdRslt)) {
            if ($spur['vatinc'] == "yes") {
                $csamt = sprint(($sstk['amt'] - $sstk['svat']) / $spur['subtot'] * ($retot - $vatamt));
            } else {
                $csamt = sprint($sstk['amt'] / $spur['subtot'] * ($retot - $vatamt));
            }
            db_connect();
            # get selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            /* Code insert */
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT * FROM warehouses WHERE whid = '{$stkt['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $tot_post += $csamt;
            writetrans($supacc, $wh['stkacc'], date("d-m-Y"), $refnum, $csamt, "Non-Stock Purchase No. {$pur['purnum']} Returned.");
            /* End code insert */
            db_connect();
            if ($stkt['units'] != 0) {
                $sql = "\n\t\t\t\t\tUPDATE stock \n\t\t\t\t\tSET csamt = (csamt - '{$csamt}'), csprice = (csamt/units) \n\t\t\t\t\tWHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            } else {
                $sql = "UPDATE stock SET csamt = (csamt - '{$csamt}') WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            $sdate = $pur['pdate'];
            stockrec($stkt['stkid'], $stkt['stkcod'], $stkt['stkdes'], 'ct', $sdate, 0, $csamt, "Cost decreased with Non Stock Purchase No. {$pur['purnum']}, returned");
            # Just wanted to fix the xxx.xxxxxxe-x value
            # get selected stock
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            # $csprice = round(($stk['csamt']/$stk['units']), 2);
            if ($stkt['units'] > 0) {
                $csprice = round($stkt['csamt'] / $stkt['units'], 2);
            } else {
                $csprice = round($stkt['csprice'], 2);
            }
            # update stock(csprice = (csamt/units))
            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        }
    }
    /* --- Start Some calculations --- */
    # Subtotal
    //$SUBTOT = sprint($subtot);
    //	$VAT = sprint($vat);
    //$TOTAL = sprint($total);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    // print $inv['ctyp']; exit;
    //$real_noteid = divlastid('note', USER_DIV);
    db_conn('cubit');
    # bank  % cust
    if ($inv['ctyp'] == 's') {
        $sql = "SELECT * FROM suppliers WHERE supid = '{$inv['supid']}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cus = pg_fetch_array($custRslt);
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql) or errDie("Unable to get details.");
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<li class=err>Department not Found.";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $tpp = 0;
        # record transaction  from data
        //foreach($totstkamt as $stkacc => $wamt){
        //}
        //$tot_dif=sprint($tot_post-$TOTAL);
    } elseif ($inv['ctyp'] == 'b') {
        $dept['debtacc'] = getbankaccid($inv['accid']);
        $amounts = "";
        $accids = "";
        $vats = "";
        $chrgvats = "";
        $gamt = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            # Cook vars
            $amounts .= "|{$wamt}";
            $accids .= "|{$stkacc}";
            $vats .= "|0";
            $chrgvats .= "|no";
            # Debit Customer and Credit stock
            //$tot_post+=$wamt;
            //writetrans($stkacc, $dept['debtacc'], date("d-m-Y"), $refnum, $wamt, "Non-Stock purchase No. $inv[invnum] Credit note No.$real_noteid.");
        }
        # Debit bank and credit the account involved
    } else {
        //$cusacc = $inv['accid'];
        $sdate = date("Y-m-d");
        # record transaction  from data
        //foreach($totstkamt as $stkacc => $wamt){
        # Debit Customer and Credit stock
        //			$tot_post+=$wamt;
        //writetrans($stkacc, $cusacc,  date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. $inv[invnum] Credit note No.$real_noteid.");
        //pettyrec($cusacc, $sdate, "dt", "Non-Stock Purchase No. $inv[invnum] Credit note No.$real_noteid.", $wamt, "Account Sale Credit note");
        //}
        # Debit bank and credit the account involved
        //$tot_post+=$VAT;
        //writetrans($vatacc, $cusacc, date("d-m-Y"), $refnum, $VAT, "Non-Stock Purchase No. $inv[invnum] Credit note No.$real_noteid VAT.");
        //pettyrec($cusacc, $sdate, "dt", "Non-Stock Purchase No. $inv[invnum] Credit note No.$real_noteid VAT.", $VAT, "Account Sale Credit note VAT");
    }
    if ($VAT != 0) {
        $tot_post += $VAT;
        writetrans($dept['credacc'], $vatacc, $td, $refnum, $VAT, "Non-Stock purchase No. {$inv['purnum']} Returned. Supplier {$inv['supplier']}.");
    }
    $sdate = date("Y-m-d");
    if ($inv['spurprd'] > 0) {
        $stkacc = $wh['stkacc'];
        $diff = sprint($TOTAL - $tot_post);
        if ($diff > 0) {
            writetrans($dept['credacc'], $cvacc, $td, $refnum, $diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']} Returned");
        } elseif ($diff < 0) {
            writetrans($cvacc, $dept['credacc'], $td, $refnum, -$diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']} Returned");
        }
    }
    /*
    	if($tot_dif>0) {
    		writetrans($stkacc, $varacc, date("d-m-Y"), $refnum, $tot_dif, "Purchase Variance on invoice $real_invid");
    	} elseif($tot_post<0) {
    		writetrans($varacc, $stkacc, date("d-m-Y"), $refnum, $tot_dif, "Purchase Variance on invoice $real_invid");
    	}*/
    $reff = $refnum;
    db_connect();
    if ($inv['ctyp'] == 's') {
        # Record the payment on the statement
        $sql = "\n\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\tsupid, ref, amount, edate, descript, div, cacc\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['supid']}', '{$reff}', '-{$TOTAL}', '{$td}', 'Non Stock purchase {$inv['purnum']} returned', '" . USER_DIV . "', '{$stkacc}'\n\t\t\t)";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance less)
        $sql = "UPDATE suppliers SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE supid = '{$inv['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Make ledge record
        suppledger($inv['supid'], $stkacc, $td, $reff, "Non Stock purchase {$inv['purnum']} returned", $TOTAL, "d");
        $mt = $TOTAL * -1;
        db_connect();
        $sql = "INSERT INTO suppurch (supid, purid, pdate, balance, div) VALUES ('{$inv['supid']}', '{$inv['purnum']}', '{$td}', '{$mt}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.{$sql}", SELF);
        //custfCT($TOTAL, $inv['cusid'], $sndate);
    } elseif ($inv['ctyp'] == 'cb') {
        $date = date("Y-m-d");
        # Record the Receipt record
        db_connect();
        $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, name, descript, cheqnum, amount, \n\t\t\t\tbanked, accids, amounts,  chrgvats, vats, div, accinv\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['supid']}', 'deposit', '{$td}', '{$inv['supplier']}', 'Nons Stock purchase {$inv['purnum']} returned', '0', '{$TOTAL}', \n\t\t\t\t'no', '', '{$TOTAL}', '{$inv['vatinc']}', '{$VAT}', '" . USER_DIV . "','{$stkacc}'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank Receipt to database.", SELF);
    }
    db_connect();
    $sql = "UPDATE \"{$prd}\".nons_purchases SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE purid = '{$inv['purid']}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
    $sql = "UPDATE cubit.suppurch SET balance=(balance - '{$TOTAL}'::numeric(13,2)) WHERE purid='{$inv['purid']}'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice balance.");
    # write note
    $sql = "\n\t\tINSERT INTO cubit.nons_purchasesn (\n\t\t\tpurid, purnum, supplier, supaddr, vatinc, pdate, subtot, vat, total, \n\t\t\tprd, notenum, ctyp, remarks, div\n\t\t) VALUES (\n\t\t\t'{$inv['purid']}', '{$inv['purnum']}', '{$inv['supplier']}', '{$inv['supaddr']}', '{$inv['vatinc']}', '{$td}', '{$SUBTOTAL}', '{$VAT}', '{$TOTAL}', \n\t\t\t'" . PRD_DB . "', '{$noteid}', '{$inv['ctyp']}', '{$remarks}', '" . USER_DIV . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to create template Non-Stock Invoice.{$sql}", SELF);
    $nid = pglib_lastid("nons_purchasesn", "id");
    $nid++;
    # write note items
    foreach ($ids as $key => $id) {
        db_conn($prd);
        $sql = "SELECT * FROM nons_pur_items  WHERE purid = '{$purid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql) or errDie("Unable to get data.{$sql}");
        $stktc = pg_fetch_array($stkdRslt);
        db_conn("cubit");
        $sql = "\n\t\t\tINSERT INTO nons_pur_itemsn (\n\t\t\t\tnoteid, cod, des, qty, unitcost, amt, svat, \n\t\t\t\tddate, accid, div\n\t\t\t) VALUES (\n\t\t\t\t'{$nid}', '{$stktc['cod']}', '{$stktc['des']}', '{$qtys[$key]}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['svat']}', \n\t\t\t\t'{$stktc['ddate']}', '{$stktc['accid']}', '" . USER_DIV . "'\n\t\t\t)";
        //$rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.",SELF);
    }
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* -- Format the remarks boxlet -- */
    $inv["remarks"] = "<table border=1><tr><td>Remarks:<br>{$inv['remarks']}</td><ble>";
    $cc = "<script> CostCenter('dt', 'Credit Note', '{$inv['pdate']}', 'Non Stock Credit Note No.{$noteid}', '" . ($TOTAL - $VAT) . "', ''); </script>";
    /* -- Final Layout -- */
    $details = "\n\t\t{$cc}\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Purchase Return</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Purchase return has been recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='purchase-view.php'>View purchases</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $details;
}
function write_data($_POST)
{
    $date = date("Y-m-d");
    # get vars
    extract($_POST);
    if (isset($back)) {
        return get_data("");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($surname, "string", 1, 100, "Last name");
    $v->isOk($name, "string", 0, 100, "First name");
    $v->isOk($account_id, "num", 0, 9, "Account ID (hidden)");
    $v->isOk($account_type, "string", 0, 100, "Account type (hidden)");
    $v->isOk($reports_to, "string", 0, 100, "Reports to");
    $v->isOk($reports_to_id, "num", 0, 9, "Reports to ID (hidden)");
    $v->isOk($lead_source, "string", 0, 100, "Lead Source");
    $v->isOk($title, "string", 0, 100, "Title");
    $v->isOk($department, "string", 0, 100, "Department");
    $v->isOk($tell, "string", 0, 100, "Home Phone");
    $v->isOk($cell, "string", 0, 100, "Mobile Phone");
    $v->isOk($fax, "string", 0, 100, "Fax");
    $v->isOk($tell_office, "string", 0, 100, "Office Phone");
    $v->isOk($tell_other, "string", 0, 100, "Other Phone");
    $v->isOk($email, "string", 0, 100, "Email");
    $v->isOk($email_other, "string", 0, 100, "Other Email");
    $v->isOk($assistant, "string", 0, 100, "Assistant");
    $v->isOk($assistant_phone, "string", 0, 100, "Assistant Phone");
    $v->isOk($padd, "string", 0, 100, "Physical Address");
    $v->isOk($padd_city, "string", 0, 100, "Physical Address: City");
    $v->isOk($padd_state, "string", 0, 100, "Physical Address: State/Province");
    $v->isOk($padd_code, "string", 0, 100, "Physical Address: Postal Code");
    $v->isOk($padd_country, "string", 0, 100, "Physical Address: Country");
    $v->isOk($hadd, "string", 0, 100, "Postal Address");
    $v->isOk($hadd_city, "string", 0, 100, "Postal Address: City");
    $v->isOk($hadd_state, "string", 0, 100, "Postal Address: State/Province");
    $v->isOk($hadd_code, "string", 0, 100, "Postal Address: Postal Code");
    $v->isOk($hadd_country, "string", 0, 100, "Postal Address: Country");
    $v->isOk($description, "string", 0, 100, "Description");
    $v->isOk($upload_img, "string", 0, 3, "Upload Image");
    $v->isOk($team_id, "num", 1, 9, "Team");
    $birthdate = "{$bf_year}-{$bf_month}-{$bf_day}";
    if ($v->isOk($birthdate, "string", 1, 100, "Birthdate")) {
        if (!checkdate($bf_month, $bf_day, $bf_year)) {
            $v->addError("_OTHER", "Invalid birthdate. No such date exists.");
        }
    }
    $birthdate_description = date("d F Y", mktime(0, 0, 0, $bf_day, $bf_month, $bf_year));
    $assigned_to = USER_NAME;
    $assigned_to_id = USER_ID;
    // read the reports to name
    $reports_to = "";
    if (!empty($reports_to_id)) {
        $reports_to_id += 0;
        db_conn("cubit");
        $sql = "SELECT * FROM cons WHERE id='{$reports_to_id}' LIMIT 1";
        $rslt = db_exec($sql) or errDie("Error retrieving 'Reports to' value.");
        $dat = pg_fetch_array($rslt);
        if (!empty($dat["name"])) {
            $reports_to .= "{$dat['name']} ";
        }
        $reports_to .= "{$dat['surname']}";
    }
    # display errors, if any
    if ($v->isError()) {
        $err = "The following field value errors occured:<br>";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            if ($e["value"] == "_OTHER") {
                $err .= "<li class='err'>{$e['msg']}</li>";
            } else {
                $err .= "<li class='err'>Invalid characters: {$e['msg']}</li>";
            }
        }
        return get_data($err);
    }
    db_conn('cubit');
    if (!pglib_transaction("BEGIN")) {
        return "<li class='err'>Unable to add contact to database. (TB)</li>";
    }
    if (isset($supid) and strlen($supid) > 0) {
        // supplier ...
        $get_sup = "SELECT supname FROM suppliers WHERE supid = '{$supid}' LIMIT 1";
        $run_sup = db_exec($get_sup) or errDie("Unable to get supplier information.");
        if (pg_numrows($run_sup) > 0) {
            $accountname = pg_fetch_result($run_sup, 0, 0);
        }
    }
    if (isset($cusnum) and strlen($cusnum) > 0) {
        // customer
        $get_cust = "SELECT surname FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
        $run_cust = db_exec($get_cust) or errDie("Unable to get customer information.");
        if (pg_numrows($run_cust) > 0) {
            $accountname = pg_fetch_result($run_cust, 0, 0);
        }
    }
    # write to db
    db_conn("cubit");
    $supid += 0;
    $cusnum += 0;
    $account_id += 0;
    $sql = "\n\t\tINSERT INTO cons (\n\t\t\tsurname, name, accountname, account_id, account_type,\n\t\t\tlead_source, title, department, birthdate, reports_to, reports_to_id,\n\t\t\ttell, cell, fax, tell_office, tell_other, email, email_other, assistant,\n\t\t\tassistant_phone, padd, padd_city, padd_state, padd_code,\n\t\t\tpadd_country, hadd, hadd_city, hadd_state, hadd_code,\n\t\t\thadd_country, description, ref, date, con, by, div, supp_id,\n\t\t\tcust_id, assigned_to, assigned_to_id, team_id\n\t\t) VALUES (\n\t\t\t'{$surname}', '{$name}', '{$accountname}', '{$account_id}', '{$account_type}', \n\t\t\t'{$lead_source}', '{$title}', '{$department}', '{$birthdate}', '{$reports_to}', \n\t\t\t'{$reports_to_id}', '{$tell}', '{$cell}', '{$fax}', '{$tell_office}', \n\t\t\t'{$tell_other}', '{$email}', '{$email_other}', '{$assistant}', \n\t\t\t'{$assistant_phone}', '{$padd}', '{$padd_city}', '{$padd_state}', \n\t\t\t'{$padd_code}', '{$padd_country}', '{$hadd}', '{$hadd_city}', '{$hadd_state}', \n\t\t\t'{$hadd_code}', '{$hadd_country}', '{$description}', '{$account_type}', CURRENT_DATE, \n\t\t\t'{$Con}', '" . USER_NAME . "', '" . USER_DIV . "', '{$supid}', \n\t\t\t'{$cusnum}', '{$assigned_to}', '{$assigned_to_id}', '{$team_id}'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to add contact to database.");
    $con_id = pglib_lastid("cons", "id");
    // Write the image (if any)
    if ($upload_img == "yes") {
        if (preg_match("/(image\\/jpeg|image\\/png|image\\/gif)/", $_FILES["img_file"]["type"], $extension)) {
            $img = "";
            $fp = fopen($_FILES["img_file"]["tmp_name"], "rb");
            while (!feof($fp)) {
                $img .= fread($fp, 1024);
            }
            fclose($fp);
            $img = base64_encode($img);
            $sql = "\n\t\t\t\tINSERT INTO cubit.cons_img (\n\t\t\t\t\tcon_id, type, file, size\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$con_id}', '" . $_FILES["img_file"]["type"] . "', '{$img}', '" . $_FILES["img_file"]["size"] . "'\n\t\t\t\t)";
            $ci_rslt = db_exec($sql) or errDie("Unable to add contact image.");
        } else {
            return "<li class='err'>Please note we only accept PNG, GIF and JPEG images.</li>";
        }
    }
    if (!pglib_transaction("COMMIT")) {
        return "<li class='err'>Unable to add contact to database. (TC)</li>";
    }
    if (isset($crm)) {
        header("Location: crm/tokens-new.php?value={$surname}");
        exit;
    }
    $write_data = "\n\t\t<table cellpadding='2' cellspacing='0' class='shtable'>\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Contact added</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$surname} has been added to Cubit.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table cellpadding='2' cellspacing='0' class='shtable'>\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='" . SELF . "'>Add another contact</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='list_cons.php'>List Contacts</a></td>\n\t\t\t</tr>\n\t\t</table>";
    return $write_data;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    #only process details if we are not changing the customer
    if (isset($customer_select) and isset($old_customer_select) and $customer_select != $old_customer_select) {
        return details($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $sdate = mkdate($nquo_year, $nquo_month, $nquo_day);
    $v->isOk($sdate, "date", 1, 1, "Invalid Date.");
    # used to generate errors
    $error = "asa@";
    // check the quote details
    $v->isOK($cusname, "string", 1, 100, "Invalid customer name");
    $v->isOK($cusaddr, "string", 0, 100, "Invalid customer address");
    $v->isOK($cusvatno, "string", 0, 50, "Invalid customer vat number");
    if ($chrgvat != "yes" && $chrgvat != "no" && $chrgvat != "none") {
        $v->addError($chrgvat, "Invalid vat option");
    }
    if (!isset($bodydata)) {
        $bodydata = "";
    }
    $bodydata = str_replace("'", "", $bodydata);
    //$bodydata = str_replace("<br>","",$bodydata);
    $bodydata = str_replace("  ", " ", $bodydata);
    $bodydata = str_replace("&nbsp;&nbsp;", " ", $bodydata);
    $bodydata = str_replace(" &nbsp;", " ", $bodydata);
    $bodydata = str_replace("&nbsp; ", " ", $bodydata);
    //[key] was $counter ... but it wasnt set ??
    $des[] = $bodydata;
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            //			$v->isOk ($des[$keys], "url", 1, 255, "Invalid Description.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- invoices Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['chrgvat'] = $chrgvat;
    # check if purchase has been printed
    if ($inv['done'] == "y") {
        $error = "<li class='err'> Error : quote number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $vatamount = 0;
    $showvat = TRUE;
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_connect();
    /* -- Start remove old items -- */
    # remove old items
    $sql = "DELETE FROM nons_inv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update quote items in Cubit.", SELF);
    $taxex = 0;
    /* -- End remove old items -- */
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod) && in_array($keys, $remprod)) {
            } else {
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                if (!isset($vatcodes[$keys])) {
                    $vatcodes[$keys] = 0;
                }
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                // 				if(pg_num_rows($Ri)<1) {
                // 					return "Please select the vatcode for all your stock.";
                // 				}
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, 0, $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                $vate = 'n';
                if (isset($vatex) && in_array($keys, $vatex) || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $vate = 'y';
                }
                $vate = $vatcodes[$keys];
                # insert purchase items
                $sql = "\n\t\t\t\t\tINSERT INTO nons_inv_items (\n\t\t\t\t\t\tinvid, qty, amt, unitcost, description, vatex, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}','{$vate}',  '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert quote items to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Done'>";
        }
    } else {
        $_POST["done"] = "";
    }
    $_POST['showvat'] = $showvat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "no") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        //		$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
    } elseif ($chrgvat == "yes") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        //	$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = $vatamount;
        $SUBTOT = sprint($sub - $vatamount);
        $TOTAL = sprint($subtotal);
    } else {
        $subtotal = sprint($sub);
        $traddiscmt = sprint($subtotal);
        $subtotal = sprint($subtotal);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- Clac ---
    	# calculate subtot
    	if( isset($amt) ){
    		$SUBTOT = array_sum($amt);
    	}else{
    		$SUBTOT = 0.00;
    	}
    
    	$VATP = TAX_VAT;
    	if($chrgvat == "no"){
    		$SUBTOT = $SUBTOT;
    	}elseif($chrgvat == "yes"){
    		$SUBTOT = sprint(($SUBTOT * 100)/(100 + $VATP));
    	}else{
    		$SUBTOT = ($SUBTOT);
    	}
    
    	if($chrgvat != "none"){
    		$VAT = sprint($SUBTOT * ($VATP/100));
    	}else{
    		$VAT = 0;
    	}
    
    	$TOTAL = sprint($SUBTOT + $VAT);
    
    	/*# if vat is not included
    	$VATP = TAX_VAT;
    	if($chrgvat == "yes"){
    		$SUBTOT = sprintf("%0.2f", $TOTAL * 100 / (100 + $VATP) );
    	} elseif($chrgvat == "no") {
    		$SUBTOT = $TOTAL;
    		$TOTAL = sprintf("%0.2f", $TOTAL * (100 + $VATP) /100 );
    	}else{
    		$SUBTOT = $TOTAL;
    	}
    
    	// compute the sub total (total - vat), done this way because the specified price already includes vat
    	$VAT = $TOTAL - $SUBTOT;
    
    	/* --- End Clac --- */
    $ncdate = "{$ncdate_year}-{$ncdate_month}-{$ncdate_day}";
    if (!isset($lead)) {
        $lead = "";
    }
    # insert purchase to DB
    $sql = "\n\t\t\tUPDATE nons_invoices \n\t\t\tSET cusname = '{$cusname}', cusaddr = '{$cusaddr}', cusvatno = '{$cusvatno}', chrgvat = '{$chrgvat}', odate = '{$sdate}', \n\t\t\t\tsubtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', remarks = '{$remarks}', lead = '{$lead}', ncdate = '{$ncdate}' \n\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update quote in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (!isset($doneBtn)) {
        return details($_POST);
    } else {
        $rslt = db_exec($sql) or errDie("Unable to update invoices status in Cubit.", SELF);
        #add lead
        if (isset($lead) and $lead == "yes") {
            db_conn("crm");
            $sql = "\n\t\t\t\tINSERT INTO leads (\n\t\t\t\t\tsurname, date, by, con, div, supp_id, cust_id, lead_source, birthdate, reports_to_id, assigned_to, \n\t\t\t\t\tassigned_to_id, account_id, gender, website, salespid, ncdate, team_id, dept_id, tell, hadd, ref\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cusname}', 'now', '" . USER_NAME . "', 'No', '" . USER_DIV . "', '0', '0', '0', 'now', '0', '" . USER_NAME . "', \n\t\t\t\t\t'0', '0', 'Male', 'http://', '0', '{$ncdate}', '0', '0', '', '{$cusaddr}', ''\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to add lead to database.");
            $lead_id = pglib_lastid("leads", "id");
        }
        // Final Laytout
        $write = "\n\t\t\t<script>\n\t\t\t\tprinter('nons-quote-print.php?invid={$invid}');\n\t\t\t</script>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>New Non-Stock Quotes</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Non-Stock Quotes for Customer <b>{$cusname}</b> has been recorded.</td>\n\t\t\t\t\t<td><input type='button' onClick=\"printer('nons-quote-print.php?invid={$invid}');\" value='Print Quote'></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\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='nons-quote-view.php'>View Non-Stock Quotes</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</table>";
        return $write;
        // 		return "
        // 			<script>
        // 				printer('nons-quote-print.php?invid=$invid');
        // 				document.location='nons-multiline-quote-new.php';
        // 			</script>";
    }
}
function write($_POST)
{
    # get vars
    extract($_POST);
    // prevent from updating
    if (isset($cusnum) && customer_overdue($cusnum)) {
        return details($_POST);
    }
    db_conn('cubit');
    if (isset($printsales)) {
        $Sl = "SELECT * FROM settings WHERE constant='SALES'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('SALES','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='SALES' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='SALES' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    if (!isset($bodydata)) {
        $bodydata = "";
    }
    if (!isset($counter)) {
        $counter = "";
    }
    $bodydata = str_replace("'", "", $bodydata);
    $bodydata = str_replace("  ", " ", $bodydata);
    $bodydata = str_replace("&nbsp;&nbsp;", " ", $bodydata);
    $bodydata = str_replace(" &nbsp;", " ", $bodydata);
    $bodydata = str_replace("&nbsp; ", " ", $bodydata);
    $des[$counter] = $bodydata;
    # validate input
    require_lib("validate");
    $v = new validate();
    if (empty($ninv_year)) {
        list($ninv_year, $ninv_month, $ninv_day) = date("Y-m-d");
    }
    $odate = mkdate($ninv_year, $ninv_month, $ninv_day);
    $v->isOk($odate, "date", 1, 1, "Invalid Date.");
    # used to generate errors
    $error = "asa@";
    // check the invoice details
    $v->isOK($cusname, "string", 1, 100, "Invalid customer name");
    $v->isOK($cusaddr, "string", 0, 400, "Invalid customer address");
    $v->isOK($cusvatno, "string", 0, 50, "Invalid customer vat number");
    $v->isOK($docref, "string", 0, 20, "Invalid Document Reference No.");
    $v->isOK($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    if ($chrgvat != "yes" && $chrgvat != "no" && $chrgvat != "none") {
        $v->addError($chrgvat, "Invalid vat option");
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "float", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            //		$v->isOk ($des[$keys], "url", 1, 255, "Invalid Description.");
            if ($qty <= 0) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity can't be zero or less. Product number: <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 16, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['chrgvat'] = $chrgvat;
    # check if purchase has been printed
    if ($inv['done'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $vatamount = 0;
    $showvat = TRUE;
    # insert purchase to DB
    db_conn("cubit");
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # remove old items
    $sql = "DELETE FROM nons_inv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod)) {
                if (in_array($keys, $remprod)) {
                    # skip product (wonder if $keys still align)
                    $amt[$keys] = 0;
                    continue;
                } else {
                    # Calculate amount
                    $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                    if (!isset($vatcodes[$keys])) {
                        $vatcodes[$keys] = 0;
                    }
                    db_connect();
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                    $Ri = db_exec($Sl);
                    // 					if(pg_num_rows($Ri)<1) {
                    // 						return "Please select the vatcode for all your stock.";
                    // 					}
                    $vd = pg_fetch_array($Ri);
                    if ($vd['zero'] == "Yes") {
                        $excluding = "y";
                    } else {
                        $excluding = "";
                    }
                    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                        $showvat = FALSE;
                    }
                    $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, 0, $vd['vat_amount']);
                    $vrs = explode("|", $vr);
                    $ivat = $vrs[0];
                    $iamount = $vrs[1];
                    $vatamount += $ivat;
                    $vate = 'n';
                    if (isset($vatex) && in_array($keys, $vatex) || $vd['zero'] == "Yes") {
                        $taxex += $amt[$keys];
                        $vate = 'y';
                    }
                    $vate = $vatcodes[$keys];
                    # insert purchase items
                    $sql = "\n\t\t\t\t\t\tINSERT INTO nons_inv_items (\n\t\t\t\t\t\t\tinvid, qty, amt, unitcost, description, vatex, div\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}', '{$vate}', '" . USER_DIV . "'\n\t\t\t\t\t\t)";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                }
            } else {
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                if (!isset($vatcodes[$keys])) {
                    $vatcodes[$keys] = 0;
                }
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                // 				if(pg_num_rows($Ri) < 1) {
                // 					return "Please select the vatcode for all your stock.";
                // 				}
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, 0, $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                $vate = 'n';
                if (isset($vatex) && in_array($keys, $vatex) || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $vate = 'y';
                }
                $vate = $vatcodes[$keys];
                db_connect();
                # insert purchase items
                $sql = "\n\t\t\t\t\tINSERT INTO nons_inv_items (\n\t\t\t\t\t\tinvid, qty, amt, unitcost, description, vatex, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}', '{$vate}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Done'>| <input name='print' type='submit' value='Process'>";
        }
    } else {
        $_POST["done"] = "";
    }
    $_POST['showvat'] = $showvat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "no") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        // 		$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
    } elseif ($chrgvat == "yes") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        // 		$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
    } else {
        $subtotal = sprint($sub);
        $traddiscmt = sprint($subtotal);
        $subtotal = sprint($subtotal);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- Clac ---
    	# calculate subtot
    	if( isset($amt) ){
    		$SUBTOT = array_sum($amt);
    	}else{
    		$SUBTOT = 0.00;
    	}
    
    	$SUBTOT -= $taxex;
    
    	$VATP = TAX_VAT;
    	if($chrgvat == "no"){
    		$SUBTOT = $SUBTOT;
    	}elseif($chrgvat == "yes"){
    		$SUBTOT = sprint(($SUBTOT * 100)/(100 + $VATP));
    	}else{
    		$SUBTOT = ($SUBTOT);
    	}
    
    	if($chrgvat != "none"){
    		$VAT = sprint($SUBTOT * ($VATP/100));
    	}else{
    		$VAT = 0;
    	}
    
    	$TOTAL = sprint($SUBTOT + $VAT + $taxex);
    	$SUBTOT += $taxex;
    
    	/* --- End Clac --- */
    $salespn = remval($salespn);
    if (!isset($bankid)) {
        if (isset($cusnum) and strlen($cusnum) > 0) {
            #get bankid from customer info
            $get_cbank = "SELECT bankid FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
            $run_cbank = db_exec($get_cbank) or errDie("Unable to get bank information for customer.");
            if (pg_numrows($run_cbank) > 0) {
                $bankid = pg_fetch_result($run_cbank, 0, 0);
            } else {
                $bankid = "2";
            }
        } else {
            $bankid = "2";
        }
    }
    # insert purchase to DB
    $sql = "\n\t\tUPDATE nons_invoices \n\t\tSET salespn='{$salespn}', cusname = '{$cusname}', cusaddr = '{$cusaddr}', \n\t\t\tcusvatno = '{$cusvatno}', cordno = '{$cordno}', docref = '{$docref}', \n\t\t\tchrgvat = '{$chrgvat}', odate = '{$odate}', terms = '{$terms}', \n\t\t\tsubtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', \n\t\t\tremarks = '{$remarks}', bankid = '{$bankid}' \n\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (isset($print)) {
        $OUTPUT = "<script>printer('nons-invoice-print.php?invid={$invid}');move('nons-invoice-new.php');</script>";
        require "template.php";
    }
    if (!isset($doneBtn)) {
        return details($_POST);
    } else {
        //$rslt = db_exec($sql) or errDie("Unable to update invoices status in Cubit.$sql",SELF);
        # Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New Non-Stock Invoices</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Non-Stock Invoices for Customer <b>{$cusname}</b> has been recorded.</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\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='nons-invoice-view.php'>View Non-Stock Invoices</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    }
}
function write()
{
    extract($_REQUEST);
    require_lib("validate");
    $v = new validate();
    // Validate Categories
    if (isset($cat_start_id) && is_numeric($cat_start_id)) {
        $sql = "SELECT catid FROM cubit.stockcat WHERE catid='{$cat_start_id}'";
        $cat_rslt = db_exec($sql) or errDie("Unable to retrieve categories.");
        if (!pg_num_rows($cat_rslt)) {
            $v->addError(0, "Invalid starting category");
        }
    }
    if (isset($cat_end_id) && is_numeric($cat_end_id) && $cat_end_id > 0) {
        $sql = "SELECT catid FROM cubit.stockcat WHERE catid='{$cat_end_id}'";
        $cat_rslt = db_exec($sql) or errDie("Unable to retrieve categories.");
        if (!pg_num_rows($cat_rslt)) {
            $v->addError(0, "Invalid ending category");
        }
    }
    // Validate price options
    $price_options = array("price_all", "price_recent", "price_multi");
    if (!isset($price_rad)) {
        $v->addError(0, "Please select a price option.");
    } elseif (!in_array($price_rad, $price_options)) {
        $v->addError(0, "Invalid price option selected.");
    } else {
        switch ($price_rad) {
            case "price_all":
                $v->isOk($price_one, "float", 1, 20, "Invalid price factor for existing selling prices.");
                break;
            case "price_recent":
                $v->isOk($price_two, "float", 1, 20, "Invalid price factor for most recent prices.");
                break;
            case "price_multi":
                // A
                if (!isset($price_a) || !isset($factor_a)) {
                    $v->addError(0, "No cost or factor specified for price A");
                } else {
                    $v->isOk($price_a, "float", 1, 20, "Invalid cost (A)");
                    $v->isOk($factor_a, "float", 1, 20, "Invalid factor (A)");
                }
                // B
                if (!isset($price_b) || empty($price_b)) {
                    break;
                } else {
                    $v->isOk($price_b, "float", 1, 20, "Invalid cost (B)");
                    $v->isOk($factor_b, "float", 1, 20, "Invalid factor (B)");
                }
                // C
                if (!isset($price_c) || empty($price_c)) {
                    break;
                } else {
                    $v->isOk($price_c, "float", 1, 20, "Invalid cost (C)");
                    $v->isOk($factor_c, "float", 1, 20, "Invalid factor (C)");
                }
                // D
                if (!isset($price_d) || empty($price_d)) {
                    break;
                } else {
                    $v->isOk($price_d, "float", 1, 20, "Invalid cost (D)");
                    $v->isOk($factor_d, "float", 1, 20, "Invalid factor (D)");
                }
                // E
                if (!isset($price_e) || empty($price_e)) {
                    break;
                } else {
                    $v->isOk($price_e, "float", 1, 20, "Invalid cost (E)");
                    $v->isOk($factor_e, "float", 1, 20, "Invalid factor (E)");
                }
                break;
        }
    }
    if ($v->isError()) {
        return enter($v->genErrors());
    }
    $affected_rows = 0;
    if (isset($new_price)) {
        foreach ($new_price as $stkid => $value) {
            $sql = "\n\t\t\tUPDATE exten.plist_prices SET price='{$value}'\n\t\t\tWHERE stkid='{$stkid}'";
            db_exec($sql);
            $affected_rows++;
        }
    }
    /*
    	// Retrieve starting category name
    	$sql = "SELECT cat FROM cubit.stockcat WHERE catid='$cat_start_id'";
    	$cat_rslt = db_exec($sql) or errDie("Unable to retrieve start category.");
    	$cat_start = pg_fetch_result($cat_rslt, 0);
    
    	// Retrieve ending category name
    	if ($cat_end_id) {
    		$sql = "SELECT cat FROM cubit.stockcat WHERE catid='$cat_end_id'";
    	} else {
    		$sql = "SELECT max(cat) FROM cubit.stockcat";
    	}
    	$cat_rslt = db_exec($sql) or errDie("Unable to retrieve end category.");
    	$cat_end = pg_fetch_result($cat_rslt, 0);
    
    	// Keep track of the amount of pricelist items updated
    	$affected_rows = 0;
    
    	pglib_transaction("BEGIN");
    	switch ($price_rad) {
    	case "price_all":
    		// Retrieve items to update
    		$sql = "
    		SELECT id
    		FROM exten.plist_prices
    			LEFT JOIN cubit.stockcat ON plist_prices.catid=stockcat.catid
    		WHERE cat BETWEEN '$cat_start' AND '$cat_end'";
    		$items_rslt = db_exec($sql)
    			or errDie("Unable to retrieve items to update.");
    		
    		while (list($id) = pg_fetch_array($items_rslt)) {
    			$sql = "
    			UPDATE exten.plist_prices SET price=(price * '$price_one')
    			WHERE id='$id'";
    			$rslt = db_exec($sql) or errDie("Unable to update pricelist.");
    
    			$affected_rows += pg_affected_rows($rslt);
    		}
    		break;
    	case "price_recent":
    		// Retrieve items to update
    		$sql = "
    		SELECT id, lcsprice
    		FROM exten.plist_prices 
    			LEFT JOIN cubit.stockcat ON plist_prices.catid=stockcat.catid
    			LEFT JOIN cubit.stock ON plist_prices.stkid=stock.stkid
    		WHERE cat BETWEEN '$cat_start' AND '$cat_end'";
    		$items_rslt = db_exec($sql)
    			or errDie("Unable to retrieve items to update.");
    
    		while (list($id, $lcsprice) = pg_fetch_array($items_rslt)) {
    			$sql = "
    			UPDATE exten.plist_prices SET price=('$lcsprice' * '$price_two')
    			WHERE id='$id'";
    			$rslt = db_exec($sql) or errDie("Unable to update pricelist.");
    
    			$affected_rows += $pg_affected_rows($rslt);
    		}
    		break;
    	case "price_multi":
    		// Query A -----------------------------------------------------------
    		$sql = "
    		SELECT id FROM exten.plist_prices 
    			LEFT JOIN cubit.stockcat ON plist_prices.catid=stockcat.catid
    			LEFT JOIN cubit.stock ON plist_prices.stkid=stock.stkid
    
    		WHERE cat BETWEEN '$cat_start' AND '$cat_end' AND
    			price BETWEEN 0 AND '$price_a'";
    		$items_rslt = db_exec($sql) or errDie("Unable to retrieve prices.");
    
    		while (list($id) = pg_fetch_array($items_rslt)) {
    			$sql = "
    			UPDATE exten.plist_prices SET price=(price * '$factor_a')
    			WHERE id='$id'";
    			$rslt = db_exec($sql) or errDie("Unable to update pricelist.");
    
    			$affected_rows += pg_affected_rows($rslt);
    		}
    
    		// Query B -----------------------------------------------------------
    		if (!isset($price_b) || empty($price_b)) break;
    
    		$sql = "
    		SELECT id FROM exten.plist_prices 
    			LEFT JOIN cubit.stockcat ON plist_prices.catid=stockcat.catid
    			LEFT JOIN cubit.stock ON plist_prices.stkid=stock.stkid
    
    		WHERE cat BETWEEN '$cat_start' AND '$cat_end' AND
    			price BETWEEN '$price_a' AND '$price_b'";
    		$items_rslt = db_exec($sql) or errDie("Unable to retrieve prices.");
    
    		while (list($id) = pg_fetch_array($items_rslt)) {
    			$sql = "
    			UPDATE exten.plist_prices SET price=(price * '$factor_b')
    			WHERE id='$id'";
    			$rslt = db_exec($sql) or errDie("Unable to update pricelist.");
    
    			$affected_rows += pg_affected_rows($rslt);
    		}
    		
    		// Query C -----------------------------------------------------------
    		if (!isset($price_c) || empty($price_c)) break;
    
    		$sql = "
    		SELECT id FROM exten.plist_prices 
    			LEFT JOIN cubit.stockcat ON plist_prices.catid=stockcat.catid
    			LEFT JOIN cubit.stock ON plist_prices.stkid=stock.stkid
    
    		WHERE cat BETWEEN '$cat_start' AND '$cat_end' AND
    			price BETWEEN '$price_b' AND '$price_c'";
    		$items_rslt = db_exec($sql) or errDie("Unable to retrieve prices.");
    
    		while (list($id) = pg_fetch_array($items_rslt)) {
    			$sql = "
    			UPDATE exten.plist_prices SET price=(price * '$factor_c')
    			WHERE id='$id'";
    			$rslt = db_exec($sql) or errDie("Unable to update pricelist.");
    
    			$affected_rows += pg_affected_rows($rslt);
    		}
    		
    		// Query D -----------------------------------------------------------
    		if (!isset($price_d) || empty($price_d)) break;
    
    		$sql = "
    		SELECT id FROM exten.plist_prices 
    			LEFT JOIN cubit.stockcat ON plist_prices.catid=stockcat.catid
    			LEFT JOIN cubit.stock ON plist_prices.stkid=stock.stkid
    
    		WHERE cat BETWEEN '$cat_start' AND '$cat_end' AND
    			price BETWEEN '$price_c' AND '$price_d'";
    		$items_rslt = db_exec($sql) or errDie("Unable to retrieve prices.");
    
    		while (list($id) = pg_fetch_array($items_rslt)) {
    			$sql = "
    			UPDATE exten.plist_prices SET price=(price * '$factor_d')
    			WHERE id='$id'";
    			$rslt = db_exec($sql) or errDie("Unable to update pricelist.");
    
    			$affected_rows += pg_affected_rows($rslt);
    		}
    
    		// Query E -----------------------------------------------------------
    		if (!isset($price_e) || empty($price_e)) break;
    
    		$sql = "
    		SELECT id FROM exten.plist_prices 
    			LEFT JOIN cubit.stockcat ON plist_prices.catid=stockcat.catid
    			LEFT JOIN cubit.stock ON plist_prices.stkid=stock.stkid
    
    		WHERE cat BETWEEN '$cat_start' AND '$cat_end' AND
    			price BETWEEN '$price_d' AND '$price_e'";
    		$items_rslt = db_exec($sql) or errDie("Unable to retrieve prices.");
    
    		while (list($id) = pg_fetch_array($items_rslt)) {
    			$sql = "
    			UPDATE exten.plist_prices SET price=(price * '$factor_e')
    			WHERE id='$id'";
    			$rslt = db_exec($sql) or errDie("Unable to update pricelist.");
    			
    			$affected_rows += pg_affected_rows($rslt);
    		}
    	}
    */
    pglib_transaction("COMMIT");
    $msg = "\n\t\t<li class='yay' style='font-size: 1.2em'>\n\t\t\t<strong>{$affected_rows}</strong> prices, updated successfully!\n\t\t\t<a href='pricelist-xls.php?listid=2'>Export</a>\n\t\t</li>";
    return enter($msg);
}
function write($_POST)
{
    extract($_POST);
    $deptid += 0;
    db_conn('cubit');
    if (isset($printsales)) {
        $Sl = "SELECT * FROM settings WHERE constant='PSALES'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('PSALES','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='PSALES' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='PSALES' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    //$it+=0;
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($client)) {
        $v->isOk($client, "string", 0, 20, "Invalid Customer.");
    } else {
        $client = "";
    }
    if (isset($vatnum)) {
        $v->isOk($vatnum, "string", 0, 30, "Invalid VAT Number.");
    } else {
        $vatnum = "";
    }
    if (isset($branch_addr)) {
        $v->isOk($branch_addr, "num", 1, 20, "Invalid site address.");
    } else {
        $branch_addr = 0;
    }
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($telno, "string", 0, 20, "Invalid Customer Telephone Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    //$v->isOk ($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($ordno, "string", 0, 20, "Invalid sales order number.");
    // 	$v->isOk ($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($salespid, "string", 1, 255, "Invalid sales person.");
    $v->isOk($pinv_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($pinv_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($pinv_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day;
    if (!checkdate($pinv_month, $pinv_day, $pinv_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($subtot, "float", 0, 20, "Invalid subtotal.");
    $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day;
    if (!checkdate($pinv_month, $pinv_day, $pinv_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    $v->isOk($collection, "string", 0, 40, "Invalid collection method.");
    # used to generate errors
    $error = "asa@";
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        if (!ext_isUnique(ext_remBlnk($sernos))) {
            $v->isOk($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # check is serial no was selected
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            # check if serial is selected
            if (ext_isSerial("stock", "stkid", $stkid) && !isset($sernos[$keys])) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number : <b>" . ($keys + 1) . "</b>");
            } elseif (ext_isSerial("stock", "stkid", $stkid) && !(strlen($sernos[$keys]) > 0)) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    $cusnum += 0;
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    if (isset($des)) {
        $des = remval($des);
    }
    if (isset($asset_id) && is_numeric($asset_id)) {
        foreach ($asset_id as $value) {
            $sql = "SELECT id, des FROM cubit.assets WHERE id='{$asset_id}'";
            $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
            $asset_data = pg_fetch_array($asset_rslt);
            if (isHired($asset_id)) {
                $v->addError(0, "Asset " . getSerial($asset_id) . " {$asset_data['des']} has already been hired out.");
            }
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>{$e['msg']}<li>";
        }
        return details($_POST, $err);
    }
    if (strlen($vatnum) < 1) {
        $vatnum = "";
    }
    $_POST['client'] = $client;
    $_POST['vatnum'] = $vatnum;
    $_POST['telno'] = $telno;
    $_POST['cordno'] = $cordno;
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    // 	if (pg_numrows ($invRslt) < 1) {
    // 		return "<li>- Invoice Not Found[1]</li>";
    // 	}
    $inv = pg_fetch_array($invRslt);
    $inv['traddisc'] = $traddisc;
    $inv['chrgvat'] = 0;
    # check if invoice has been printed
    // 	if($inv['printed'] == "y"){
    // 		$error = "<li class=err> Error : Invoice number <b>$invid</b> has already been printed.";
    // 		$error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
    // 		return $error;
    // 	}
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found[3]</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $traddisc += 0;
    $delchrg += 0;
    $vatamount = 0;
    $showvat = TRUE;
    # insert invoice to DB
    db_connect();
    if (isset($upBtn) || isset($hirenewBtn)) {
        $update_ret = update($_POST);
    } else {
        $update_ret = false;
    }
    # begin updating
    pglib_transaction("BEGIN");
    /* -- Start remove old items -- */
    # get selected stock in this invoice
    $sql = "SELECT * FROM hire.hire_invitems  WHERE invid = '{$invid}'";
    $stktRslt = db_exec($sql);
    $subtot = 0;
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(alloc + qty)
        //$sql = "UPDATE stock SET alloc = (alloc - '$stkt[qty]')  WHERE stkid = '$stkt[stkid]' AND div = '".USER_DIV."'";
        //$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
        //if(strlen($stkt['serno']) > 0)
        //ext_unresvSer($stkt['serno'], $stkt['stkid']);
        $subtot += $stkt["amt"];
    }
    # remove old items
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $VATP = TAX_VAT;
    $subtotal = sprint($subtot + $delchrg);
    $traddiscmt = sprint($subtotal * $traddisc / 100);
    $subtotal = sprint($subtotal - $traddiscmt);
    $VAT = $subtotal / 100 * 14;
    $SUBTOT = $subtotal;
    $TOTAL = $subtotal + $VAT;
    $delexvat = sprint($delchrg);
    $Sl = "SELECT * FROM posround";
    $Ri = db_exec($Sl);
    $data = pg_fetch_array($Ri);
    if ($data['setting'] == "5cent") {
        if (sprint(floor(sprint($TOTAL / 0.05))) != sprint($TOTAL / 0.05)) {
            $otot = $TOTAL;
            $nTOTAL = sprint(sprint(floor($TOTAL / 0.05)) * 0.05);
            $rounding = $otot - $nTOTAL;
        } else {
            $rounding = 0;
        }
    } else {
        $rounding = 0;
    }
    //print sprint(floor($TOTAL/0.05));
    #get accno if invoice is on credit
    if ($cusnum != "0") {
        $get_acc = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
        $run_acc = db_exec($get_acc) or errDie("Unable to get customer information");
        if (pg_numrows($run_acc) < 1) {
            $accno = "";
        } else {
            $arr = pg_fetch_array($run_acc);
            $cusacc = $arr['accno'];
            $cusname = "{$arr['cusname']} {$arr['surname']}";
        }
    } else {
        $cusacc = "";
        $cusname = "";
    }
    # insert invoice to DB
    $sql = "\r\n\t\t\tUPDATE hire.hire_invoices \r\n\t\t\tSET cusnum='{$cusnum}', cusname='{$cusname}', rounding='{$rounding}', deptid='{$deptid}', deptname='{$dept['deptname']}', \r\n\t\t\t\tcordno='{$cordno}', ordno='{$ordno}', salespn='{$salespid}', odate='{$odate}', traddisc='{$traddisc}', \r\n\t\t\t\tdelchrg='{$delchrg}', subtot='{$SUBTOT}', vat='{$VAT}',balance='{$TOTAL}', total='{$TOTAL}', discount='{$traddiscmt}', \r\n\t\t\t\tdelivery='{$delexvat}', vatnum='{$vatnum}', cusacc='{$cusacc}', telno='{$telno}', deposit_type='{$deposit_type}', \r\n\t\t\t\tdeposit_amt='{$deposit_amt}', collection='{$collection}', custom_txt='{$custom_txt}', branch_addr='{$branch_addr}' \r\n\t\t\tWHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM pinv_data WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF);
    # put in new data
    $sql = "INSERT INTO pinv_data(invid, dept, customer, div) VALUES('{$invid}', '{$dept['deptname']}', '{$client}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice data to Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    return details($_POST, $update_ret);
    if (strlen($bar) > 0) {
        $Sl = "SELECT * FROM possets WHERE div = '" . USER_DIV . "'";
        $Rs = db_exec($Sl) or errDie("Unable to add supplier to the system.", SELF);
        if (pg_numrows($Rs) < 1) {
            return details($_POST, "Please go set the point of sale settings under the stock settings");
        }
        $Dets = pg_fetch_array($Rs);
        if ($Dets['opt'] == "No") {
            switch (substr($bar, strlen($bar) - 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 details($_POST, "The code you selected is invalid");
            }
            db_conn('cubit');
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $stid = barext_dbget($tab, 'code', $bar, 'stock');
            if (!($stid > 0)) {
                return details($_POST, "<li class='err'><b>ERROR</b>: The bar code you selected is not in the system or is not available.</li>");
            }
            $Sl = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            $s = pg_fetch_array($Rs);
            # put scanned-in product into invoice db
            $sql = "\r\n\t\t\t\tINSERT INTO hire.hire_invitems (\r\n\t\t\t\t\tinvid, whid, stkid, qty, amt, disc, discp, ss, serno, \r\n\t\t\t\t\tdiv\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$s['whid']}', '{$stid}', '1', '{$s['selamt']}', '{$s['selamt']}', '0', '0', '{$bar}', '{$bar}', \r\n\t\t\t\t\t'" . USER_DIV . "'\r\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            # update stock(alloc + qty)
            $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            $Sl = "UPDATE " . $tab . " SET active = 'no' WHERE code = '{$bar}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            $stid = ext_dbget('stock', 'bar', $bar, 'stkid');
            if (!($stid > 0)) {
                return details($_POST, "<li class='err'><b>ERROR</b>: The bar code you selected is not in the system or is not available.</li>");
            }
            $Sl = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            $s = pg_fetch_array($Rs);
            # put scanned-in product into invoice db
            $sql = "INSERT INTO hire.hire_invitems(invid, whid, stkid, qty, amt, disc, discp,ss, div) VALUES('{$invid}', '{$s['whid']}', '{$stid}', '1', '{$s['selamt']}','0','0','{$bar}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            # update stock(alloc + qty)
            $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        }
    }
    /* --- Start button Listeners --- */
    if (isset($doneBtn)) {
        # check if stock was selected(yes = put done button)
        db_connect();
        $sql = "SELECT stkid FROM hire.hire_invitems WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
        $crslt = db_exec($sql);
        if (pg_numrows($crslt) < 1) {
            $error = "<li class='err'> Error : Invoice number has no items.</li>";
            return details($_POST, $error);
        }
        $TOTAL = sprint($TOTAL - $rounding);
        if ($pcash + $pcheque + $pcc + $pcredit < $TOTAL) {
            return details($_POST, "<li class='err'>The total of all the payments is less than the invoice total</li>");
        }
        $change = sprint(sprint($pcash + $pcheque + $pcc + $pcredit) - sprint($TOTAL));
        $pcash = sprint($pcash - $change);
        if ($pcash < 0) {
            $pcash = 0;
        }
        if (sprint($pcash + $pcheque + $pcc + $pcredit) != sprint($TOTAL)) {
            return details($_POST, "<li class='err'>The total of all the payments is not equal to the invoice total.<br>\r\n\t\t\t(You can only overpay with cash)</li>");
        }
        // make plant available
        $sql = "UPDATE hire.hire_invoices SET done = 'y' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice status in Cubit.", SELF);
        # print the invoice
        $OUTPUT = "<script>printer('pos-invoice-print.php?invid={$invid}');move('pos-invoice-new.php');</script>";
        require "template.php";
    } elseif (isset($cancel)) {
        // Final Laytout
        $write = "\r\n\t\t\t<table border='0' cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th>New Point of Sale Invoice Saved</th>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Invoice for <b>{$client}</b> has been saved.</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t<p>\r\n\t\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th>Quick Links</th>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><a href='pos-invoice-new.php'>New Point of Sale Invoice</a></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><a href='pos-invoice-list.php'>View Point of Sale Invoices</a></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t</table>";
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        return details($_POST);
    }
}
function confirm($_POST)
{
    # get vars
    extract($_POST);
    if ($type != $old_type) {
        return slctCat($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($type, "string", 1, 3, "Invalid category type.");
    $v->isOk($tab, "string", 1, 14, "Invalid category type.");
    $v->isOk($accname, "string", 1, 50, "Invalid account name.");
    $v->isOk($topacc, "num", 4, 4, "Invalid account number prefix.");
    $v->isOk($catid, "string", 1, 50, "Invalid category ID.");
    $v->isOk($accnum, "num", 0, 3, "Invalid account number suffix.");
    $v->isOk($toptype, "string", 1, 255, "Invalid category type.");
    #check the account numbers for range ...
    switch ($type) {
        case "I":
            $min = 01;
            $max = 1999;
            if ($topacc < $min or $topacc > $max) {
                $v->addError($topacc, "Please Ensure Account Number is Within Its Type Bracket ({$min} - {$max})");
            }
            break;
        case "E":
            $min = 2000;
            $max = 4999;
            if ($topacc < $min or $topacc > $max) {
                $v->addError($topacc, "Please Ensure Account Number is Within Its Type Bracket ({$min} - {$max})");
            }
            break;
        case "B":
            $min = 5000;
            $max = 9999;
            if ($topacc < $min or $topacc > $max) {
                $v->addError($topacc, "Please Ensure Account Number is Within Its Type Bracket ({$min} - {$max})");
            }
            break;
        default:
    }
    //	if ((strlen($accname) < 1) OR (strlen($topacc) < 1) OR (strlen($accnum) < 1))
    //		if ($oldtype != $type)
    //			$v->addError(null, "Please check account number for this category.");
    if (preg_match("/-- [A-Z]* --/", $toptype)) {
        $v->addError(null, "Please select a category type.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "<tr><td colspan='2' class='err'>";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        $confirm .= "</li>";
        # Return error function
        return slctCat($_POST, $confirm);
    }
    // If we don't have an accnum default to 000
    if (empty($accnum)) {
        $accnum = "000";
    }
    # Check Account name on selected type and category
    core_connect();
    //we need a better check than this ....
    //	$sql = "SELECT * FROM accounts WHERE accname = '$accname' AND div = '".USER_DIV."'";
    //	$checkRslt = db_exec ($sql) or errDie ("Unable to retrieve Account details from database.");
    //	if (pg_numrows($checkRslt) > 0) {
    //		$confirm = "
    //						<tr>
    //							<td colspan='2' class='err'>Account name already exist.</td>
    //						</tr>";
    //		# return error function
    //		return slctCat($_POST, $confirm);
    //	}
    $get_accs = "SELECT accname FROM accounts WHERE div = '" . USER_DIV . "'";
    $run_accs = db_exec($get_accs) or errDie("Unable to get accounts information.");
    if (pg_numrows($run_accs) > 0) {
        while ($aarr = pg_fetch_array($run_accs)) {
            $checkval = str_replace(" ", "", strtolower($aarr['accname']));
            if ($checkval == str_replace(" ", "", strtolower($accname))) {
                $confirm = "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='2'><li class='err'>Account name already exist.</li></td>\n\t\t\t\t\t</tr>";
                return slctCat($_POST, $confirm);
            }
        }
    }
    # Check Account name on selected type and category
    core_connect();
    $sql = "SELECT * FROM accounts WHERE topacc = '{$topacc}' AND accnum = '{$accnum}' AND div = '" . USER_DIV . "'";
    $cRslt = db_exec($sql) or errDie("Unable to retrieve Account details from database.");
    if (pg_numrows($cRslt) > 0) {
        $confirm = "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><li class='err'>The Account number is already in use.</li></td>\n\t\t\t</tr>";
        # return error function
        return slctCat($_POST, $confirm);
    }
    if ($accnum != "000") {
        #check if main account exists ...
        $sql = "SELECT * FROM accounts WHERE topacc = '{$topacc}' OFFSET 0 LIMIT 1";
        $run_sql = db_exec($sql) or errDie("Unable to get account information.");
        if (pg_numrows($run_sql) < 1) {
            $confirm = "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><li class='err'>Main Account doesn't exist.</li></td>\n\t\t\t\t</tr>";
            # return error function
            return slctCat($_POST, $confirm);
        }
    }
    $sql = "SELECT SUM(debit)-SUM(credit) AS balance,accname FROM core.trial_bal \n\t\t\tWHERE topacc = '{$topacc}' AND accnum='000' AND div = '" . USER_DIV . "' \n\t\t\tGROUP BY accname";
    $rslt = db_exec($sql);
    if (pg_num_rows($rslt) > 0) {
        $ad = pg_fetch_array($rslt);
        if ($ad['accname'] == "Customer Control Account") {
            return slctCat($_POST, "<li class='err'>You cannot add a sub account for the Customer Control Account.</li>");
        } else {
            if ($ad['accname'] == "Supplier Control Account") {
                return slctCat($_POST, "<li class='err'>You cannot add a sub account for the Supplier Control Account.</li>");
            } else {
                if ($ad['accname'] == "Inventory") {
                    return slctCat($_POST, "<li class='err'>You cannot add a sub account for the Inventory account.</li>");
                } else {
                    if ($ad['accname'] == "Employees Control Account") {
                        return slctCat($_POST, "<li class='err'>You cannot add a sub account for the Employees Control Account.</li>");
                    } else {
                        if ($ad["balance"] != 0) {
                            return slctCat($_POST, "<li class='err'>You cannot create a sub account for a main account that already has transactions.</li>");
                        }
                    }
                }
            }
        }
    }
    // Get the human value of toptype
    $toptype_h = explode(":", $toptype);
    $toptype_h = $toptype_h[1];
    $confirm = "\n\t\t<h3>Add New Account</h3>\n\t\t<h4>Confirm entry</h4>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='write' />\n\t\t\t<input type='hidden' name='type' value='{$type}' />\n\t\t\t<input type='hidden' name='catid' value='{$catid}' />\n\t\t\t<input type='hidden' name='tab' value='{$tab}' />\n\t\t\t<input type='hidden' name='accname' value='{$accname}' />\n\t\t\t<input type='hidden' name='topacc' value='{$topacc}' />\n\t\t\t<input type='hidden' name='accnum' value='{$accnum}' />\n\t\t\t<input type='hidden' name='toptype' value='{$toptype}' />\n\t\t\t<input type='hidden' name='update_parent' value='{$update_parent}' />\n\t\t\t<input type='hidden' name='set_key' value='{$set_key}' />\n\t\t\t<tr>\n\t\t\t\t<th>Field</th>\n\t\t\t\t<th>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Account Type</td>\n\t\t\t\t<td>{$tab}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Category ID</td>\n\t\t\t\t<td>{$catid}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Category Type</td>\n\t\t\t\t<td>{$toptype_h}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Account Number</td>\n\t\t\t\t<td>{$topacc}/{$accnum}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Account Name</td>\n\t\t\t\t<td>{$accname}</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td><input type='submit' name='back' value='&laquo; Correction' /></td>\n\t\t\t\t<td align='right'><input type='submit' value='Write &raquo' /></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>" . mkQuickLinks(ql("../reporting/allcat.php", "List All Accounts (New Window)", true), ql("acc-view.php", "View Accounts"), ql("acc-new2.php", "Add Account"));
    return $confirm;
}
function con_data($_POST)
{
    # get vars
    extract($_POST);
    if (isset($back)) {
        return view_data($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($id, "num", 0, 100, "Invalid number.");
    $v->isOk($depamt, "float", 0, 14, "Invalid Depreciation Amount.");
    $v->isOk($depmonths, "num", 0, 3, "Invalid auto depreciation period.");
    $v->isOk("{$depmonths}{$depamt}", "float", 1, 14, "Enter one of Depreciation amount or period.");
    if (!empty($depamt) && $netval < $depamt) {
        $v->isOk("###", "float", 1, 1, "Error : Depreciation amount must not be more than the Net Value.");
    } else {
        if (!empty($depmonths) && $depperc <= 0) {
            $v->addError("###", "Depriaction percentage has to be more than 0 if depreciating by period.");
        }
    }
    $v->isOk($date, "date", 1, 14, "Invalid account open date.");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class=err>" . $e["msg"];
        }
        $confirmCust .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    db_conn('cubit');
    $user = USER_NAME;
    $Sql = "SELECT * FROM assets WHERE (id='{$id}' AND div = '" . USER_DIV . "')";
    $Rslt = db_exec($Sql) or errDie("Unable to access database.");
    if (pg_numrows($Rslt) < 1) {
        return "Asset not Found";
    }
    $led = pg_fetch_array($Rslt);
    # Get group
    $sql = "SELECT * FROM assetgrp WHERE grpid = '{$led['grpid']}' AND div = '" . USER_DIV . "'";
    $grpRslt = db_exec($sql);
    $grp = pg_fetch_array($grpRslt);
    # get last ref number
    $refnum = getrefnum($date);
    if ($led["dep_acc"]) {
        $dep_acc = $led["dep_acc"];
    } else {
        // Maintain backwards compatibiltiy
        $sql = "\r\n\t\tSELECT accid FROM core.accounts\r\n\t\tWHERE topacc='2200' AND accnum='000'";
        $acc_rslt = db_exec($sql) or errDie("Unable to retrieve account.");
        $dep_acc = pg_fetch_result($acc_rslt, 0);
    }
    if ($led["accdep_acc"]) {
        $accdep_acc = $led["accdep_acc"];
    } else {
        // Maintain backwards compatibiltiy
        $accdep_acc = $grp["accdacc"];
    }
    pglib_transaction("BEGIN");
    # dt(depacc) ct(accdep)
    writetrans($dep_acc, $accdep_acc, $date, $refnum, $depamt, "{$led['des']} Depreciation");
    db_connect();
    $sql = "UPDATE assets SET accdep = (accdep + '{$depamt}') WHERE (id='{$id}' AND div = '" . USER_DIV . "')";
    $up = db_exec($sql) or errdie("Could not update assets table.");
    $snetval = $netval - $depamt;
    $sdate = date("Y-m-d");
    $sql = "INSERT INTO assetledger(assetid, asset, date, depamt, netval, div) \r\n\t\t\tVALUES ('{$id}', '{$led['des']}', '{$date}', '{$depamt}', '{$snetval}', '" . USER_DIV . "')";
    $rec = db_exec($sql) or errdie("Could not write to asset ledger.");
    $cc = "<script> CostCenter('ct', 'Asset Depreciation', '{$date}', '{$led['des']} Depreciation', '{$depamt}', ''); </script>";
    pglib_transaction("COMMIT");
    $write = "\r\n\t\t\t\t{$cc}\r\n\t\t\t\t<table " . TMPL_tblDflts . " width='50%'>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Asset Depreciation</th>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='datacell'>\r\n\t\t\t\t\t\t<td>Asset Depreciation has been recorded</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</table>\r\n\t\t\t\t<p>\r\n\t\t\t\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Quick Links</th>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td><a href='asset-new.php'>New Asset</a></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td><a href='asset-view.php'>View Assets</a></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t\t</table>";
    return $write;
}
function confirm($_POST)
{
    # get vars
    $_POST = var_makesafe($_POST);
    extract($_POST);
    if (isset($back)) {
        return slctEmployee();
    }
    $annual += 0;
    $bonus += 0;
    $mpaye_amount += 0;
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($account)) {
        $v->isOk($account, "num", 1, 9, "Invalid ledger account.");
    }
    $v->isOk($empnum, "num", 1, 9, "Invalid employee number.");
    $v->isOk($accid, "num", 1, 9, "Invalid bank number.");
    $v->isOk($MON, "num", 1, 2, "Invalid month.");
    $v->isOk($bonus, "float", 1, 11, "Invalid bonus.");
    $v->isOk($mpaye_amount, "float", 1, 11, "Invalid manual PAYE amount.");
    $v->isOk($all_travel, "float", 1, 11, "Invalid travel allowance.");
    $v->isOk($comp_pension, "float", 1, 11, "Invalid company pension.");
    $v->isOk($comp_medical, "float", 1, 11, "Invalid company medical.");
    $v->isOk($emp_pension, "float", 1, 11, "Invalid employee pension.");
    $v->isOk($emp_medical, "float", 1, 11, "Invalid employee medical.");
    $v->isOk($comp_provident, "float", 1, 11, "Invalid company provident.");
    $v->isOk($emp_provident, "float", 1, 11, "Invalid employee provident.");
    //$v->isOk ($comp_uif, "float", 1, 11, "Invalid company uif.");
    //$v->isOk ($emp_uif, "float", 1, 11, "Invalid employee uif.");
    $v->isOk($comp_other, "float", 1, 11, "Invalid company other.");
    $v->isOk($emp_other, "float", 1, 11, "Invalid employee other.");
    $v->isOk($comp_ret, "float", 1, 11, "Invalid company ret.");
    $v->isOk($emp_ret, "float", 1, 11, "Invalid employee ret.");
    $v->isOk($basic_sal, "float", 1, 11, "Invalid basic salary.");
    $v->isOk($commission, "float", 0, 11, "Invalid commision.");
    $v->isOk($loaninstall, "float", 0, 11, "Invalid loan installment.");
    $v->isOk($loanint, "float", 0, 11, "Invalid loan interest.");
    if ($divisor != 1 && round($divisor, 2) != round(52 / 12, 2) && round($divisor) != round(26 / 12, 2)) {
        $v->addError("", "Invalid pay period (DIVIS).");
    }
    if ($saltyp == 'd' || $saltyp == 'h') {
        $salnarr = array("d" => "Days", "h" => "Hours");
        $salntype = $salnarr[$saltyp];
        $v->isOk($multi, "float", 1, 5, "Invalid number of {$salntype}.");
        if ($multi < 1) {
            $v->isOk("##", "num", 1, 1, "Error : Employee cannot be paid for {$multi} {$salntype}.");
        }
    }
    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, 3, "Invalid allowance tax option" . ($key + 1) . ".");
        }
    }
    $date = $day . "-" . $mon . "-" . $year;
    $ydate = $year . "-" . $mon . "-" . $day;
    if (!checkdate($mon, $day, $year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $confirmCust . process($_POST);
    }
    db_conn('cubit');
    $sql = "SELECT * FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "'";
    $empRslt = db_exec($sql) or errDie("Unable to select employees from database.");
    if (pg_numrows($empRslt) < 1) {
        return "Invalid employee ID.";
    }
    $myEmp = pg_fetch_array($empRslt);
    if ($myEmp['payprd'] == "d") {
        $Sl = "SELECT * FROM salpaid WHERE empnum='{$empnum}' AND saldate='{$ydate}'";
        $Ri = db_exec($Sl);
        $paid = pg_num_rows($Ri);
        $Sl = "SELECT * FROM salr WHERE empnum='{$empnum}' AND saldate='{$ydate}'";
        $Ri = db_exec($Sl);
        $upaid = pg_num_rows($Ri);
        $upaid += 0;
        $paid -= $upaid;
    } elseif ($myEmp['payprd'] == "w") {
        $yy = date("Y");
        $mm = $MON;
        $mm += 0;
        $Sl = "SELECT * FROM salpaid WHERE empnum='{$empnum}' AND month='{$mm}' AND substr(saldate,1,4)='{$yy}' AND week='{$week}'";
        $Ri = db_exec($Sl);
        $paid = pg_num_rows($Ri);
        $Sl = "SELECT * FROM salr WHERE empnum='{$empnum}' AND month='{$mm}' AND substr(saldate,1,4)='{$yy}' AND week='{$week}'";
        $Ri = db_exec($Sl);
        $upaid = pg_num_rows($Ri);
        $upaid += 0;
        $paid -= $upaid;
    } elseif ($myEmp['payprd'] == "f") {
        $yy = date("Y");
        $mm = $MON;
        $mm += 0;
        $Sl = "SELECT * FROM salpaid WHERE empnum='{$empnum}' AND month='{$mm}' AND substr(saldate,1,4)='{$yy}' AND week='{$week}'";
        $Ri = db_exec($Sl);
        $paid = pg_num_rows($Ri);
        $Sl = "SELECT * FROM salr WHERE empnum='{$empnum}' AND month='{$mm}' AND substr(saldate,1,4)='{$yy}' AND week='{$week}'";
        $Ri = db_exec($Sl);
        $upaid = pg_num_rows($Ri);
        $upaid += 0;
        $paid -= $upaid;
    }
    if (isset($paid) && $paid > 0) {
        return "<li class='err'>You have already processed a salary for that period</li>" . process($_POST);
    }
    $salconacc = gethook("accnum", "salacc", "name", "salaries control");
    $salconacc_orig = gethook("accnum", "salacc", "name", "salaries control original");
    if ($salconacc != $salconacc_orig) {
        block_check($salconacc);
    }
    block_check($uifbal = gethook("accnum", "salacc", "name", "uifbal"));
    block_check($intrec = gethook("accnum", "salacc", "name", "interestreceived"));
    block_check($sdlbal = gethook("accnum", "salacc", "name", "sdlbal"));
    block_check($pa = gethook("accnum", "salacc", "name", "pension"));
    block_check($ma = gethook("accnum", "salacc", "name", "medical"));
    block_check($cash_account = gethook("accnum", "salacc", "name", "cash"));
    block_check($retire = gethook("accnum", "salacc", "name", "retire"));
    block_check($provident = gethook("accnum", "salacc", "name", "provident"));
    block_check($commacc = gethook("accnum", "salacc", "name", "Commission"));
    block_check($payeacc = gethook("accnum", "salacc", "name", "PAYE"));
    block_check($uifacc = gethook("accnum", "salacc", "name", "UIF"));
    block_check($providente = $myEmp["expacc_provident"]);
    block_check($retiree = $myEmp["expacc_ret"]);
    block_check($pax = $myEmp["expacc_pension"]);
    block_check($uifexp = $myEmp["expacc_uif"]);
    block_check($max = $myEmp["expacc_medical"]);
    block_check($dedgenerale = $myEmp["expacc_other"]);
    block_check($sdlexp = $myEmp["expacc_sdl"]);
    block_check($salacc = $myEmp["expacc_salwages"]);
    if (($loanexp = $myEmp["expacc_loan"]) > 0) {
        block_check($loanexp);
    }
    if (isset($allowaccs)) {
        foreach ($allowaccs as $checkacc) {
            block_check($checkacc);
        }
    }
    if (isset($dedaccs)) {
        foreach ($dedaccs as $k => $checkacc) {
            block_check($checkacc);
        }
    }
    if (isset($bal_dedaccs)) {
        foreach ($bal_dedaccs as $checkacc) {
            if ($checkacc != 0) {
                block_check($checkacc);
            }
        }
    }
    finish_block_check();
    # The Paye
    $tyear = 12;
    switch ($saltyp) {
        case 'm':
            $tyear = 12;
            $perhr = sprint($basic_sal / ($myEmp['hpweek'] * 52 / 12));
            break;
        case 'w':
            $tyear = 52;
            $perhr = sprint($basic_sal / $myEmp['hpweek']);
            break;
        case 'f':
            $tyear = 26;
            $perhr = sprint($basic_sal / ($myEmp['hpweek'] * 2));
            break;
        case 'd':
            $tyear = 5 * 52;
            $perhr = sprint($basic_sal / ($myEmp['hpweek'] / 5));
            break;
        case 'h':
            $tyear = 45 * 52;
            $perhr = $basic_sal;
            break;
    }
    $overamt = $novert * ($perhr * $myEmp['novert']);
    $overamt += $hovert * ($perhr * $myEmp['hovert']);
    $overamt = sprint($overamt);
    # Multiply basic_sal add overtime
    if (isset($multi)) {
        $basic_sal = sprint($basic_sal * $multi);
        $tyear = $tyear / $multi;
    }
    # Zero if not specified
    $commission = $commission + 0;
    $loaninstall = $loaninstall + 0;
    //$basic_sal=$basic_sal+$commission;
    $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 .= "\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td>{$allowname[$key]}</td>\r\n\t\t\t\t\t\t<td>" . CUR . " {$allowances[$key]}</td>\r\n\t\t\t\t\t</tr>";
                $all_beforeamount = $all_beforeamount + $allowances[$key];
            } elseif ($allowances[$key] > 0) {
                $all_after .= "\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td>{$allowname[$key]}</td>\r\n\t\t\t\t\t\t<td>" . CUR . " {$allowances[$key]}</td>\r\n\t\t\t\t\t</tr>";
                $all_afteramount = $all_afteramount + $allowances[$key];
            }
        }
    }
    $de_before = "\r\n\t\t<tr>\r\n\t\t\t<td colspan='2'>\r\n\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Details</th>\r\n\t\t\t\t\t\t<th>Employee Contribution</th>\r\n\t\t\t\t\t\t<!--<th>Employer Contribution</th>//-->\r\n\t\t\t\t\t</tr>";
    $de_after = "\r\n\t\t<tr>\r\n\t\t\t<td colspan='2'>\r\n\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Details</th>\r\n\t\t\t\t\t\t<th>Employee Contribution</th>\r\n\t\t\t\t\t\t<!--<th>Employer Contribution</th>//-->\r\n\t\t\t\t\t</tr>";
    $de_beforeamount = 0;
    $de_afteramount = 0;
    $de_beforeamount_emp = 0;
    $de_afteramount_emp = 0;
    if (isset($deducttax)) {
        foreach ($deducttax as $key => $perc) {
            if ($perc == "Yes" and $deductions[$key] > 0) {
                $de_before .= "\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td>{$deductname[$key]}</td>\r\n\t\t\t\t\t\t<td>" . CUR . " {$deductions[$key]}</td>\r\n\t\t\t\t\t\t<!--<td>" . CUR . " {$employer_deductions[$key]}</td>//-->\r\n\t\t\t\t\t</tr>";
                $de_beforeamount = $de_beforeamount + $deductions[$key] + $employer_deductions[$key];
                $de_beforeamount_emp += $employer_deductions[$key];
            } elseif ($deductions[$key] > 0) {
                $de_after .= "\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td>{$deductname[$key]}</td>\r\n\t\t\t\t\t\t<td>" . CUR . " {$deductions[$key]}</td>\r\n\t\t\t\t\t\t<!--<td>" . CUR . " {$employer_deductions[$key]}</td>//-->\r\n\t\t\t\t\t</tr>";
                $de_afteramount = $de_afteramount + $deductions[$key] + $employer_deductions[$key];
                $de_afteramount_emp += $employer_deductions[$key];
            }
        }
    }
    $de_before .= "</table></td></tr>";
    $de_after .= "</table></td></tr>";
    if ($all_beforeamount > 0) {
        $all_before = "<tr><th colspan='2'>Allowances</th></tr>" . $all_before;
    }
    if ($all_afteramount > 0) {
        $all_after = "<tr><th colspan='2'>Allowances</th></tr>" . $all_after;
    }
    if ($de_beforeamount > 0) {
        $de_before = "<tr><th colspan='2'>Deductions</th></tr>" . $de_before;
    } else {
        $de_before = "";
    }
    if ($de_afteramount > 0) {
        $de_after = "<tr><th colspan='2'>Deductions</th></tr>" . $de_after;
    } else {
        $de_after = "";
    }
    // calculate age of employee (if intl., ie has passport num only), act asif under 65
    if (!empty($myEmp["idnum"])) {
        $bd_year = 1900 + substr($myEmp["idnum"], 0, 2);
        $bd_month = substr($myEmp["idnum"], 2, 2);
        $bd_day = substr($myEmp["idnum"], 4, 2);
        /* get the current financial year */
        db_conn("core");
        $sql = "SELECT yrname FROM active";
        $rslt = db_exec($sql) or errDie("Error fetching financial year.");
        if (pg_num_rows($rslt) < 1) {
            return "Please run quick setup first.";
        }
        $fin_year = substr(pg_fetch_result($rslt, 0, 0), 1);
        $sql = "SELECT EXTRACT('year' FROM AGE('{$fin_year}-02-28', '{$bd_year}-{$bd_month}-{$bd_day}'))";
        $rslt = db_exec($sql) or errDie("Error calculating age at financial year end.");
        $age = pg_fetch_result($rslt, 0, 0);
    } else {
        $age = 1;
    }
    /* calculate uif */
    $tmp_uif = $basic_sal + $all_travel + $overamt + $comp_provident + $comp_pension + $comp_ret + $all_beforeamount + $all_afteramount + $comp_medical + $bonus;
    $comp_uif = sprint($tmp_uif * ($myEmp["comp_uif"] / 100));
    $emp_uif = sprint($tmp_uif * ($myEmp["emp_uif"] / 100));
    db_conn("cubit");
    $sql = "SELECT value FROM settings WHERE constant='UIF_MAX'";
    $percrslt = db_exec($sql);
    $perc = pg_fetch_array($percrslt);
    $uifmax = $perc['value'];
    if ($emp_uif > $uifmax) {
        $emp_uif = sprint($uifmax);
    }
    if ($comp_uif > $uifmax) {
        $comp_uif = sprint($uifmax);
    }
    /* calculate sdl */
    $tmp_sdl = $basic_sal + $overamt + $commission + $comp_provident + $all_travel + $all_beforeamount + $all_afteramount + $comp_medical + $bonus;
    if ($age > 65) {
        $tmp_sdl -= $comp_medical;
    }
    $comp_sdl = $tmp_sdl * ($myEmp["comp_sdl"] / 100);
    // calculate loan fringe benefit amount for this month
    if (!empty($myEmp["loanamt"]) && $myEmp["gotloan"] == "t" && $myEmp["loanamt"] > 0) {
        $loanpart = $loaninstall / $myEmp["loanamt"];
        $fringe_loan = sprint($myEmp["loanfringe"] * $loanpart);
    } else {
        $fringe_loan = "0.00";
    }
    $car_count = ($myEmp["fringe_car1"] > 0 ? 1 : 0) + ($myEmp["fringe_car2"] > 0 ? 1 : 0);
    // if car count is one and employee gets a travel allowance, that car's fringe benefit is calculated
    // as if the second car, and ALSO: contribitions/fuel/service amounts are not deducted from benefit
    $car1_travelall = $car_count == 1 && $all_travel > 0;
    if ($car1_travelall) {
        $PERC1 = 0.04;
    } else {
        $PERC1 = 0.018;
    }
    // calculate motor car fringe benefit
    if ($myEmp["fringe_car1"] > 0) {
        $fringe_car1 = $myEmp["fringe_car1"] * ($myEmp["fringe_car1"] >= $myEmp["fringe_car2"] ? $PERC1 : 0.04);
        $fringe_car1 /= $divisor;
        if ($myEmp["fringe_car1_contrib"] > 0 && !$car1_travelall) {
            $fringe_car1 -= $myEmp["fringe_car1_contrib"] / $divisor;
        }
        if ($myEmp["fringe_car1_fuel"] == 1 && !$car1_travelall) {
            $fringe_car1 -= 120 / $divisor;
        }
        if ($myEmp["fringe_car1_service"] == 1 && !$car1_travelall) {
            $fringe_car1 -= 85 / $divisor;
        }
        if ($fringe_car1 < 0) {
            $fringe_car1 = 0;
        }
    } else {
        $fringe_car1 = 0;
    }
    if ($myEmp["fringe_car2"] > 0) {
        $fringe_car2 = $myEmp["fringe_car2"] * ($myEmp["fringe_car2"] > $myEmp["fringe_car1"] ? $PERC1 : 0.04);
        $fringe_car2 /= $divisor;
        if ($myEmp["fringe_car2_contrib"] > 0 && !$car1_travelall) {
            $fringe_car2 -= $myEmp["fringe_car2_contrib"] / $divisor;
        }
        if ($myEmp["fringe_car2_fuel"] == 1 && !$car1_travelall) {
            $fringe_car2 -= 120 / $divisor;
        }
        if ($myEmp["fringe_car2_service"] == 1 && !$car1_travelall) {
            $fringe_car2 -= 85 / $divisor;
        }
        if ($fringe_car2 < 0) {
            $fringe_car2 = 0;
        }
    } else {
        $fringe_car2 = 0;
    }
    $fringe_car1 = sprint($fringe_car1);
    $fringe_car2 = sprint($fringe_car2);
    // calc medical 1/3rd fringe benefits
    $tot_medical = sprint($emp_medical + $comp_medical);
    if ($comp_medical > $tot_medical / 3 * 2) {
        $fringe_medical = sprint($comp_medical - $tot_medical / 3 * 2);
    } else {
        $fringe_medical = 0;
    }
    // calculate total fringe benefits
    $tot_fringe = $fringe_medical + $fringe_car1 + $fringe_car2 + $fringe_loan + $comp_other + $comp_ret + $de_beforeamount_emp + $de_afteramount_emp;
    if (isset($fringeid)) {
        foreach ($fringeid as $key => $value) {
            $fringebens[$key] = sprint($fringebens[$key]);
            $tot_fringe += $fringebens[$key];
        }
    }
    if ($emp_pension > $basic_sal * 7.5 / 100) {
        $emp_pension = $basic_sal * 7.5 / 100;
    }
    $max_ret = $myEmp["basic_sal_annum"] * 7.5 / 100 > 1750 ? $myEmp["basic_sal_annum"] * 7.5 / 100 : 1750;
    // calculate total gross salary
    $grossal = $basic_sal + $commission + $overamt + $bonus + $annual + $all_beforeamount + $all_travel * 0.5 - $de_beforeamount;
    // deductions deducted before paye (non taxible)
    $grossal_2 = $grossal;
    $grossal_nodedall = $basic_sal + $overamt + $bonus + $annual + $all_travel;
    // pension/provident/ra: calculate deduction amounts, limiting them to maximum amount and only deducting
    // ONE of them for taxable income
    if ($comp_pension + $emp_pension > 0) {
        $tmp = ($grossal_2 + $tot_fringe) * $tyear;
        $maxallowed = $tmp * 0.075 > 1750 ? $tmp * 0.075 : 1750;
        if ($emp_pension > $maxallowed) {
            $tmp_ded = $maxallowed;
        } else {
            $tmp_ded = $emp_pension;
        }
        $grossal -= $tmp_ded;
    }
    if ($comp_ret + $emp_ret > 0) {
        $tmp = ($grossal_2 + $tot_fringe) * $tyear;
        // if their is a pension contributions the percentage is 0
        if ($comp_pension + $emp_pension + $comp_provident + $emp_provident > 0) {
            $PERC = 0;
        } else {
            $PERC = 0.15;
        }
        $maxallowed = $tmp * $PERC > 1750 ? $tmp * $PERC : 1750;
        $maxallowed = $maxallowed > 3500 - $emp_pension * 12 ? $maxallowed : 3500 - $emp_pension * 12;
        if ($emp_ret + $comp_ret > $maxallowed / 12) {
            $tmp_ded = $maxallowed / 12;
        } else {
            $tmp_ded = $emp_ret + $comp_ret;
        }
        $grossal -= $tmp_ded;
    }
    // calculate total paye salary
    // just remove annual this month, and add annual divided by 12
    // because paye is calculate for full twelve months and therefore
    // paye salary is average received each month
    $paye_salary = $grossal - $annual + $tot_fringe;
    // total fringe benefits;
    // a little hack, apparently the grossal is displayed wrong, in a strictly antisocial.co.za opinion,
    // i think the person who thinks that must suck
    $grossal += $comp_ret;
    if (isset($mpaye)) {
        $paye = $mpaye_amount;
    } else {
        // calculate paye (take age of 65+ threshold into account)
        if ($age >= 65 && $paye_salary * $tyear < 60000 || $paye_salary * $tyear < 35000) {
            $paye = "0.00";
        } else {
            $paye = calculate_paye($paye_salary, $tyear, $age);
            if ($annual > 0) {
                $tmp_bonpaye = calculate_paye($paye_salary + $annual / 12, $tyear, $age);
                $paye += $tmp_bonpaye * $tyear - $paye * $tyear;
            }
        }
    }
    // fringe benefits
    $i = 0;
    $fringes = "";
    $fringes_desc = "";
    if (isset($fringebens)) {
        foreach ($fringebens as $key => $value) {
            if ($fringebens[$key] > 0) {
                $fringes_desc .= "\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>{$fringename[$key]}</td>\r\n\t\t\t\t\t<td>" . CUR . " {$fringebens[$key]}</td>\r\n\t\t\t\t</tr>";
                $fringes .= "\r\n\t\t\t\t\t<input type=hidden name='fringebens[]' value='{$fringebens[$key]}'>\r\n\t\t\t\t\t<input type=hidden name='fringeid[]' value='{$fringeid[$key]}'>\r\n\t\t\t\t\t<input type=hidden name='fringename[]' value='{$fringename[$key]}'>\r\n\t\t\t\t\t<input type=hidden name='fringeaccs[]' value='{$fringeaccs[$key]}'>";
            }
        }
    }
    if (!empty($fringes_desc)) {
        $fringes_desc = "<tr><th colspan=2>Fringe Benefits</th></tr>{$fringes_desc}";
    }
    $allow = "";
    # Get allowances names and value from array
    if (isset($allowances)) {
        foreach ($allowances as $key => $value) {
            if ($allowances[$key] > 0) {
                $allow .= "\r\n\t\t\t\t\t<input type='hidden' size='10' name='allowname[]' value='{$allowname[$key]}'>\r\n\t\t\t\t\t<input type='hidden' size='10' name='allowid[]' value='{$allowid[$key]}'>\r\n\t\t\t\t\t<input type='hidden' size='10' name='allowances[]' value='{$allowances[$key]}'>\r\n\t\t\t\t\t<input type='hidden' size='10' name='allowtax[]' value='{$allowtax[$key]}'>\r\n\t\t\t\t\t<input type='hidden' name='allowaccs[]' value='{$allowaccs[$key]}'>";
            }
        }
    }
    $deduct = "";
    if (isset($deductions)) {
        foreach ($deductions as $key => $value) {
            if ($deductions[$key] > 0) {
                $deduct .= "\r\n\t\t\t\t\t<input type='hidden' size='10' name='deductname[]' value='{$deductname[$key]}'>\r\n\t\t\t\t\t<input type='hidden' size='10' name='deductid[]' value='{$deductid[$key]}'>\r\n\t\t\t\t\t<input type='hidden' size='10' name='deductions[]' value='{$deductions[$key]}'>\r\n\t\t\t\t\t<input type='hidden' size='10' name='employer_deductions[]' value='{$employer_deductions[$key]}'>\r\n\t\t\t\t\t<input type='hidden' size='10' name='deducttax[]' value='{$deducttax[$key]}'>\r\n\t\t\t\t\t<input type='hidden' name='dedaccs[]' value='{$dedaccs[$key]}'>\r\n\t\t\t\t\t<input type='hidden' name='bal_dedaccs[]' value='{$bal_dedaccs[$key]}'>";
            }
        }
    }
    $nonretfunding = $basic_sal - $paye - $loaninstall - $de_afteramount + $de_afteramount_emp + $all_afteramount - $emp_pension - $emp_medical - $emp_uif - $emp_provident;
    /*$ret_max = (1800>($nonretfunding*0.15)) ? 1800 : ($nonretfunding*0.15);
    
    	if ( $comp_ret + $emp_ret > $ret_max ) {
    		$comp_ret = $ret_max - $emp_ret;
    
    		if ( $comp_ret < 0 ) {
    			$comp_ret = 0;
    			$emp_ret = $ret_max;
    		}
    	}*/
    $nettpay = $basic_sal + $overamt - $paye - $loaninstall - $de_beforeamount - $de_afteramount + $all_afteramount + $all_beforeamount - $emp_pension - $emp_medical - $emp_ret - $emp_uif - $emp_provident - $emp_other + $all_travel + $annual + $bonus;
    $nettpay = sprint($nettpay);
    if (isset($rbsa)) {
        $nettpay += array_sum($rbsa);
        $nettpay = sprint($nettpay);
    }
    db_conn("cubit");
    # Get bank account name
    $sql = "SELECT * FROM bankacct WHERE bankid = '{$accid}' AND div = '" . USER_DIV . "'";
    $bankRslt = db_exec($sql);
    $bank = pg_fetch_array($bankRslt);
    $basic_sal = sprint($basic_sal);
    $commission = sprint($commission);
    $overamt = sprint($overamt);
    $paye = sprint($paye);
    $nettpay = sprint($nettpay);
    if ($myEmp['paytype'] == "Cash") {
        $paydetails = " <tr class='" . bg_class() . "'><td colspan=2>Pay Salary Cash</td></tr>";
    } else {
        $paydetails = " <tr class='" . bg_class() . "'><td>Bank Account</td><td>{$bank['accname']}</td></tr>";
    }
    $bonus = sprint($bonus);
    $annual = sprint($annual);
    $comp_pension = sprint($comp_pension);
    $emp_medical = sprint($emp_medical);
    $comp_ret = sprint($comp_ret);
    $emp_ret = sprint($emp_ret);
    $loaninstall = sprint($loaninstall);
    $emp_pension = sprint($emp_pension);
    if (!isset($account)) {
        $account = 0;
    } else {
        db_conn('core');
        $Sl = "SELECT * FROM accounts WHERE accid='{$account}'";
        $Ri = db_exec($Sl);
        $ad = pg_fetch_array($Ri);
        $paydetails = " <tr class='" . bg_class() . "'><td>Ledger Account</td><td>{$ad['accname']}</td></tr>";
    }
    db_conn('cubit');
    //$rt="<table border=0 cellpadding='".TMPL_tblCellPadding."' cellspacing='".TMPL_tblCellSpacing."'>
    $Sl = "SELECT * FROM rbs ORDER BY name";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    $i = 0;
    $rt = "";
    if (pg_num_rows($Ri) > 0) {
        while ($td = pg_fetch_array($Ri)) {
            if (!isset($rbsa[$td['id']]) || $rbsa[$td['id']] < 1) {
                continue;
            }
            $rbsa[$td['id']] = sprint($rbsa[$td['id']]);
            if ($i == 0) {
                $rt = "<tr><th colspan='2'>Reimbursements</th></tr>";
            }
            $rt .= "\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><input type='hidden' name='rbs[{$td['id']}]' value='{$td['id']}'>{$td['name']}</td>\r\n\t\t\t\t\t<td>" . CUR . " <input type='hidden' name='rbsa[{$td['id']}]' value='" . $rbsa[$td['id']] . "'>" . $rbsa[$td['id']] . "</td>\r\n\t\t\t\t</tr>";
            $i++;
        }
    } else {
        //$rt.="<tr class='bg-odd'><td colspan=2>There are no reimbursements</td></tr>";
    }
    if ($myEmp['payprd'] == "w") {
        $row = "\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>Period</td>\r\n\t\t\t\t<td>{$week}</td>\r\n\t\t\t</tr>\r\n\t\t\t<input type='hidden' name='week' value='{$week}'>";
    } else {
        if ($myEmp['payprd'] == "f") {
            $row = "\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>Period</td>\r\n\t\t\t\t<td>{$week}</td>\r\n\t\t\t</tr>\r\n\t\t\t<input type='hidden' name='week' value='{$week}'>";
        } else {
            $row = "<input type='hidden' name='week' value='0'>";
        }
    }
    $grossal = sprint($grossal);
    $confirm = "\r\n        <table " . TMPL_tblDflts . " width='300'>\r\n        <form action='" . SELF . "' method='POST'>\r\n\t\t\t<input type='hidden' name='key' value='pack'>\r\n\t\t\t<input type='hidden' name='grossal' value='{$grossal}'>\r\n\t\t\t<input type='hidden' name='grossal_nodedall' value='{$grossal_nodedall}'>\r\n\t\t\t<input type='hidden' name='empnum' value='{$empnum}'>\r\n\t\t\t<input type='hidden' name='account' value='{$account}'>\r\n\t\t\t<input type='hidden' name='MON' value={$MON}>\r\n\t\t\t<input type='hidden' name='basic_sal' value='{$basic_sal}'>\r\n\t\t\t<input type='hidden' name='commission' value='{$commission}'>\r\n\t\t\t<input type='hidden' name='overamt' value='{$overamt}'>\r\n\t\t\t<input type='hidden' name='loaninstall' value='{$loaninstall}'>\r\n\t\t\t<input type='hidden' name='paye' value='{$paye}'>\r\n\t\t\t<input type='hidden' name='accid' value='{$accid}'>\r\n\t\t\t<input type='hidden' name='income' value='{$nettpay}'>\r\n\t\t\t<input type='hidden' name='bonus' value='{$bonus}'>\r\n\t\t\t<input type='hidden' name='all_travel' value='{$all_travel}'>\r\n\t\t\t<input type='hidden' name='comp_pension' value='{$comp_pension}'>\r\n\t\t\t<input type='hidden' name='emp_pension' value='{$emp_pension}'>\r\n\t\t\t<input type='hidden' name='comp_medical' value='{$comp_medical}'>\r\n\t\t\t<input type='hidden' name='emp_medical' value='{$emp_medical}'>\r\n\t\t\t<input type='hidden' name='comp_ret' value='{$comp_ret}'>\r\n\t\t\t<input type='hidden' name='emp_ret' value='{$emp_ret}'>\r\n\t\t\t<input type='hidden' name='comp_uif' value='{$comp_uif}'>\r\n\t\t\t<input type='hidden' name='emp_uif' value='{$emp_uif}'>\r\n\t\t\t<input type='hidden' name='comp_sdl' value='{$comp_sdl}'>\r\n\t\t\t<input type='hidden' name='comp_other' value='{$comp_other}'>\r\n\t\t\t<input type='hidden' name='emp_other' value='{$emp_other}'>\r\n\t\t\t<input type='hidden' name='comp_provident' value='{$comp_provident}'>\r\n\t\t\t<input type='hidden' name='emp_provident' value='{$emp_provident}'>\r\n\t\t\t<input type='hidden' name='paye_salary' value='{$paye_salary}'>\r\n\t\t\t<input type='hidden' name='day' value='{$day}'>\r\n\t\t\t<input type='hidden' name='mon' value='{$mon}'>\r\n\t\t\t<input type='hidden' name='year' value='{$year}'>\r\n\t\t\t<input type='hidden' name='novert' value='{$novert}'>\r\n\t\t\t<input type='hidden' name='hovert' value='{$hovert}'>\r\n\t\t\t<input type='hidden' name='annual' value='{$annual}'>\r\n\t\t\t<input type='hidden' name='week' value='{$week}'>\r\n\t\t\t<input type='hidden' name='fringe_medical' value='{$fringe_medical}'>\r\n\t\t\t<input type='hidden' name='fringe_tot' value='{$tot_fringe}'>\r\n\t\t\t<input type='hidden' name='fringe_car1' value='{$fringe_car1}'>\r\n\t\t\t<input type='hidden' name='fringe_car2' value='{$fringe_car2}'>\r\n\t\t\t<input type='hidden' name='fringe_loan' value='{$fringe_loan}'>\r\n\t\t\t<input type='hidden' name='process_comp_deductions' value='{$process_comp_deductions}'>\r\n\t\t\t{$fringes}\r\n\t\t\t{$allow}\r\n\t\t\t{$deduct}\r\n\t\t\t<tr><th colspan='2'>Salary Details</th></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Basic salary</td><td>" . CUR . " {$basic_sal}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Special Bonus/Additional Salary</td><td>" . CUR . " {$bonus}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Bonus(Annual Payments)</td><td>" . CUR . " {$annual}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Commission</td><td>" . CUR . " {$commission}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Travel Allowance</td><td>" . CUR . " {$all_travel}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Pension: Company Contribution</td><td>" . CUR . " {$comp_pension}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Pension: Employee Deduction</td><td>" . CUR . " {$emp_pension}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Provident Fund: Company Contribution</td><td>" . CUR . " {$comp_provident}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Provident Fund: Employee Deduction</td><td>" . CUR . " {$emp_provident}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>UIF: Company Contribution</td><td>" . CUR . " {$comp_uif}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>UIF: Employee Deduction</td><td>" . CUR . " {$emp_uif}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Retirement Annuity: Company Contribution</td><td>" . CUR . " {$comp_ret}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Retirement Annuity: Employee Deduction</td><td>" . CUR . " {$emp_ret}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Medical Aid: Company Contribution</td><td>" . CUR . " {$comp_medical}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Medical Aid: Employee Deduction</td><td>" . CUR . " {$emp_medical}</td></tr>\r\n\t\t\t<!--\r\n\t\t\t<tr class='" . bg_class() . "'><td>Other: Company Contribution</td><td>" . CUR . " {$comp_other}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Other: Employee Deduction</td><td>" . CUR . " {$emp_other}</td></tr>\r\n\t\t\t//-->\r\n\t\t\t<tr class='" . bg_class() . "'><td>Overtime</td><td>" . CUR . " {$overamt}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Medical Fringe Benefit</td><td>" . CUR . " {$fringe_medical}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Motorcar 1 Fringe Benefit</td><td>" . CUR . " {$fringe_car1}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Motorcar 1 Contribution for Use</td><td>" . CUR . " {$myEmp['fringe_car1_contrib']}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Motorcar 2 Fringe Benefit</td><td>" . CUR . " {$fringe_car2}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Motorcar 2 Contribution for Use</td><td>" . CUR . " {$myEmp['fringe_car2_contrib']}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Loan Interest Fringe Benefit</td><td>" . CUR . " {$fringe_loan}</td></tr>\r\n\t\t\t{$fringes_desc}\r\n\t\t\t{$all_before}\r\n\t\t\t{$de_before}\r\n\t\t\t<tr><th colspan='2'>Gross Salary</th></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Gross Salary</td><td>" . CUR . " {$grossal}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>SITE/PAYE</td><td>" . CUR . " {$paye}</td></tr>\r\n\t\t\t<tr><th colspan='2'>Loans</th></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Loan Instalment</td><td>" . CUR . " {$loaninstall}</td></tr>\r\n\t\t\t{$all_after}\r\n\t\t\t{$de_after}\r\n\t\t\t<tr><th colspan='2'>Nett Pay</th></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Nett Pay + Reimbursements</td><td>" . CUR . " {$nettpay}</td></tr>\r\n\t\t\t<tr class='" . bg_class() . "'><td>Amount Paid now</td><td><input type='text' size='10' name='paidamount' value='0'></td></tr>\r\n\t\t\t{$paydetails}\r\n\t\t\t<tr class='" . bg_class() . "'><td>Date</td><td>{$date}</td></tr>\r\n\t\t\t{$row}\r\n\t\t\t{$rt}\r\n\t\t\t<tr><td><br></td></tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td><input type='submit' name='back' value='&laquo; Correction'></td>\r\n\t\t\t\t<td align='right'><input type='submit' value='Write &raquo;'></td>\r\n\t\t\t</tr>\r\n\t\t</form>\r\n\t\t</table>\r\n\t\t<p>\r\n\t\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Quick Links</th>\r\n\t\t\t</tr>\r\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t<tr bgcolor='#88BBFF'>\r\n\t\t\t\t<td><a href='../main.php'>Main Menu</a></td>\r\n\t\t\t</tr>\r\n        </table>";
    return $confirm;
}
function write_req($_POST)
{
    global $_SESSION;
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    $user = $_SESSION["USER_NAME"];
    # validate input
    require_lib("validate");
    $v = new validate();
    if (!isset($to)) {
        $v->addError("", "No user specified");
    } else {
        foreach ($to as $arr => $arrval) {
            $v->isOk($arrval, "string", 1, 200, "Invalid recipient: {$arrval}");
        }
    }
    $v->isOk($des, "string", 1, 200, "Invalid description.");
    $v->isOk($user, "string", 1, 200, "Invalid user.");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class=err>" . $e["msg"];
        }
        return "{$confirmCust}</li></li>" . get_req();
    }
    $id += 0;
    $date = date("Y-m-d");
    $time = date("H:i:s");
    db_conn('cubit');
    if (in_array("_ALL_", $to)) {
        $to = "";
        $rslt = db_exec("SELECT username FROM users");
        // if users found
        if (pg_num_rows($rslt) > 0) {
            while ($row = pg_fetch_array($rslt)) {
                $to[] = $row["username"];
            }
        }
    }
    # write to db
    // create the list of users the messages should get sent to
    $msg_results = "";
    foreach ($to as $arr => $arrval) {
        db_conn('cubit');
        $Sql = "INSERT INTO req (sender, recipient, message, timesent, viewed)\r\n\t\t\tVALUES ('{$user}','{$arrval}','{$des}',CURRENT_TIMESTAMP, 0)";
        $Rslt = db_exec($Sql) or errDie("Unable to add to database.", SELF);
        if (pg_cmdtuples($Rslt) < 1) {
            return "Unable to access database.";
        } else {
            // if it isn't noticed that person has new messages, notify him
            $rslt = db_exec("SELECT * from req_new WHERE for_user='******' ");
            if (pg_num_rows($rslt) == 0) {
                db_exec("INSERT INTO req_new VALUES('{$arrval}')");
            }
            $msg_results .= "<tr class=datacell><td>Your message has been sent to {$arrval}</td></tr>";
        }
        db_conn('crm');
        $Sl = "INSERT INTO token_actions (token,action,donedate,donetime,doneby,donebyid)\r\n\t\tVALUES ('{$id}','Sent message to {$arrval}','{$date}','{$time}','" . USER_NAME . "','" . USER_ID . "')";
        $Ry = db_exec($Sl) or errDie("Unable to insert query action.");
    }
    $OUTPUT .= "<script> window.opener.parent.mainframe.location.reload(); window.close(); </script>";
    return $OUTPUT;
    $write_req = "\r\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\r\n\t<tr><th>Message proccessed</th></tr>\r\n\t{$msg_results}\r\n\t</table>";
    return $write_req;
}
function writeLoan($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    $v->isOk($loanamt, "float", 1, 10, "Invalid loan amount.");
    $v->isOk($loanint, "float", 1, 5, "Invalid loan interest.");
    $v->isOk($loanperiod, "num", 1, 3, "Invalid payback period.");
    $v->isOk($loaninstall, "float", 1, 10, "Invalid monthly installment.");
    $v->isOk($fringebenefit, "float", 1, 10, "Invalid fringe benefit amount.");
    $v->isOk($lday, "num", 1, 2, "Invalid day.");
    $v->isOk($lmonth, "num", 1, 2, "Invalid month.");
    $v->isOk($lyear, "num", 4, 4, "Invalid year.");
    $v->isOk($accid, "num", 1, 9, "Invalid bank account selected.");
    $v->isOk($account, "num", 1, 9, "Invalid contra account selected.");
    $v->isOk($loan_account, "num", 1, 9, "Invalid loan account selected.");
    $v->isOk($loan_type, "num", 1, 9, "Invalid loan type selected.");
    if (!checkdate($lmonth, $lday, $lyear)) {
        $v->addError("", "Invalid date.");
    }
    if ($account > 0 && isb($account) || isb($loan_account)) {
        $v->addError("", "Main accounts blocked. Please select sub accounts.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return enterLoan($confirmCust);
    }
    # get employee details
    db_connect();
    $sql = "SELECT * FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "'";
    $empRslt = db_exec($sql) or errDie("Unable to select employees from database.");
    if (pg_numrows($empRslt) < 1) {
        return "Invalid employee ID.";
    }
    $myEmp = pg_fetch_array($empRslt);
    # check for previous loan
    $sql = "SELECT empnum FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "' AND gotloan='t'::bool";
    $chkRslt = db_exec($sql) or errDie("Unable to check existing loans for employee.");
    if (pg_numrows($chkRslt) > 0) {
        return "<li class='err'>Loan already exists for employee number: {$myEmp['enum']}.</li>";
    }
    if ($accid > 0) {
        $bankacc = getbankaccid($accid);
    }
    # Debit salaries control acc and credit Bank acc
    $date = date("Y-m-d");
    $ldate = mkdate($lyear, $lmonth, $lday);
    $refnum = getrefnum();
    if ($account > 0) {
        $bankacc = $account;
    }
    //	writetrans($loan_account, $bankacc, $date, $refnum, $loanamt, "Loan granted to employee $myEmp[fnames] $myEmp[sname].");
    if ($accid > 0) {
        # issue bank record
        //		banktrans($accid, "withdrawal", date("d-m-Y"), "$myEmp[fnames] $myEmp[sname]", "Loan granted to employee $myEmp[fnames] $myEmp[sname].", 0, $loanamt, $loan_account);
    }
    $totamount = sprint($loanperiod * $loaninstall);
    $loanint_amt = $totamount - $loanamt;
    # connect to db
    db_connect();
    $ldate = "{$lyear}-{$lmonth}-{$lday}";
    $insert_sql = "\n\t\tINSERT INTO loan_requests (\n\t\t\tempnum, loanamt, loaninstall, loanint, loanperiod, loandate, \n\t\t\tloan_type, div, loan_account, bankacc, date, totamount, \n\t\t\tloanint_amt, fringebenefit, ldate, account, accid\n\t\t) VALUES (\n\t\t\t'{$empnum}', '{$loanamt}', '{$loaninstall}', '{$loanint}', '{$loanperiod}', '{$ldate}', \n\t\t\t'{$loan_type}', '" . USER_DIV . "', '{$loan_account}', '{$bankacc}', '{$date}', '{$totamount}', \n\t\t\t'{$loanint_amt}', '{$fringebenefit}', '{$ldate}', '{$account}', '{$accid}'\n\t\t)";
    $run_insert = db_exec($insert_sql) or errDie("Unable to add loan application request.");
    // 	pglib_transaction("BEGIN");
    //
    // 	$sql = "INSERT INTO emp_loanarchive (empnum, loanamt, loaninstall, loanint, loanperiod,loandate, loan_type, div)
    // 			VALUES('$empnum', '$totamount', '$loaninstall', '$loanint', '$loanperiod', CURRENT_DATE, '$loan_type', '".USER_DIV."')";
    // 	$rslt = db_exec($sql) or errDie("Unable to pre archive loan.");
    //
    // 	$loanid = pglib_lastid('emp_loanarchive', 'id');
    //
    // 	# write to db
    // 	$sql = "UPDATE employees
    // 			SET loanamt='$totamount', loanint='$loanint', loanint_amt='$loanint_amt',
    // 				loanint_unpaid='$loanint_amt', loanperiod='$loanperiod', loaninstall='$loaninstall',
    // 				gotloan='t'::bool, loanpayslip='$loanamt', loanfringe='$fringebenefit', loandate='$ldate',
    // 				expacc_loan='$loan_account', loanamt_tot='$totamount', loanid='$loanid'
    // 			WHERE empnum='$empnum' AND div = '".USER_DIV."'";
    // 	$loanRslt = db_exec ($sql) or errDie ("Unable to add loan to system.", SELF);
    //
    // 	if (pg_cmdtuples ($loanRslt) < 1) {
    // 		return "Unable to add loan to system.";
    // 	}
    //
    // 	pglib_transaction("COMMIT");
    $writeLoan = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Loan granted and added to system</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>New loan application has been successfully added to Cubit.\n\t\t\t\t<a href='../groupware/req_gen.php'>Send</a> an instant message.</td>\n\t\t\t</tr>\n\t\t</table><br>" . mkQuickLinks(ql("loan_apply.php", "Add Loan Application"), ql("loan_apply_view.php", "View Loan Applications"), ql("../admin-employee-add.php", "Add Employee"), ql("../admin-employee-view.php", "View Employees"));
    return $writeLoan;
}