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($_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 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_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 writeEmp($_POST)
{
    $_POST = var_makesafe($_POST);
    global $_FILES;
    extract($_POST);
    if (isset($back)) {
        return enterEmp();
    }
    $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");
    $v->isOk($emp_group, "num", 1, 10, "Invalid Employee Group.");
    $v->isOK($person_nature, "string", 1, 1, "Invalid Nature Of Person Selection.");
    $v->isOK($medical_aid, "num", 1, 4, "Invalid Medical Aid Selected.");
    $v->isOK($medical_aid_number, "string", 0, 25, "Invalid Medical Aid Number.");
    if (strlen($idnum) >= 6) {
        $bd_year = substr($idnum, 0, 2);
        $bd_month = substr($idnum, 2, 2);
        $bd_day = substr($idnum, 4, 2);
        if (!(is_numeric($bd_year) && is_numeric($bd_month) && is_numeric($bd_day) && checkdate($bd_month, $bd_day, $bd_year))) {
            $v->addError("", "Invalid id num (BD).");
        }
    }
    if (isset($allowances)) {
        foreach ($allowances as $key => $value) {
            $v->isOk($allowances[$key], "float", 0, 20, "Invalid allowance amount " . ($key + 1) . ".");
        }
    }
    if (isset($deductid)) {
        foreach ($deductid as $key => $value) {
            $v->isOk($deductid[$key], "num", 1, 20, "Invalid deductions ID.");
        }
    }
    if (isset($deductions)) {
        foreach ($deductions as $key => $value) {
            $v->isOk($deductions[$key], "float", 0, 20, "Invalid deduction amount" . ($key + 1) . ".");
        }
    }
    if (isset($allowid)) {
        foreach ($allowid as $key => $value) {
            $v->isOk($allowid[$key], "num", 1, 20, "Invalid allowance ID.");
        }
    }
    if (isset($allowtax)) {
        foreach ($allowtax as $key => $value) {
            $v->isOk($allowtax[$key], "string", 2, 20, "Invalid allowance tax " . ($key + 1) . ".");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>{$e['msg']}</li>";
        }
        return enterEmp($confirmCust);
    }
    $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 = "\n\t\tINSERT INTO cubit.employees (\n\t\t\tsname, fnames, sex, marital, resident, hiredate, telno, email, basic_sal, saltyp, \n\t\t\thpweek, novert, hovert, payprd, payprd_day, paytype, bankname, bankcode, bankacctype, \n\t\t\tbankaccno, vaclea, siclea, stdlea, res1, res2, res3, res4, pos1, pos2, pcode, \n\t\t\tcontsname, contfnames, contres1, contres2, contres3, conttelno, div, idnum, \n\t\t\tpassportnum, taxref, enum, designation, balance, comp_pension, emp_pension, comp_ret, \n\t\t\temp_ret, comp_medical, emp_medical, emp_meddeps, sal_bonus, sal_bonus_month, basic_sal_annum, \n\t\t\tall_travel, comp_uif, comp_sdl, comp_other, comp_provident, emp_uif, emp_other, \n\t\t\temp_provident, expacc_provident, expacc_ret, expacc_pension, expacc_uif, expacc_medical, expacc_other, \n\t\t\texpacc_salwages, expacc_sdl, expacc_reimburs, department, occ_cat, occ_level, pos_filled, \n\t\t\ttemporary, termination_date, recruitment_from, employment_reason, union_name, union_mem_num, \n\t\t\tunion_pos, race, disabled_stat, fringe_car1, fringe_car1_contrib, fringe_car1_fuel, \n\t\t\tfringe_car1_service, fringe_car2, fringe_car2_contrib, fringe_car2_fuel, fringe_car2_service, \n\t\t\tprevemp_remun, prevemp_tax, cyear, emp_group, person_nature, medical_aid, medical_aid_number, \n\t\t\temp_usescales\n\t\t) VALUES (\n\t\t\t'{$sname}', '{$fnames}', '{$sex}', '{$marital}', '{$resident}', '{$hiredate}', '{$telno}', '{$email}', '{$basic_sal}', '{$saltyp}', \n\t\t\t'{$hpweek}', '{$novert}', '{$hovert}', '{$payprd}','{$payprd_day}', '{$paytype}', '{$bankname}', '{$bankcode}', '{$bankacctype}', \n\t\t\t'{$bankaccno}', '{$vaclea}', '{$siclea}', '{$stdlea}', '{$res1}', '{$res2}', '{$res3}', '{$res4}', '{$pos1}', '{$pos2}', '{$pcode}', \n\t\t\t'{$contsname}', '{$contfnames}', '{$contres1}', '{$contres2}', '{$contres3}', '{$conttelno}', '" . USER_DIV . "', '{$idnum}', \n\t\t\t'{$passportnum}', '{$taxref}', '{$empnum}', '{$designation}', 0, '{$comp_pension}', '{$emp_pension}', '{$comp_ret}', \n\t\t\t'{$emp_ret}','{$comp_medical}','{$emp_medical}','{$emp_meddeps}', '{$sal_bonus}', '{$sal_bonus_month}', '{$basic_sal_annum}', \n\t\t\t'{$all_travel}', '{$comp_uif}', '{$comp_sdl}', '{$comp_other}', '{$comp_provident}', '{$emp_uif}', '{$emp_other}', \n\t\t\t'{$emp_provident}', '{$expacc_provident}', '{$expacc_ret}', '{$expacc_pension}', '{$expacc_uif}', '{$expacc_medical}', '0', \n\t\t\t'{$expacc_salwages}', '{$expacc_sdl}', '{$expacc_reimburs}', '{$department}', '{$occ_cat}', '{$occ_level}', '{$pos_filled}', \n\t\t\t'{$temporary}', '{$termination_date}', '{$recruitment_from}', '{$employment_reason}', '{$union_name}', '{$union_mem_num}', \n\t\t\t'{$union_pos}', '{$race}', '{$disabled_stat}', '{$fringe_car1}', '{$fringe_car1_contrib}', '{$fringe_car1_fuel}', \n\t\t\t'{$fringe_car1_service}', '{$fringe_car2}', '{$fringe_car2_contrib}', '{$fringe_car2_fuel}', '{$fringe_car2_service}', \n\t\t\t'{$prevemp_remun}', '{$prevemp_tax}', '" . EMP_YEAR . "', '{$emp_group}', '{$person_nature}', '{$medical_aid}', '{$medical_aid_number}', \n\t\t\t'{$emp_usescales}'\n\t\t)";
    $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 = "\n\t\t\t\t\tINSERT INTO empdeduct (\n\t\t\t\t\t\tdedid, empnum, amount, employer_amount, employer_type, div, \n\t\t\t\t\t\ttype, accid\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$id}', '{$empnum}', '{$deductions[$i]}', '{$comp_deductions[$i]}', '{$deducttype[$i]}', '" . USER_DIV . "', \n\t\t\t\t\t\t'{$deducttype[$i]}', '{$deductaccid[$i]}'\n\t\t\t\t\t)";
            }
            $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 = "\n\t\t\t\t\tINSERT INTO empfringe (\n\t\t\t\t\t\tfringeid, empnum, amount, type, accid, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$id}', '{$empnum}', '{$fringebens[$i]}', '{$fringetype[$i]}', '{$fringeexpacc[$i]}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            }
            $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.</li>";
        }
        if (is_uploaded_file($_FILES["logo"]["tmp_name"])) {
            # Check file ext
            if (preg_match("/(image\\/jpeg|image\\/png|image\\/gif)/", $_FILES["logo"]["type"], $extension)) {
                $type = $_FILES["logo"]["type"];
                // open file in "read, binary" mode
                $img = "";
                $file = fopen($_FILES['logo']['tmp_name'], "rb");
                while (!feof($file)) {
                    // fread is binary safe
                    $img .= fread($file, 1024);
                }
                fclose($file);
                # base 64 encoding
                $img = base64_encode($img);
                db_connect();
                $Sl = "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);
        }
    }
    # Provide some info on status
    $writeEmp = "\n\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t<tr>\n\t\t\t\t<th>New employee added to database</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>New employee, {$fnames} {$sname}, successfully added to Cubit.</td>\n\t\t\t</tr>\n\t\t</table>" . mkQuickLinks(ql("admin-employee-view.php", "View Employees"));
    return $writeEmp;
}
function write($_POST)
{
    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 = $sord_year . "-" . $sord_month . "-" . $sord_day;
    if (!checkdate($sord_month, $sord_day, $sord_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    // check the sales order 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");
    }
    # 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, 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 : sales order number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $taxex = 0;
    $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 sales order items in Cubit.", SELF);
    /* -- 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, div, vatex\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}', '" . USER_DIV . "', '{$vate}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert sales order items to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = "&nbsp; | &nbsp;<input name='doneBtn' type='submit' value='Done'>\n\t\t\t&nbsp; | &nbsp;<input type='submit' name='donePrnt' value='Done, Print and make another'>";
        }
    } 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;*/
    # insert purchase to DB
    $sql = "\n\t\tUPDATE nons_invoices \n\t\tSET cusname = '{$cusname}', cusaddr = '{$cusaddr}', cusvatno = '{$cusvatno}', cusordno = '{$cusordno}', \n\t\t\tchrgvat = '{$chrgvat}', odate = '{$sdate}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', \n\t\t\tremarks = '{$remarks}' \n\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update sales order in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (isset($donePrnt)) {
        $OUTPUT = "\n\t\t\t<script>\n\t\t\t\tprinter('nons-sorder-print.php?invid={$invid}');\n\t\t\t\tmove('nons-sorder-new.php');\n\t\t\t</script>";
        return $OUTPUT;
    }
    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\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>New Non-Stock Sales Orders</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 Sales Orders for Customer <b>{$cusname}</b> has been recorded.</td>\n\t\t\t\t\t<td><a target='_blank' href='nons-sorder-print.php?invid={$invid}'>Print Order</a></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-sorder-view.php'>View Non-Stock Sales Orders</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;
    }
}