Example #1
0
function views()
{
    if (empty($_GET['view'])) {
        view_index();
        return;
    }
    switch ($_GET['view']) {
        case 'all':
            main_view('item.*, `condition`.c_description as descript', " inner join `condition` on code=i_state and type='S'", '', 'all');
            break;
        case 'sold':
            main_view('item.*, `condition`.c_description as descript', " inner join `condition` on code=i_state and type='S'", " i_state='D'", 'all');
            break;
        case 'sale':
            main_view('item.*, `condition`.c_description as descript', " inner join `condition` on code=i_state and type='S'", " i_state in('A','S')", 'all');
            break;
        case 'parted':
            main_view('item.*, `condition`.c_description as descript', " inner join `condition` on code=i_state and type='S'", " i_state in('P')", 'all');
            break;
        case 'unsold':
            main_view('item.*, `condition`.c_description as descript', " inner join `condition` on code=i_state and type='S'", " i_state in('N')", 'all');
            break;
        case 'nonsel':
            main_view('item.*, `condition`.c_description as descript', " inner join `condition` on code=i_state and type='S'", " i_state in('I')", 'all');
            break;
        case 'totals':
            math_view('total');
            break;
        case 'detail':
            details($_POST['item']);
            break;
    }
}
Example #2
0
function supporter_details($errorMessage = "")
{
    global $wpdb;
    $table_name = $wpdb->prefix . "supporters";
    $type = $_GET['page'];
    $sql_query = "SELECT * FROM {$table_name} WHERE type='" . $type . "' ORDER BY position;";
    $supporters = $wpdb->get_results($sql_query);
    echo "<h2>Supporter</h2>";
    echo '<div class="leftDiv">';
    add_form(count($supporters), $errorMessage);
    echo '</div>';
    echo '<div class="rightDiv">';
    details($supporters, $type);
    echo "</div>";
    echo '<div class="clearfix"></div>';
}
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid purchase number.");
    if (!isset($supid) && !isset($deptid)) {
        $v->isOk($supacc, "num", 1, 10, "Invalid Supplier Account number.");
    }
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # 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>");
            if ($qty > $qts[$keys]) {
                $v->isOk($qty, "num", 0, 0, "Error : Quantity for product number : <b>" . ($keys + 1) . "</b> is more that Qty Purchased");
            }
            $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>");
            }
        }
    }
    # 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);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($pur['pdate']) >= strtotime($blocked_date_from) and strtotime($pur['pdate']) <= 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>";
    }
    $pur['pdate'] = $p_year . "-" . $p_month . "-" . $p_day;
    # Get selected supplier info
    db_connect();
    if (isset($supid)) {
        $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql) or errDie("Unable to get supplier");
        if (pg_numrows($supRslt) < 1) {
            $error = "<li class='err'> Supplier not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $sup = pg_fetch_array($supRslt);
            $pur['supplier'] = $sup['supname'];
            $pur['supaddr'] = $sup['supaddr'];
            # Get department info
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$sup['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $supacc = $dept['credacc'];
        }
    } elseif (isset($deptid)) {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Department not Found.";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = $dept['pca'];
        }
    }
    # check if purchase has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    # Insert purchase to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $refnum = getrefnum();
    /*refnum*/
    db_connect();
    if (isset($qtys)) {
        # amount of stock in
        $totstkamt = array();
        $resub = 0;
        # Get subtotal
        foreach ($qtys as $keys => $value) {
            # Skip zeros
            if ($qtys[$keys] < 1) {
                continue;
            }
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        }
        $SUBTOTAL = array_sum($amt);
        $revat = 0;
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            $sql = "SELECT * FROM nons_pur_items WHERE cod = '{$cod[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # Calculate cost amount bought
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
            /* delivery charge */
            # Calculate percentage from subtotal
            $perc[$keys] = $amt[$keys] / $SUBTOTAL * 100;
            # Get percentage from shipping charges
            $shipc[$keys] = $perc[$keys] / 100 * $shipchrg;
            # add delivery charges
            $amt[$keys] += $shipc[$keys];
            /* end delivery charge */
            # the subtotal + delivery charges
            $resub += $amt[$keys];
            # calculate vat
            $svat[$keys] = svat($amt[$keys], $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'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Vat for Non-Stock Purchase No. {$pur['purnum']}", -$amt[$keys], -$svat[$keys]);
            # received vat
            $revat += $svat[$keys];
            # make amount vat free
            if ($pur['vatinc'] == "yes") {
                $amt[$keys] = $amt[$keys] - $svat[$keys];
            }
            # Update Order items
            $sql = "UPDATE nons_pur_items SET rqty = (rqty + '{$qtys[$keys]}') WHERE cod = '{$cod[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            /* ?: refer to :Code Insert:
            			# keep records for transactions
            			if(isset($totstkamt[$stkacc[$keys]])){
            				$totstkamt[$stkacc[$keys]] += $amt[$keys];
            			}else{
            				$totstkamt[$stkacc[$keys]] = $amt[$keys];
            			}
            			*/
            # check if there are any outstanding items
            $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            # if none the set to received
            if (pg_numrows($stkdRslt) < 1) {
                # update surch_int(received = 'y')
                $sql = "UPDATE nons_purchases SET received = 'y', supplier = '{$pur['supplier']}', supaddr = '{$pur['supaddr']}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF);
            }
        }
    }
    # Update purchase on the DB
    if ($pur['part'] == 'y') {
        # Update purchase on the DB
        $sql = "UPDATE nons_purchases SET shipchrg = (shipchrg + '{$shipchrg}'), refno = '{$refno}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    } else {
        # Update purchase on the DB
        $sql = "UPDATE nons_purchases SET shipchrg = '{$shipchrg}', refno = '{$refno}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    }
    /* Transactions */
    /* - Start Hooks - */
    /* - End Hooks - */
    $detadd = "";
    if (isset($supid)) {
        $detadd = " from Supplier {$sup['supname']}";
    }
    $sdate = $pur['pdate'];
    /* ?:refer to :Code Insert:
    		# record transaction  from data
    		foreach($totstkamt as $stkacc => $wamt){
    			# Debit Stock and Credit Suppliers control
    			writetrans($stkacc, $supacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. $pur[purnum] Received $detadd.");
    			pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. $pur[purnum] Received $detadd.", $wamt, "Cash Purchase");
    		}*/
    # Calc Vat amount on (subtot + delchrg)
    $vatamt = $revat;
    # Add vat if not included
    if ($pur['vatinc'] == 'no') {
        $retot = $resub + $vatamt;
    } elseif ($pur['vatinc'] == "novat") {
        $retot = $resub;
        $vatamt = 0;
    } else {
        $retot = $resub;
    }
    # get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    $tot_post = 0;
    if ($vatamt != 0) {
        $tot_post += $vatamt;
        # Debit bank and credit the account involved
        writetrans($vatacc, $supacc, $pdate, $refnum, $vatamt, "Non-Stock Purchase Vat paid on Non-Stock Purchase No. {$pur['purnum']} {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $vatamt, "Cash Purchase Vat");
        # Record the payment on the statement
        db_connect();
        $sdate = $pur['pdate'];
    }
    if (isset($supid)) {
        $DAte = $pur['pdate'];
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$retot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$sup['supid']}','{$DAte}', '{$dept['credacc']}', '{$retot}','Non-Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}','" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        suppledger($sup['supid'], $wh['stkacc'], $DAte, $pur['purid'], "Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'c');
        db_connect();
        # update the supplier age analysis (make balance less)
        /* Make transaction record for age analysis */
        $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, div) VALUES('{$sup['supid']}', '{$pur['purnum']}', '{$DAte}', '{$retot}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    /* End Transactions */
    # commit updating
    // pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    /* Update items found in ther linked purchase */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    db_conn($pur['spurprd']);
    $stab = $pur['spurtype'] == "int" ? "purch_int" : "purchases";
    $itab = $pur['spurtype'] == "int" ? "purint_items" : "pur_items";
    # Get purchase info
    $sql = "SELECT * FROM {$stab} 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);
    $purs = explode(",", $pur['purs']);
    $TSUB = 0;
    foreach ($purs as $purID) {
        $purID += 0;
        db_connect();
        $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $p = pg_fetch_array($srchRslt);
            $TSUB += $p['subtot'];
            $Sl = "SELECT sum(unitcost) -sum(svat) as non FROM pur_items WHERE purid='{$p['purid']}' AND stkid=0";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $pi = pg_fetch_array($Ri);
            $pi = $pi['non'];
        }
        $sql = "SELECT * FROM movpurch WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $res = pg_fetch_array($srchRslt);
            db_conn($res['prd']);
            $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
            $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
            if (pg_numrows($srchRslt) > 0) {
                $p = pg_fetch_array($srchRslt);
                $TSUB += $p['subtot'];
                $Sl = "SELECT sum(unitcost)-sum(svat) as non FROM pur_items WHERE purid='{$p['purid']}' AND stkid=0";
                $Ri = db_exec($Sl) or errDie("Unable to get data.");
                $pi = pg_fetch_array($Ri);
                $pi = $pi['non'];
            } else {
                db_conn($res['prd']);
                $sql = "SELECT * FROM purch_int WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
                $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
                if (pg_numrows($srchRslt) > 0) {
                    $p = pg_fetch_array($srchRslt);
                    $TSUB += $p['subtot'];
                    // 					$Sl="SELECT sum(unitcost)-sum(svat) as non FROM purint_items WHERE purid='$p[purid]' AND stkid=0";
                    //
                    // 					$Ri=db_exec($Sl) or errDie("Unable to get data.");
                    // 					$pi=pg_fetch_array($Ri);
                    // 					$pi=$pi['non'];
                    $pi = 0;
                }
            }
        }
        if (!isset($pi)) {
            $pi = 0;
        }
        $TSUB -= $pi;
    }
    $purs = explode(",", $pur['purs']);
    foreach ($purs as $purID) {
        $itab = "pur_items";
        $purID += 0;
        //print $purID;
        db_connect();
        $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $pur['spurprd'] = "cubit";
        }
        $sql = "SELECT * FROM movpurch WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $res = pg_fetch_array($srchRslt);
            db_conn($res['prd']);
            $pur['spurprd'] = $res['prd'];
        }
        db_conn($pur['spurprd']);
        $test = $pur['spurprd'];
        $test += 0;
        if ($test != 0) {
            $s = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
            $q = db_exec($s) or errDie("Unable to retrieve purchases from database.");
            if (pg_num_rows($q) > 0) {
                $p = pg_fetch_array($q);
                $purID = $p['purid'];
            } else {
                $s = "SELECT * FROM purch_int WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
                $q = db_exec($s) or errDie("Unable to retrieve purchases from database.");
                if (pg_num_rows($q) > 0) {
                    $p = pg_fetch_array($q);
                    $purID = $p['purid'];
                    $itab = "purint_items";
                }
            }
        }
        # Get selected stock
        $sql = "SELECT * FROM {$itab} WHERE purid = '{$purID}' AND div = '" . USER_DIV . "' AND stkid!=0";
        $sstkdRslt = db_exec($sql);
        while ($sstk = pg_fetch_array($sstkdRslt)) {
            if ($pur['spurtype'] == "int") {
                $csamt = sprint($sstk['amt'] / $TSUB * ($retot - $vatamt));
            } else {
                if ($spur['vatinc'] == "yes") {
                    $csamt = sprint(($sstk['amt'] - $sstk['svat']) / $TSUB * ($retot - $vatamt));
                } else {
                    $csamt = sprint($sstk['amt'] / $TSUB * ($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($wh['stkacc'], $supacc, $pdate, $refnum, $csamt, "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.");
            /* End code insert */
            db_connect();
            if ($stkt['units'] != 0) {
                $sql = "UPDATE stock SET csamt = (csamt + '{$csamt}'), csprice = (csamt/units) WHERE 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'], 'dt', $sdate, 0, $csamt, "Cost Increased with Non Stock Purchase No. {$pur['purnum']}");
            # 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);
        }
    }
    //exit;
    /*
    		db_conn($pur['spurprd']);
    		# Get selected stock
    		$sql = "SELECT * FROM $itab WHERE purid = '$spur[purid]' AND div = '".USER_DIV."' AND stkid!=0";
    		$sstkdRslt = db_exec($sql);
    		while($sstk = pg_fetch_array($sstkdRslt)){
    			if($pur['spurtype'] == "int"){
    				$csamt = sprint(($sstk['amt']/$TSUB) * ($retot - $vatamt));
    			}else{
    				if($spur['vatinc'] == "yes"){
    					$csamt = sprint((($sstk['amt'] - $sstk['svat'])/$TSUB) * ($retot - $vatamt));
    				}else{
    					$csamt = sprint((($sstk['amt'])/$TSUB) * ($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($wh['stkacc'], $supacc, date("d-m-Y"), $refnum, $csamt, "Non-Stock Purchase No. $pur[purnum] Received $detadd.");
    			/* End code insert
    
    			db_connect();
    			if($stkt['units'] <> 0){
    				$sql = "UPDATE stock SET csamt = (csamt + '$csamt'), csprice = (csamt/units) WHERE 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'], 'dt', $sdate, 0, $csamt, "Cost Increased with Non Stock Purchase No. $pur[purnum]");
    
    			# 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);
    		}
    */
    $diff = sprint($retot - $tot_post);
    if ($diff > 0) {
        writetrans($cvacc, $supacc, $sdate, $refnum, $diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']}");
    } elseif ($diff < 0) {
        writetrans($supacc, $cvacc, $sdate, $refnum, -$diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']}");
    }
    /* End Update items found in ther linked purchase */
    /* Start moving if purchase received */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        if (isset($supid)) {
            $ctyp = "sup";
            $typeid = $supid;
        } elseif (isset($deptid)) {
            $ctyp = "led";
            $typeid = $deptid;
        } else {
            $ctyp = "ot";
            $typeid = 0;
        }
        # copy purchase
        db_conn($pur['prd']);
        $pur['spurprd'] += 0;
        $pur['spurnum'] += 0;
        $sql = "INSERT INTO nons_purchases(purid, deptid, supplier, supaddr, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, remarks, refno, received, done, div, purnum,ctyp,typeid,spurprd,spurnum)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}','{$ctyp}','{$typeid}','{$pur['spurprd']}','{$pur['spurnum']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Purchase to Cubit.", SELF);
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert purchase items
            db_conn($pur['prd']);
            $sql = "INSERT INTO nons_pur_items(purid, cod, des, qty, unitcost, amt, ddate, div,svat) VALUES('{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['ddate']}', '" . USER_DIV . "','{$stktc['svat']}')";
            $rslt = db_exec($sql) or errDie("Unable to insert purchase items to Cubit.", SELF);
        }
        db_connect();
        # Remove the purchase from running DB
        $sql = "DELETE FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Remove those purchase items from running DB
        $sql = "DELETE FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving purchase received */
    $cc = "<script> CostCenter('ct', 'Non-Stock Purchase', '{$pdate}', 'Non Stock Purchase No.{$pur['purnum']}', '" . ($retot - $vatamt) . "', ''); </script>";
    // Final Layout
    $write = "\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Non-Stock Purchase received</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Non-Stock Purchase receipt has been recorded.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<p>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='nons-purchase-view.php'>View purchases</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t</table>";
    return $write;
}
#
# get settings
require "settings.php";
require "core-settings.php";
# decide what to do
if (isset($_POST["key"])) {
    switch ($_POST["key"]) {
        case "confirm":
            $OUTPUT = confirm($_POST);
            break;
        case "write":
            $OUTPUT = write($_POST);
            break;
        case "details":
            if (isset($_POST['details'])) {
                $OUTPUT = details($_POST);
            } else {
                $OUTPUT = details2($_POST);
            }
            break;
        default:
            if (isset($_GET['cusnum'])) {
                $OUTPUT = slctacc($_GET);
            } else {
                $OUTPUT = "<li> - Invalid use of module";
            }
    }
} else {
    if (isset($_GET['cusnum'])) {
        $OUTPUT = slctacc($_GET);
    } else {
function confirm($_POST)
{
    $showvat = TRUE;
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid remarks.");
    $sdate = $ninv_year . "-" . $ninv_month . "-" . $ninv_day;
    if (!checkdate($ninv_month, $ninv_day, $ninv_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    foreach ($ids as $key => $id) {
        $v->isOk($id, "num", 1, 20, "Invalid Item number.");
        $v->isOk($qtys[$key], "float", 1, 20, "Invalid Item quantity.");
        if ($qtys[$key] > $oqtys[$key]) {
            $v->isOk("##", "num", 1, 1, "Error: Item quantity cannot be more than invoiced quantity.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>{$e['msg']}</li>";
        }
        $confirm = "{$err}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return details($_POST, $err);
        return $confirm;
    }
    # Products layout
    $products = "\r\n\t\t<table " . TMPL_tblDflts . " width='100%'>\r\n\t\t\t<tr>\r\n\t\t\t\t<th width='5%'>#</th>\r\n\t\t\t\t<th width='40%'>DESCRIPTION</th>\r\n\t\t\t\t<th width='10%'>QTY</th>\r\n\t\t\t\t<th width='10%'>UNIT PRICE</th>\r\n\t\t\t\t<th width='10%'>AMOUNT</th>\r\n\t\t\t\t<th width='20%'>ACCOUNT</th>\r\n\t\t\t<tr>";
    // Retrieve invoice items
    db_connect();
    $sql = "SELECT *,(qty - rqty) as qty FROM nons_inv_items WHERE invid='{$invid}' AND div='" . USER_DIV . "'";
    $item_rslt = db_exec($sql);
    $i = 0;
    while ($item_data = pg_fetch_array($item_rslt)) {
        ++$i;
        $accRs = get("core", "accname, topacc, accnum", "accounts", "accid", $item_data['accid']);
        $acc = pg_fetch_array($accRs);
        // 					<tr class='".bg_class()."'>
        // 						<td align=center>$i<input type='hidden' name=ids[] value='$stkd[id]'></td>
        // 						<td>$stkd[description]</td>
        // 						<td><input type='hidden' name='qtys[]' value='$qtys[$key]'>$qtys[$key]</td>
        // 						<td nowrap>".CUR." $stkd[unitcost]</td>
        // 						<td nowrap><input type='hidden' name='amts[]' value='$amt[$key]'>".CUR." $amt[$key]</td>
        // 						<td>$acc[topacc]/$acc[accnum] - $acc[accname]</td>
        // 					</tr>";
        $products .= "\r\n\t\t\t<input type='hidden' name='ids[]' value='{$item_data['id']}' />\r\n\t\t\t<input type='hidden' name='qtys[]' value='{$item_data['qty']}' />\r\n\t\t\t<input type='hidden' name='amts[]' value='{$item_data['amt']}' />\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td align='center'>{$i}</td>\r\n\t\t\t\t<td>{$item_data['description']}</td>\r\n\t\t\t\t<td>{$item_data['qty']}</td>\r\n\t\t\t\t<td nowrap>" . CUR . " {$item_data['unitcost']}</td>\r\n\t\t\t\t<td nowrap>" . CUR . " {$item_data['amt']}</td>\r\n\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\r\n\t\t\t</tr>";
    }
    $products .= "</table>";
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    $sql = "SELECT * FROM cubit.nons_invoices WHERE invid='{$invid}'";
    $inv_rslt = db_exec($sql) or errDie("Unable to retrieve non stock invoice.");
    $inv = pg_fetch_array($inv_rslt);
    /* -- Final Layout -- */
    $details = "\r\n\t\t<center>\r\n\t\t<h3>Non-Stock Credit Note</h3>\r\n\t\t<form action='" . SELF . "' method='POST' name='form'>\r\n\t\t\t<input type='hidden' name='key' value='write'>\r\n\t\t\t<input type='hidden' name='invid' value={$invid}>\r\n\t\t\t<input type='hidden' name='remarks' value='{$remarks}'>\r\n\t\t<table " . TMPL_tblDflts . " width='95%'>\r\n\t\t\t<tr>\r\n\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th colspan='2'> Customer Details </th>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Customer</td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$inv['cusname']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Customer Address</td>\r\n\t\t\t\t\t\t\t<td valign='center'><pre>{$inv['cusaddr']}</pre></td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Customer VAT Number</td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$inv['cusvatno']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t\t<td valign='top' align='right'>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th colspan='2'> Non-Stock Invoice Details </th>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Non-Stock Invoice No.</td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$inv['invnum']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Date</td>\r\n\t\t\t\t\t\t\t<td valign='center'>\r\n\t\t\t\t\t\t\t\t<input type='hidden' size='2' name='ninv_day' maxlength='2' value='{$ninv_day}'>{$ninv_day}-\r\n\t\t\t\t\t\t\t\t<input type='hidden' size='2' name='ninv_month' maxlength='2' value='{$ninv_month}'>{$ninv_month}-\r\n\t\t\t\t\t\t\t\t<input type='hidden' size='4' name='ninv_year' maxlength='4' value='{$ninv_year}'>{$ninv_year}\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>VAT Inclusive</td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$inv['chrgvat']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</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 colspan='2'>{$products}</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th width='40%'>Quick Links</th>\r\n\t\t\t\t\t\t\t<th width='45%'>Remarks</th>\r\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='15%'><br></td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='nons-invoice-new.php'>New Non-Stock Invoices</a></td>\r\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'>" . nl2br($remarks) . "</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td><a href='nons-invoice-view.php'>View Non-Stock Invoices</a></td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t\t<td align='right'>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Trade Discount</td>\r\n\t\t\t\t\t\t\t<td align='right' nowrap>\r\n\t\t\t\t\t\t\t\t<input type='hidden' name='discount' value='{$inv['discount']}' />\r\n\t\t\t\t\t\t\t\t" . CUR . " {$inv['discount']}\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Subtotal</td>\r\n\t\t\t\t\t\t\t<td align='right' nowrap><input type='hidden' name='subtot' value='{$inv['subtot']}'>" . CUR . " {$inv['subtot']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>VAT {$vat14}</td>\r\n\t\t\t\t\t\t\t<td align='right' nowrap><input type='hidden' name='vat' value='{$inv['vat']}'>" . CUR . " {$inv['vat']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\r\n\t\t\t\t\t\t\t<td align='right' nowrap><input type='hidden' name='total' value='{$inv['total']}'>" . CUR . " {$inv['total']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\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</table>\r\n\t\t</form>\r\n\t\t</center>";
    return $details;
}
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 confirm($stkid)
{
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($stkid, "num", 1, 50, "Invalid stock id.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li>";
        }
        return $confirm;
    }
    # Select Stock
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    # get stock vars
    extract($stk);
    if ($ordered > 0) {
        # get all done allocated invoices
        db_connect();
        $sql = "SELECT purid FROM purchases WHERE received = 'n' AND subtot > 0 AND div = '" . USER_DIV . "'";
        $purRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
        if (pg_numrows($purRslt) > 0) {
            $deliveries = "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='2' align='center'><h3>Expected Deliveries</h3></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t<th>Number</th>\n\t\t\t\t\t</tr>";
            $i = 0;
            while ($pur = pg_fetch_array($purRslt)) {
                # get all items that are outstanding
                $sql = "SELECT ddate, qty FROM pur_items WHERE stkid = '{$stkid}' AND purid = '{$pur['purid']}' AND qty > 0 AND div = '" . USER_DIV . "'";
                $itRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
                while ($it = pg_fetch_array($itRslt)) {
                    # delivery date
                    $ddate = explode("-", $it['ddate']);
                    $ddate = $ddate[2] . "-" . $ddate[1] . "-" . $ddate[0];
                    $deliveries .= "\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>{$ddate}</td>\n\t\t\t\t\t\t\t\t\t\t<td>" . sprint3($it['qty']) . " x {$suom}</td>\n\t\t\t\t\t\t\t\t\t</tr>";
                }
            }
        } else {
            $deliveries = "";
        }
        # get all done allocated invoices
        db_connect();
        $sql = "SELECT purid FROM purch_int WHERE received = 'n' AND subtot > 0 AND div = '" . USER_DIV . "'";
        $ipurRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
        if (pg_numrows($ipurRslt) > 0) {
            $intdeliveries = "\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td colspan='2' align='center'><h3>Expected International Deliveries</h3></td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t\t\t\t<th>Number</th>\n\t\t\t\t\t\t\t\t</tr>";
            $i = 0;
            while ($pur = pg_fetch_array($ipurRslt)) {
                # get all items that are outstanding
                $sql = "SELECT ddate, qty FROM purint_items WHERE stkid = '{$stkid}' AND purid = '{$pur['purid']}' AND qty > 0 AND div = '" . USER_DIV . "'";
                $itRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
                while ($it = pg_fetch_array($itRslt)) {
                    # delivery date
                    $ddate = explode("-", $it['ddate']);
                    $ddate = $ddate[2] . "-" . $ddate[1] . "-" . $ddate[0];
                    $intdeliveries .= "\n\t\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t\t<td>{$ddate}</td>\n\t\t\t\t\t\t\t\t\t\t\t<td>" . sprint3($it['qty']) . " x {$suom}</td>\n\t\t\t\t\t\t\t\t\t\t</tr>";
                }
            }
        } else {
            $intdeliveries = "";
        }
    } else {
        $intdeliveries = "";
        $deliveries = "";
    }
    if ($units >= 0 && $alloc >= 0) {
        $avstk = $units - $alloc;
    } else {
        $avstk = $units + $alloc;
    }
    // Layout
    $confirm = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h3>Stock Details</h3>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='350'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th width='40%'>Field</th>\n\t\t\t\t\t\t\t<th width='60%'>Value</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>Category</td>\n\t\t\t\t\t\t\t<td>{$catname}</td>\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>Stock code</td>\n\t\t\t\t\t\t\t<td>{$stkcod}</td>\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>Stock description</td>\n\t\t\t\t\t\t\t<td>" . nl2br($stkdes) . "</pre></td>\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>On Hand</td>\n\t\t\t\t\t\t\t<td>" . sprint3($units) . "</td>\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>Allocated</td>\n\t\t\t\t\t\t\t<td>" . sprint3($alloc) . "</td>\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>Available</td>\n\t\t\t\t\t\t\t<td>" . sprint3($avstk) . "</td>\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>On Order</td>\n\t\t\t\t\t\t\t<td>" . sprint3($ordered) . "</td>\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>Location</td>\n\t\t\t\t\t\t\t<td>Shelf : {$shelf} - Row : {$row}</td>\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>Minimum level</td>\n\t\t\t\t\t\t\t<td>{$minlvl}</td>\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>Maximum level</td>\n\t\t\t\t\t\t\t<td>{$maxlvl}</td>\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>Selling price per selling unit</td>\n\t\t\t\t\t\t\t<td>" . CUR . " " . sprint($selamt) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t{$deliveries}\n\t\t\t\t\t\t<tr><td><br><br></td><tr>\n\t\t\t\t\t\t{$intdeliveries}\n\t\t\t\t\t</table>";
    # Select Stock
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    # get all done allocated invoices
    db_connect();
    $sql = "SELECT invid,cusnum FROM invoices WHERE printed = 'n' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
    $alloc = "";
    $i = 0;
    while ($inv = pg_fetch_array($invRslt)) {
        db_connect();
        $sql = "SELECT sum(qty) FROM inv_items WHERE stkid = '{$stkid}' AND invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
        $allRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
        $all = pg_fetch_array($allRslt);
        if ($all['sum'] > 0) {
            # Get selected customer info
            db_connect();
            $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to get customer information");
            if (pg_numrows($custRslt) < 1) {
                return details($_POST);
            }
            $cust = pg_fetch_array($custRslt);
            # get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return details($_POST);
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $alloc .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>{$dept['deptname']}</td>\n\t\t\t\t\t\t\t\t<td>{$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t\t\t\t\t<td>{$inv['invid']}</td>\n\t\t\t\t\t\t\t\t<td>{$all['sum']} x {$stk['suom']}</td>\n\t\t\t\t\t\t\t</tr>";
            $i++;
        }
    }
    if ($i < 1) {
        $alloc = "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan='4'>No Invoices Allocated</td>\n\t\t\t\t\t\t</tr>";
    }
    # get all undone allocated invoices
    db_connect();
    $sql = "SELECT invid,cusnum FROM invoices WHERE printed = 'n' AND done != 'y' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
    $nalloc = "";
    $i = 0;
    while ($inv = pg_fetch_array($invRslt)) {
        db_connect();
        $sql = "SELECT sum(qty) FROM inv_items WHERE stkid = '{$stkid}' AND invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
        $allRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
        $all = pg_fetch_array($allRslt);
        if ($all['sum'] > 0) {
            # Get selected customer info
            db_connect();
            $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to get customer information");
            if (pg_numrows($custRslt) < 1) {
                return details($_POST);
            }
            $cust = pg_fetch_array($custRslt);
            # get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return details($_POST);
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $nalloc .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>{$dept['deptname']}</td>\n\t\t\t\t\t\t\t\t<td>{$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t\t\t\t\t<td>{$inv['invid']}</td>\n\t\t\t\t\t\t\t\t<td>{$all['sum']} x {$stk['suom']}</td>\n\t\t\t\t\t\t\t</tr>";
            $i++;
        }
    }
    if ($i < 1) {
        $nalloc = "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan='4'>No Incomplete Invoices Allocated</td>\n\t\t\t\t\t\t</tr>";
    }
    # get all undone allocated invoices
    db_connect();
    $sql = "SELECT * FROM pinvoices WHERE printed = 'n' AND done != 'y' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
    $pall = "";
    $i = 0;
    while ($inv = pg_fetch_array($invRslt)) {
        db_connect();
        $sql = "SELECT sum(qty) FROM pinv_items WHERE stkid = '{$stkid}' AND invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
        $allRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
        $all = pg_fetch_array($allRslt);
        if ($all['sum'] > 0) {
            # Get selected customer info
            # get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return details($_POST);
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $pall .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>{$dept['deptname']}</td>\n\t\t\t\t\t\t\t\t<td>{$inv['cusname']}</td>\n\t\t\t\t\t\t\t\t<td>{$inv['invid']}</td>\n\t\t\t\t\t\t\t\t<td>{$all['sum']} x {$stk['suom']}</td>\n\t\t\t\t\t\t\t</tr>";
            $i++;
        }
    }
    if ($i < 1) {
        $pall = "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='4'>No unprinted POS Invoices</td>\n\t\t\t\t\t</tr>";
    }
    # get all allocated quotes
    db_connect();
    $sql = "SELECT sordid,cusnum FROM sorders WHERE accepted = 'n' AND div = '" . USER_DIV . "'";
    $sordRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
    $sordalloc = "";
    $q = 0;
    while ($sord = pg_fetch_array($sordRslt)) {
        db_connect();
        $sql = "SELECT sum(qty) FROM sorders_items WHERE stkid = '{$stkid}' AND sordid = '{$sord['sordid']}' AND div = '" . USER_DIV . "'";
        $qallRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
        $all = pg_fetch_array($qallRslt);
        if ($all['sum'] > 0) {
            # Get selected customer info
            db_connect();
            $sql = "SELECT * FROM customers WHERE cusnum = '{$sord['cusnum']}' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to get customer information");
            if (pg_numrows($custRslt) < 1) {
                return details($_POST);
            }
            $cust = pg_fetch_array($custRslt);
            # get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return details($_POST);
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $sordalloc .= "\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td>{$dept['deptname']}</td>\n\t\t\t\t\t\t\t\t\t<td>{$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t\t\t\t\t\t<td>{$sord['sordid']}</td>\n\t\t\t\t\t\t\t\t\t<td>{$all['sum']} x {$stk['suom']}</td>\n\t\t\t\t\t\t\t\t</tr>";
            $q++;
        }
    }
    if ($q < 1) {
        $sordalloc = "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan='4'>No Sales Orders Allocated</td>\n\t\t\t\t\t\t</tr>";
    }
    # get all incomplete consignment orders
    db_connect();
    $sql = "SELECT * FROM corders WHERE div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
    $call = "";
    $c = 0;
    while ($cord = pg_fetch_array($invRslt)) {
        db_connect();
        $sql = "SELECT sum(qty) FROM corders_items WHERE stkid = '{$stkid}' AND sordid = '{$cord['sordid']}' AND div = '" . USER_DIV . "'";
        $allRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
        $all = pg_fetch_array($allRslt);
        if ($all['sum'] > 0) {
            # get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$cord['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                //	return details($_POST);
                return "<li class='err'>Unable to get department information. (Consignment Orders)</li>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $call .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>{$dept['deptname']}</td>\n\t\t\t\t\t\t\t\t<td>{$cord['surname']}</td>\n\t\t\t\t\t\t\t\t<td>{$cord['sordid']}</td>\n\t\t\t\t\t\t\t\t<td>{$all['sum']} x {$stk['suom']}</td>\n\t\t\t\t\t\t\t</tr>";
            $c++;
        }
    }
    if ($c < 1) {
        $call = "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='4'>No Consignment Orders</td>\n\t\t\t\t\t</tr>";
    }
    // Layout
    $confirm .= "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h3>Stock Allocation</h3>\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<td colspan='4'><h4>Unprinted Invoices</h4></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Department</th>\n\t\t\t\t\t\t\t<th>Customer</th>\n\t\t\t\t\t\t\t<th>Invoice No.</th>\n\t\t\t\t\t\t\t<th>Quantity Allocated</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t{$alloc}\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='4'><h4>Unprinted POS Invoices</h4></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Department</th>\n\t\t\t\t\t\t\t<th>Customer</th>\n\t\t\t\t\t\t\t<th>Invoice No.</th>\n\t\t\t\t\t\t\t<th>Quantity Allocated</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t{$pall}\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='4'><h4>Incomplete Invoices</h4></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Department</th>\n\t\t\t\t\t\t\t<th>Customer</th>\n\t\t\t\t\t\t\t<th>Invoice No.</th>\n\t\t\t\t\t\t\t<th>Quantity Allocated</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t{$nalloc}\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='4'><h4>Sales Orders</h4></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Department</th>\n\t\t\t\t\t\t\t<th>Customer</th>\n\t\t\t\t\t\t\t<th>Sales Order No.</th>\n\t\t\t\t\t\t\t<th>Quantity Allocated</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t{$sordalloc}\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='4'><h4>Consignment Orders</h4></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Department</th>\n\t\t\t\t\t\t\t<th>Customer</th>\n\t\t\t\t\t\t\t<th>Consignment Order No.</th>\n\t\t\t\t\t\t\t<th>Quantity Allocated</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t{$call}\n\t\t\t\t\t</table>\n\t\t\t\t\t<p>\n\t\t\t\t\t<input type='button' value='[X] Close' onClick='javascript:window.close();'>";
    return $confirm;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 9, "Invalid Order ID");
    $v->isOk($ordernum, "string", 0, 20, "Invalid order number.");
    $v->isOk($supid, "num", 1, 20, "Invalid Supplier number.");
    $v->isOk($terms, "num", 1, 5, "Invalid terms days.");
    $v->isOk($npuri_day, "num", 1, 2, "Invalid Date day.");
    $v->isOk($npuri_month, "num", 1, 2, "Invalid Date month.");
    $v->isOk($npuri_year, "num", 1, 5, "Invalid Date year.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    $v->isOk($xrate, "float", 1, 20, "Invalid Exchange Rate.");
    $v->isOk($tax, "float", 0, 20, "Invalid Tax.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $pdate = $npuri_year . "-" . $npuri_month . "-" . $npuri_day;
    if (!checkdate($npuri_month, $npuri_day, $npuri_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    $ddate = $del_year . "-" . $del_month . "-" . $del_day;
    if (!checkdate($del_month, $del_day, $del_year)) {
        $v->isOk($ddate, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            # Nasty Zeros
            $unitcost[$keys] += 0;
            $cunitcost[$keys] += 0;
            $duty[$keys] += 0;
            $dutyp[$keys] += 0;
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 0, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($cunitcost[$keys], "float", 0, 20, "Invalid Foreign currency Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($duty[$keys], "float", 0, 20, "Invalid Duty Charges for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($dutyp[$keys], "float", 0, 20, "Invalid Duty Charges Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($des[$keys], "string", 1, 255, "Invalid Description.");
            $v->isOk($cod[$keys], "string", 0, 255, "Invalid Item Code.");
            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 Order info
    db_connect();
    $sql = "SELECT * FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # Get selected supplier  info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get supplier  information");
    $sup = pg_fetch_array($supRslt);
    # Currency
    $currs = getSymbol($sup['fcid']);
    $curr = $currs['symbol'];
    # check if Order has been printed
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : Order number <b>{$pur['purnum']}</b> has already been received.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # fix those nasty zeros
    $xrate += 0;
    if ($xrate == 0) {
        $xrate = 1;
    }
    $shipchrg += 0;
    $tax += 0;
    # insert Order 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_purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Order items in Cubit.", SELF);
    /* -- End remove old items -- */
    $VATP = TAX_VAT;
    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 the unitcost
                    if ($cunitcost[$keys] > 0) {
                        $unitcost[$keys] = round($cunitcost[$keys] * $xrate, 2);
                    } else {
                        $cunitcost[$keys] = round($unitcost[$keys] / $xrate, 2);
                    }
                    # Calculate the duty amount
                    if ($duty[$keys] < 1) {
                        if ($dutyp[$keys] > 0) {
                            $duty[$keys] = round($dutyp[$keys] / 100 * $unitcost[$keys], 2);
                        }
                    } else {
                        if ($unitcost[$keys] > 0) {
                            $dutyp[$keys] = round($duty[$keys] * 100 / $unitcost[$keys], 2);
                        } else {
                            $dutyp[$keys] = 0;
                        }
                    }
                    # Calculate amount
                    $amt[$keys] = $qtys[$keys] * $cunitcost[$keys] + $duty[$keys];
                    # insert Order items
                    $sql = "\n\t\t\t\t\t\tINSERT INTO nons_purint_items (\n\t\t\t\t\t\t\tpurid, cod, des, qty, unitcost, cunitcost, duty, dutyp, amt, div\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$purid}', '{$cod[$keys]}', '{$des[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$cunitcost[$keys]}', '{$duty[$keys]}', '{$dutyp[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "'\n\t\t\t\t\t\t)";
                    $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
                }
            } else {
                # Calculate the unitcost
                if ($cunitcost[$keys] > 0) {
                    $unitcost[$keys] = round($cunitcost[$keys] * $xrate, 2);
                } else {
                    $cunitcost[$keys] = round($unitcost[$keys] / $xrate, 2);
                }
                # Calculate the duty amount
                if ($duty[$keys] < 1) {
                    if ($dutyp[$keys] > 0) {
                        $duty[$keys] = round($dutyp[$keys] / 100 * $unitcost[$keys], 2);
                    }
                } else {
                    if ($unitcost[$keys] > 0) {
                        $dutyp[$keys] = round($duty[$keys] * 100 / $unitcost[$keys], 2);
                    } else {
                        $dutyp[$keys] = 0;
                    }
                }
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $cunitcost[$keys] + $duty[$keys];
                # insert Order items
                $sql = "\n\t\t\t\t\tINSERT INTO nons_purint_items (\n\t\t\t\t\t\tpurid, cod, des, qty, unitcost, cunitcost, \n\t\t\t\t\t\tduty, dutyp, amt, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$cod[$keys]}', '{$des[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$cunitcost[$keys]}', \n\t\t\t\t\t\t'{$duty[$keys]}', '{$dutyp[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert 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 name='recv' type='submit' value='Receive'>\n\t\t\t&nbsp; | &nbsp;<input type='submit' name='donePrnt' value='Done, Print and make another'>";
        }
    } else {
        $_POST["done"] = "";
    }
    /* --- Clac --- */
    # Calculate subtot
    if (isset($amt)) {
        $SUBTOT = array_sum($amt);
    } else {
        $SUBTOT = 0.0;
    }
    # shipchrg is in for curr
    $fshipchrg = $shipchrg;
    // $shipchrg = ($shipchrg * $xrate);
    # total
    $TOTAL = sprint($SUBTOT + $shipchrg + $tax);
    # total Duty
    if (isset($duty)) {
        $dutytot = sprint(array_sum($duty));
    } else {
        $dutytot = "0.00";
    }
    # Local Totals
    $LTOTAL = sprint($TOTAL * $xrate);
    $LSUBTOT = sprint($SUBTOT * $xrate);
    /* --- End Clac --- */
    # insert Order to DB
    $sql = "\n\t\tUPDATE nons_purch_int \n\t\tSET supid = '{$supid}',cusid = '{$delvat}', supplier = '{$sup['supname']}', supaddr = '{$sup['supaddr']}', terms = '{$terms}', \n\t\t\tpdate = '{$pdate}', ddate = '{$ddate}', fcid = '{$sup['fcid']}', currency = '{$curr}', curr = '{$curr}', tax = '{$tax}', \n\t\t\txrate = '{$xrate}', fshipchrg = '{$fshipchrg}', shipchrg = '{$shipchrg}', duty = '{$dutytot}', subtot = '{$SUBTOT}', \n\t\t\ttotal = '{$TOTAL}', balance = '{$TOTAL}', fsubtot = '{$LSUBTOT}', fbalance = '{$LTOTAL}', remarks = '{$remarks}' \n\t\tWHERE purid = '{$purid}'";
    $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $lastid = pglib_lastid("nons_purch_int", "purid");
    if (isset($donePrnt)) {
        $sql = "UPDATE nons_purch_int SET done='y' WHERE purid='{$purid}' AND div='" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.");
        $OUTPUT = "\n\t\t\t<script>\n\t\t\t\tprinter('nons-purch-int-print.php?purid={$lastid}');\n\t\t\t\tmove('nons-purch-int-new.php');\n\t\t\t</script>";
        return $OUTPUT;
    }
    if (isset($recv)) {
        header("Location: nons-purch-int-recv.php?purid={$purid}");
        exit;
    } elseif (!isset($doneBtn)) {
        return details($_POST);
    } else {
        # insert Order to DB
        $sql = "UPDATE nons_purch_int SET done = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order 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 International Non-Stock Order</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>International Non-Stock Order from Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t\t\t<td><a href='nons-purch-int-print.php?purid={$lastid}'>Print Order</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-purch-int-view.php'>View International Non-Stock 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;
    }
}
#
#
#
#
#
#
#
#
#
#
# get settings
require "settings.php";
require "core-settings.php";
# decide what to do
if (isset($_GET["ordnum"])) {
    $OUTPUT = details($_GET["ordnum"]);
} else {
    $OUTPUT = "<li> Invalid Order number";
}
# get templete
require "template.php";
# View details
function details($ordnum)
{
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($ordnum, "num", 1, 50, "Invalid order number.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($budid, "num", 1, 20, "Invalid Budget id.");
    $v->isOk($budname, "string", 1, 255, "Invalid Budget Name.");
    $v->isOk($budtype, "string", 1, 20, "Invalid Budget type.");
    if ($budfor == 'acc') {
        if (isset($accids)) {
            foreach ($accids as $akey => $accid) {
                $v->isOk($accid, "num", 1, 50, "Invalid Account number.");
                foreach ($amts[$accid] as $skey => $amtr) {
                    $v->isOk($amts[$accid][$skey], "float", 1, 20, "Invalid Budget amount.");
                }
            }
        } else {
            $v->isOk("#", "num", 0, 0, "Error : please select at least one account.");
        }
    } elseif ($budfor == 'cost') {
        if (isset($ccids)) {
            foreach ($ccids as $akey => $ccid) {
                $v->isOk($ccid, "num", 1, 50, "Invalid Cost Center.");
                foreach ($amts[$ccid] as $skey => $amtr) {
                    $v->isOk($amts[$ccid][$skey], "float", 1, 20, "Invalid Budget amount.");
                }
            }
        } else {
            $v->isOk("#", "num", 0, 0, "Error : please select at least one cost center.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        return details($_POST, $confirm);
    }
    # Query server
    db_connect();
    $sql = "SELECT * FROM budgets WHERE budid = '{$budid}'";
    $budRslt = db_exec($sql) or errDie("Unable to retrieve Budgets from database.");
    if (pg_numrows($budRslt) < 1) {
        return "<li class=err> - Invalid Budget.";
    }
    $bud = pg_fetch_array($budRslt);
    global $BUDFOR, $PERIODS, $TYPES, $YEARS;
    $vbudfor = $BUDFOR[$bud['budfor']];
    $vbudtype = $TYPES[$budtype];
    $vfromyr = $YEARS[$bud['fromprd']];
    $vtoyr = $YEARS[$bud['toprd']];
    db_connect();
    $sql = "UPDATE budgets SET budname = '{$budname}', budtype = '{$budtype}' WHERE budid = '{$budid}'";
    $inRs = db_exec($sql);
    # delete old values
    $rs = db_exec("DELETE FROM buditems WHERE budid = '{$budid}'");
    if ($bud['budfor'] == 'acc') {
        foreach ($accids as $akey => $id) {
            foreach ($amts[$id] as $sprd => $amt) {
                $sql = "INSERT INTO buditems(budid, id, prd, amt) VALUES('{$budid}', '{$id}', '{$sprd}', '{$amt}')";
                $itRs = db_exec($sql);
            }
        }
    } else {
        foreach ($ccids as $akey => $id) {
            foreach ($amts[$id] as $sprd => $amt) {
                $sql = "INSERT INTO buditems(budid, id, prd, amt) VALUES('{$budid}', '{$id}', '{$sprd}', '{$amt}')";
                $itRs = db_exec($sql);
            }
        }
    }
    // Start layout
    $write = "<center>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=500>\n\t\t<tr><th colspan=2>Edit Yearly Budget</th></tr>\n\t\t<tr><td class='bg-odd' colspan=2>Yearly Budget <b>{$budname}</b> has been edited.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=25%>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class='bg-odd'><td align=center><a href='budget-view.php'>View Budgets</td></tr>\n\t\t<tr class='bg-odd'><td align=center><a href='../main.php'>Main Menu</td></tr>\n\t</table>";
    return $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 bwrite($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($prd, "num", 1, 20, "Invalid period Database number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # 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>");
            if ($qty > $qts[$keys]) {
                $v->isOk($qty, "num", 0, 0, "Error : Quantity for product number : <b>" . ($keys + 1) . "</b> is more that Qty Orderd");
            }
            $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>");
            }
        }
    }
    # 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);
    }
    # Get Order info
    db_conn($prd);
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # Get selected supplier info
    db_connect();
    if ($pur['ctyp'] == 's') {
        $supid = $pur['typeid'];
        $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql) or errDie("Unable to get supplier");
        if (pg_numrows($supRslt) < 1) {
            $error = "<li class='err'> Supplier not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $sup = pg_fetch_array($supRslt);
            $pur['supplier'] = $sup['supname'];
            $pur['supaddr'] = $sup['supaddr'];
            # Get department info
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$sup['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $supacc = $dept['credacc'];
        }
    } elseif ($pur['ctyp'] == 'c') {
        $deptid = $pur['typeid'];
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Department not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = $dept['pca'];
        }
    }
    # Insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    if (isset($qtys)) {
        # amount of stock in
        $totstkamt = array();
        $resub = 0;
        # Get subtotal
        foreach ($qtys as $keys => $value) {
            # Skip zeros
            if ($qtys[$keys] < 1) {
                continue;
            }
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        }
        $SUBTOTAL = array_sum($amt);
        $revat = 0;
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            $sql = "SELECT * FROM nons_pur_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # Calculate cost amount bought
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
            /* delivery charge */
            # Calculate percentage from subtotal
            $perc[$keys] = $amt[$keys] / $SUBTOTAL * 100;
            # Get percentage from shipping charges
            $shipc[$keys] = $perc[$keys] / 100 * $shipchrg;
            # add delivery charges
            $amt[$keys] += $shipc[$keys];
            /* end delivery charge */
            # the subtotal + delivery charges
            $resub += $amt[$keys];
            # calculate vat
            $svat[$keys] = svat($amt[$keys], $stkd['amt'], $stkd['svat']);
            # received vat
            $revat += $svat[$keys];
            # make amount vat free
            if ($pur['vatinc'] == "yes") {
                $amt[$keys] = $amt[$keys] - $svat[$keys];
            }
            # Update Order items
            $sql = "\n\t\t\t\t\tUPDATE nons_pur_items \n\t\t\t\t\tSET rqty = (rqty + '{$qtys[$keys]}'), accid = '{$stkacc[$keys]}' \n\t\t\t\t\tWHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            # keep records for transactions
            if (isset($totstkamt[$stkacc[$keys]])) {
                $totstkamt[$stkacc[$keys]] += $amt[$keys];
            } else {
                $totstkamt[$stkacc[$keys]] = $amt[$keys];
            }
            # check if there are any outstanding items
            $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            # if none the set to received
            if (pg_numrows($stkdRslt) < 1) {
                # update surch_int(received = 'y')
                $sql = "\n\t\t\t\t\t\tUPDATE nons_purchases \n\t\t\t\t\t\tSET received = 'y', supplier = '{$pur['supplier']}', supaddr = '{$pur['supaddr']}' \n\t\t\t\t\t\tWHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF);
            }
        }
    }
    # Update Order on the DB
    if ($pur['part'] == 'y') {
        # Update Order on the DB
        $sql = "\n\t\t\t\tUPDATE nons_purchases \n\t\t\t\tSET ctyp = '{$ctyp}', typeid = '{$typeid}', refno = '{$refno}', remarks = '{$remarks}' \n\t\t\t\tWHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    } else {
        # Update Order on the DB
        $sql = "\n\t\t\t\tUPDATE nons_purchases \n\t\t\t\tSET ctyp = '{$ctyp}', typeid = '{$typeid}', refno = '{$refno}', remarks = '{$remarks}' \n\t\t\t\tWHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    }
    /* Transactions */
    $refnum = getrefnum(date("d-m-Y"));
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    $detadd = "";
    if (isset($supid)) {
        $detadd = " from Supplier {$sup['supname']}";
    }
    $sdate = $pur['pdate'];
    $tpp = 0;
    $ccamt = 0;
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        # Debit Stock and Credit Suppliers control
        writetrans($stkacc, $supacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $wamt, "Cash Order");
    }
    # vat
    $vatamt = $revat;
    # Add vat if not included
    if ($pur['vatinc'] == 'no') {
        $retot = $resub + $vatamt;
    } elseif ($pur['vatinc'] == "novat") {
        $retot = $resub;
        $vatamt = 0;
    } else {
        $retot = $resub;
    }
    if (isset($supid)) {
        # Ledger Records
        $DAte = $pur['pdate'];
        suppledger($sup['supid'], $stkacc, $DAte, $pur['purid'], "Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'c');
    }
    if ($vatamt != 0) {
        # Debit bank and credit the account involved
        writetrans($vatacc, $supacc, date("d-m-Y"), $refnum, $vatamt, "Non-Stock Purchase VAT paid on Non-Stock Order No. {$pur['purnum']} {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $vatamt, "Cash Order VAT");
        # Record the payment on the statement
        db_connect();
        $sdate = $pur['pdate'];
    }
    if (isset($supid)) {
        $DAte = $pur['pdate'];
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$retot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "\n\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\tsupid, edate, cacc, amount, descript, ref, ex, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$sup['supid']}','{$DAte}', '{$dept['credacc']}', '{$retot}', 'Non Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t\t)";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        db_connect();
        # update the supplier age analysis (make balance less)
        /* Make transaction record for age analysis */
        $sql = "\n\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$sup['supid']}', '{$pur['purnum']}', '{$DAte}', '{$retot}', '" . USER_DIV . "'\n\t\t\t\t)";
        $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    }
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End Transactions */
    /* Start moving if Order received */
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        # copy Order
        db_conn($pur['prd']);
        $sql = "\n\t\t\t\tINSERT INTO nons_purchases (\n\t\t\t\t\tpurid, deptid, supplier, supaddr, terms, pdate, ddate, \n\t\t\t\t\tshipchrg, shipping, subtot, total, balance, vatinc, vat, \n\t\t\t\t\tremarks, refno, received, done, ctyp, typeid, div, purnum\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', \n\t\t\t\t\t'{$pur['shipchrg']}', '{$pur['shipping']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', \n\t\t\t\t\t'{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '{$pur['ctyp']}', '{$pur['typeid']}', '" . USER_DIV . "', '{$pur['purnum']}'\n\t\t\t\t)";
        $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Order to Cubit.", SELF);
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert Order items
            db_conn($pur['prd']);
            $sql = "\n\t\t\t\t\tINSERT INTO nons_pur_items (\n\t\t\t\t\t\tpurid, cod, des, qty, unitcost, amt, \n\t\t\t\t\t\tsvat, ddate, accid, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', \n\t\t\t\t\t\t'{$stktc['svat']}', '{$stktc['ddate']}', '{$stktc['accid']}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        db_connect();
        # Remove the Order from running DB
        $sql = "DELETE FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Remove those Order items from running DB
        $sql = "DELETE FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    }
    /* End moving Order received */
    $cc = "<script> CostCenter('ct', 'Non-Stock Purchase', '{$pur['pdate']}', 'Non Stock Purchase No.{$pur['purnum']}', '" . ($retot - $vatamt) . "', ''); </script>";
    // Final Layout
    $write = "\n\t\t{$cc}\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Non-Stock Order received</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Non-Stock Order receipt 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='nons-purchase-view.php'>View Orders</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    if (!isset($cusnum)) {
        return details($_POST, "<li class='err'>Please select customer/department first.</li>");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($quoid, "num", 1, 20, "Invalid Quote 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 order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($quote_day, "num", 1, 2, "Invalid Quote Date day.");
    $v->isOk($quote_month, "num", 1, 2, "Invalid Quote Date month.");
    $v->isOk($quote_year, "num", 1, 5, "Invalid Quote Date year.");
    $odate = $quote_year . "-" . $quote_month . "-" . $quote_day;
    if (!checkdate($quote_month, $quote_day, $quote_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Quote Date.");
    }
    $v->isOk($ncdate_day, "num", 1, 2, "Invalid Next Contact Date day.");
    $v->isOk($ncdate_month, "num", 1, 2, "Invalid Next Contact Date month.");
    $v->isOk($ncdate_year, "num", 1, 5, "Invalid Next Contact Date year.");
    $ncdate = $ncdate_year . "-" . $ncdate_month . "-" . $ncdate_day;
    if (!checkdate($ncdate_month, $ncdate_day, $ncdate_year)) {
        $v->isOk($ncdate, "num", 1, 1, "Invalid Followon 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.");
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "float", 1, 15, "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>.");
            if ($discp[$keys] > 100) {
                $v->isOk($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than 100 %.");
            }
            $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.");
        }
    }
    # 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.");
        }
    }
    # 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);
    }
    // 	# insert quote to DB
    // 	$sql = "UPDATE quotes SET delvat='$delvat',cusnum = '$cusnum', deptname = '$dept[deptname]', cusacc = '$cust[accno]', cusname = '$cust[cusname]', surname = '$cust[surname]', cusaddr = '$cust[addr1]', cusvatno = '$cust[vatnum]', cordno = '$cordno', ordno = '$ordno', chrgvat = '$chrgvat', terms = '$terms', salespn = '$salespn',
    // 	odate = '$odate', traddisc = '$traddisc', delchrg = '$delchrg', subtot = '$SUBTOT', vat = '$VAT', total = '$TOTAL', balance = '$TOTAL', comm = '$comm', discount='$traddiscmt', delivery='$delexvat' WHERE quoid = '$quoid'";
    // 	$rslt = db_exec($sql) or errDie("Unable to update quote in Cubit.",SELF);
    # Get quote info
    db_connect();
    $sql = "SELECT * FROM quotes WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
    $quoRslt = db_exec($sql) or errDie("Unable to get quote information");
    if (pg_numrows($quoRslt) < 1) {
        return "<li>- Quote Not Found</li>";
    }
    $quo = pg_fetch_array($quoRslt);
    $quo['traddisc'] = $traddisc;
    # check if quote has been printed
    if ($quo['accepted'] == "y") {
        $error = "<li class='err'>Error : Quote number <b>{$quoid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM quote_data WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        $quo['deptid'] = $cust['deptid'];
        # If customer was just selected, get the following
        if ($quo['cusnum'] == 0) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
        }
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$quo['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 quote 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 quote
    db_connect();
    $sql = "SELECT * FROM quote_items  WHERE quoid = '{$quoid}' 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]'";
    #	$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    #}
    # remove old items
    $sql = "DELETE FROM quote_items WHERE quoid='{$quoid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update quote items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod) && in_array($keys, $remprod)) {
                // 					if(in_array($keys, $remprod)){
                // 						# skip product (wonder if $keys still align)
                // 						$amt[$keys] = 0;
                // 						continue;
                // 					}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]));
                //
                // 						# Check Tax Excempt
                // 						if($stk['exvat'] == 'yes'){
                // 							$taxex += $amt[$keys];
                // 						}
                //
                // 						$wtd = $whids[$keys];
                // 						# insert quote items
                // 						$sql = "INSERT INTO quote_items(quoid, whid, stkid, qty, unitcost, amt, disc, discp, div) VALUES('$quoid', '$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 quote items to Cubit.",SELF);
                //
                // 						# update stock(alloc + qty)
                // 						# $sql = "UPDATE stock SET alloc = (alloc + '$qtys[$keys]') WHERE stkid = '$stkids[$keys]'";
                // 						# $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
                // 					}
            } elseif (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);
                # Calculate amount
                $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], $quo['chrgvat'], $excluding, $quo['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 = "\n\t\t\t\t\t\tINSERT INTO quote_items (\n\t\t\t\t\t\t\tquoid, whid, stkid, qty, unitcost, amt, \n\t\t\t\t\t\t\tdisc, discp,  div, vatcode, description, \n\t\t\t\t\t\t\taccount\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$quoid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '" . USER_DIV . "', '{$vatcodes[$keys]}', '{$descriptions[$keys]}', \n\t\t\t\t\t\t\t'{$accounts[$keys]}'\n\t\t\t\t\t\t)";
                $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], $quo['chrgvat'], $excluding, $quo['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 quote items
                $sql = "\n\t\t\t\t\t\tINSERT INTO quote_items (\n\t\t\t\t\t\t\tquoid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\t\tamt, disc, discp, div, vatcode\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$quoid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t\t'{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '" . USER_DIV . "','{$vatcodes[$keys]}'\n\t\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert quote items to Cubit.", SELF);
                # update stock(alloc + qty)
                # $sql = "UPDATE stock SET alloc = (alloc + '$qtys[$keys]') WHERE stkid = '$stkids[$keys]'";
                # $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
            }
            # everything is set place done button
            $_POST["done"] = "&nbsp; | &nbsp;<input name='doneBtn' type='submit' value='Done'>";
            //&nbsp; | &nbsp;<input type='submit' name='donePrnt' value='Done, Print and make another'>";
        }
    } else {
        $_POST["done"] = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$delvat}'";
    $Ri = db_exec($Sl);
    $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, $quo['chrgvat'], $excluding, $quo['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 = $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 = $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);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- ----------- Clac ---------------------
    
    		# calculate subtot
    		$SUBTOT = 0.00;
    		if(isset($amt))
    			$SUBTOT = array_sum($amt);
    
    		$SUBTOT -= $taxex;
    
    		# duplicate
    		$SUBTOTAL = $SUBTOT;
    
    		$VATP = TAX_VAT;
    		if($chrgvat == "exc"){
    			$SUBTOTAL = $SUBTOTAL;
    			$delexvat= ($delchrg);
    		}elseif($chrgvat == "inc"){
    			$SUBTOTAL = sprint(($SUBTOTAL * 100)/(100 + $VATP));
    			$delexvat = sprint(($delchrg * 100)/($VATP + 100));
    		}else{
    			$SUBTOTAL = ($SUBTOTAL);
    			$delexvat = ($delchrg);
    		}
    
    		$SUBTOT = $SUBTOTAL;
    		$EXVATTOT = $SUBTOT;
    		$EXVATTOT += $delexvat;
    
    		# Minus trade discount from taxex
    		if($traddisc > 0){
    			$traddiscmtt = (($traddisc/100) * $taxex);
    		}else{
    			$traddiscmtt = 0;
    		}
    		$taxext = ($taxex - $traddiscmtt);
    
    		if($traddisc > 0) {
    			$traddiscmt = ($EXVATTOT * ($traddisc/100));
    		}else{
    			$traddiscmt = 0;
    		}
    		$EXVATTOT -= $traddiscmt;
    		// $EXVATTOT -= $taxex;
    
    		$traddiscmt = sprint($traddiscmt  + $traddiscmtt);
    
    		if($chrgvat != "nov"){
    			$VAT = sprint($EXVATTOT * ($VATP/100));
    		}else{
    			$VAT = 0;
    		}
    
    		$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    		$SUBTOT += $taxex;
    
    /* --- ----------- Clac --------------------- */
    $delvat += 0;
    //manual error handling
    if (!isset($lead)) {
        $lead = "";
    }
    # insert quote to DB
    $sql = "\n\t\t\tUPDATE quotes \n\t\t\tSET delvat='{$delvat}',cusnum = '{$cusnum}', deptid = '{$dept['deptid']}', deptname = '{$dept['deptname']}', \n\t\t\t\tcusacc = '{$cust['accno']}', cusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\t\tcusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', chrgvat = '{$chrgvat}', terms = '{$terms}', \n\t\t\t\tsalespn = '{$salespn}', odate = '{$odate}', ncdate = '{$ncdate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', \n\t\t\t\tsubtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', comm = '{$comm}', discount='{$traddiscmt}', \n\t\t\t\tdelivery='{$delexvat}', lead = '{$lead}' \n\t\t\tWHERE quoid = '{$quoid}'";
    $rslt = db_exec($sql) or errDie("Unable to update quote in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM quote_data WHERE quoid='{$quoid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update quote data in Cubit.", SELF);
    # pu in new data
    $sql = "\n\t\t\tINSERT INTO quote_data (\n\t\t\t\tquoid, dept, customer, addr1, div\n\t\t\t) VALUES (\n\t\t\t\t'{$quoid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '" . USER_DIV . "'\n\t\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert quote data to Cubit.", SELF);
    $ncdate = "{$ncdate_year}-{$ncdate_month}-{$ncdate_day}";
    /* --- Start button Listeners --- */
    if (isset($donePrnt)) {
        $sql = "UPDATE quotes SET done='y' WHERE quoid='{$quoid}' AND div='" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update quote status in Cubit.");
        $OUTPUT = "\n\t\t\t<script>\n\t\t\t\tprinter('pdf/pdf-quote.php?quoid={$quoid}');\n\t\t\t\tmove('quote-new.php');\n\t\t\t</script>";
        return $OUTPUT;
    }
    if (isset($doneBtn)) {
        # insert quote to DB
        $sql = "UPDATE quotes SET done = 'y' WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update quote 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, \n\t\t\t\t\tassigned_to, assigned_to_id, account_id, gender, website, salespid, ncdate, team_id, dept_id, tell, \n\t\t\t\t\thadd, ref\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cust['surname']}', 'now', '" . USER_NAME . "', 'No', '" . USER_DIV . "', '0', '0', '0', 'now', '0', \n\t\t\t\t\t'" . USER_NAME . "', '2', '0', 'Male', 'http://', '0', '{$ncdate}', '0', '0', '{$cust['cellno']}', \n\t\t\t\t\t'{$cust['addr1']}', ''\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to add lead to database.");
            $lead_id = pglib_lastid("leads", "id");
        }
    }
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (isset($doneBtn)) {
        //old <a target='_blank' href='quote-print.php?quoid=$quoid'>Print Quote</a>
        // Final Laytout
        // 		$write = "
        // 			<table ".TMPL_tblDflts.">
        // 				<tr>
        // 					<th colspan='2'>New Quote</th>
        // 				</tr>
        // 				<tr class='".bg_class()."'>
        // 					<td>Quote for customer <b>$cust[cusname] $cust[surname]</b> has been recorded.</td>
        // 					<td><input type='button' onClick=\"javascript:printer('pdf/quote-pdf-print.php?quoid=$quoid')\" value='Print Quote'></td>
        // 					<td><input type='button' onclick='javascript:move(\"quote-email.php?evs=$quoid\")' value='Email'></td>
        // 				</tr>
        // 			</table>"
        // 			.mkQuickLinks(
        // 				ql("quote-view.php", "View Quotes"),
        // 				ql("customers-new.php", "New Customer")
        // 			);
        // 		return $write;
        return "\n\t\t\t<script>\n\t\t\t\tprinter('quote-print.php?quoid={$quoid}');\n\t\t\t\tdocument.location='quote-new.php';\n\t\t\t</script>";
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New Quote Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Quote for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</td>\n\t\t\t\t</tr>\n\t\t\t</table>" . mkQuickLinks(ql("quote-view.php", "View Quotes"), ql("customers-new.php", "New Customer"));
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        return details($_POST);
    }
    /* --- End button Listeners --- */
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($supinv, "string", 0, 255, "Invalid supp inv.");
    # used to generate errors
    $error = "asa@";
    # 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);
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $td = $pur['pdate'];
    # check if purchase has been received
    if ($pur['invcd'] == "y") {
        $error = "<li class=err> Error : purchase number <b>{$pur['purnum']}</b> has already been invoiced.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($supRslt) < 1) {
        // code here
    } else {
        $sup = pg_fetch_array($supRslt);
    }
    # Get department info
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['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);
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $Ri = db_exec($sql);
    $refnum = getrefnum();
    while ($id = pg_fetch_array($Ri)) {
        db_connect();
        # get selamt from selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$id['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatcode']}'";
        $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 ($id['svat'] == 0) {
            $exvat = "y";
        } else {
            $exvat = "";
        }
        $vr = pvatcalc($id['amt'], $pur['vatinc'], $exvat);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Purchase {$pur['purnum']} Supplier : {$pur['supname']}.", $iamount, $ivat);
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    # Record the payment on the statement
    db_connect();
    $sdate = date("Y-m-d");
    $DAte = date("Y-m-d");
    db_connect();
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$pur['total']}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$pur['supid']}','{$pur['pdate']}', '{$dept['credacc']}', '{$pur['total']}', 'Stock Received - Purchase {$pur['purnum']}', '{$refnum}','{$pur['purnum']}','" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Debit Stock Control and Credit Creditors control
    writetrans($wh['conacc'], $dept['credacc'], $td, $refnum, $pur['total'] - $pur['vat'], "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Transfer vat
    writetrans($vatacc, $dept['credacc'], $td, $refnum, $pur['vat'], "Vat Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Ledger Records
    suppledger($pur['supid'], $wh['conacc'], $td, $pur['purid'], "Purchase No. {$pur['purnum']} received.", $pur['total'], 'c');
    db_connect();
    /* End Transactions */
    /* Make transaction record  for age analysis */
    db_connect();
    # update the supplier age analysis (make balance less)
    if (ext_ex2("suppurch", "purid", $pur['purnum'], "supid", $pur['supid'])) {
        # Found? Make amount less
        $sql = "UPDATE suppurch SET balance = (balance + '{$pur['total']}') WHERE supid = '{$pur['supid']}' AND purid = '{$pur['purnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    } else {
        /* Make transaction record for age analysis */
        $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, div) VALUES('{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$pur['total']}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
    }
    /* Make transaction record  for age analysis */
    # commit updating
    //1 ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    /* Start moving if purchase */
    if ($pur['received'] == "y") {
        if (strlen($pur['appdate']) < 8) {
            $pur['appdate'] = date("Y-m-d");
        }
        # copy purchase
        db_conn(PRD_DB);
        $sql = "INSERT INTO purchases(purid, deptid, supid, supname, supaddr, supno, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, shipping, remarks, refno, received, done, div, purnum, supinv,ordernum,appname,appdate)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}','{$supinv}','{$pur['ordernum']}','{$pur['appname']}','{$pur['appdate']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
        /*-- Cost varience -- */
        $nsubtot = sprint($pur['total'] - $pur['vat']);
        if ($pur['rsubtot'] > $nsubtot) {
            $diff = sprint($pur['rsubtot'] - $nsubtot);
            # Debit Stock Control and Credit Creditors control
            writetrans($wh['conacc'], $cvacc, $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        } elseif ($nsubtot > $pur['rsubtot']) {
            $diff = sprint($nsubtot - $pur['rsubtot']);
            # Debit Stock Control and Credit Creditors control
            writetrans($cvacc, $wh['conacc'], $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        }
        /*-- End Cost varience -- */
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert purchase items
            db_conn(PRD_DB);
            $sql = "INSERT INTO pur_items(purid, whid, stkid, qty, rqty, unitcost, amt, svat, ddate, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        # begin updating
        db_connect();
        # Remove the purchase from running DB
        $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Record where purchase is
        $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
        $movRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Remove those purchase items from running DB
        $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        /* End moving purchase received */
        # commit updating
    } else {
        # insert Order to DB
        $sql = "UPDATE purchases SET invcd = 'y',supinv='{$supinv}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Layout
    $write = "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>Purchase Invoiced</th></tr>\n\t\t<tr class='bg-even'><td>Purchase Invoice from Supplier <b>{$pur['supname']}</b> has been recorded.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class='bg-odd'><td><a href='purchase-view.php'>View purchases</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
Example #15
0
include_once dirname(__FILE__) . '/ressources/class.ldap.inc';
include_once dirname(__FILE__) . "/ressources/class.sockets.inc";
include_once dirname(__FILE__) . "/ressources/class.pdns.inc";
include_once dirname(__FILE__) . '/ressources/class.system.network.inc';
include_once dirname(__FILE__) . '/ressources/class.squid.inc';
$users = new usersMenus();
if (!$users->AsProxyMonitor) {
    echo FATAL_ERROR_SHOW_128("{ERROR_NO_PRIVS}");
    die;
}
if (isset($_GET["graph-size"])) {
    graph_size();
    exit;
}
if (isset($_GET["details"])) {
    details();
    exit;
}
if (isset($_GET["page"])) {
    page();
    exit;
}
if (isset($_GET["cpustats"])) {
    cpustats();
    exit;
}
if (isset($_GET["tabs"])) {
    tabs();
    exit;
}
if (isset($_GET["requests-status"])) {
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($budname, "string", 1, 255, "Invalid Budget Name.");
    $v->isOk($budtype, "string", 1, 20, "Invalid Budget type.");
    $v->isOk($budfor, "string", 1, 20, "Invalid Budget for option.");
    $v->isOk($fromprd, "string", 1, 20, "Invalid Budget period.");
    $v->isOk($toprd, "string", 1, 20, "Invalid Budget period.");
    if ($budfor == 'acc') {
        if (isset($accids)) {
            foreach ($accids as $akey => $accid) {
                $v->isOk($accid, "num", 1, 50, "Invalid Account number.");
                foreach ($amts[$accid] as $skey => $amtr) {
                    $v->isOk($amts[$accid][$skey], "float", 1, 20, "Invalid Budget amount.");
                }
            }
        } else {
            $v->isOk("#", "num", 0, 0, "Error : please select at least one account.");
        }
    } elseif ($budfor == 'cost') {
        if (isset($ccids)) {
            foreach ($ccids as $akey => $ccid) {
                $v->isOk($ccid, "num", 1, 50, "Invalid Cost Center.");
                foreach ($amts[$ccid] as $skey => $amtr) {
                    $v->isOk($amts[$ccid][$skey], "float", 1, 20, "Invalid Budget amount.");
                }
            }
        } else {
            $v->isOk("#", "num", 0, 0, "Error : please select at least one cost center.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>{$e['msg']}</li>";
        }
        return details($_POST, $confirm);
    }
    global $BUDFOR, $TYPES, $PERIODS;
    $vbudfor = $BUDFOR[$budfor];
    $vbudtype = $TYPES[$budtype];
    $vfromprd = $PERIODS[$fromprd];
    $vtoprd = $PERIODS[$toprd];
    db_conn("cubit");
    $sql = "SELECT * FROM budgets WHERE budname='{$budname}' AND budfor='{$budfor}' AND budtype='{$budtype}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve budgets from Cubit.");
    $bud_data = pg_fetch_array($rslt);
    if (!pg_num_rows($rslt)) {
        db_connect();
        $sql = "INSERT INTO budgets(budname, budtype, budfor, fromprd, toprd, edate, div) VALUES('{$budname}', '{$budtype}', '{$budfor}', '{$fromprd}', '{$toprd}', now(), '" . USER_DIV . "')";
        $inRs = db_exec($sql);
        $budid = pglib_lastid("budgets", "budid");
    } else {
        $budid = $bud_data["budid"];
    }
    if ($budfor == 'acc') {
        foreach ($accids as $akey => $id) {
            foreach ($amts[$id] as $sprd => $amt) {
                $sql = "INSERT INTO buditems(budid, id, prd, amt) VALUES('{$budid}', '{$id}', '{$sprd}', '{$amt}')";
                $itRs = db_exec($sql);
            }
        }
    } else {
        foreach ($ccids as $akey => $id) {
            foreach ($amts[$id] as $sprd => $amt) {
                $sql = "INSERT INTO buditems(budid, id, prd, amt) VALUES('{$budid}', '{$id}', '{$sprd}', '{$amt}')";
                $itRs = db_exec($sql);
            }
        }
    }
    // Start layout
    $write = "<center>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=500>\n\t\t<tr>\n\t\t\t<th colspan=2>New Monthly Budget created</th>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td class='bg-odd' colspan=2>New Monthly Budget <b>{$budname}</b> has been created.</td>\n\t\t</tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=25%>\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='bg-odd'>\n\t\t\t<td align=center><a href='budget-view.php'>View Budgets</td>\n\t\t</tr>\n\t\t<tr class='bg-odd'>\n\t\t\t<td align=center><a href='../main.php'>Main Menu</td>\n\t\t</tr>\n\t</table>";
    return $write;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    if (!isset($ria)) {
        $ria = "";
    }
    $v->isOk($ria, "string", 0, 20, "Invalid stock code(fist letters).");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($docref, "num", 0, 20, "Invalid Document Reference No.");
    $v->isOk($ordno, "num", 0, 20, "Invalid sales order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($oday, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($omon, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($oyear, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $oyear . "-" . $omon . "-" . $oday;
    if (!checkdate($omon, $oday, $oyear)) {
        $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.");
    # 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 serai 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>");
            $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>.");
            if ($discp[$keys] > 100) {
                $v->isOk($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than 100 %.");
            }
            $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.");
        }
    }
    # 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.");
        }
    }
    # 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);
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM 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</li>";
    }
    $inv = pg_fetch_array($invRslt);
    # 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 selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM inv_data WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        # If customer was just selected, get the following
        if ($inv['cusnum'] == 0) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
        }
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['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;
    # 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 inv_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 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 {
                    # 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]);
                    $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]);
                    # Check Tax Excempt
                    if ($stk['exvat'] == 'yes') {
                        $taxex += $amt[$keys];
                    }
                    $wtd = $whids[$keys];
                    # insert invoice items
                    $sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, serno, div) VALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '{$sernos[$keys]}','" . USER_DIV . "')";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                    if (strlen($stkt['serno']) > 0) {
                        ext_resvSer($stkt['serno'], $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);
                }
            } 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]);
                # Check Tax Excempt
                if ($stk['exvat'] == 'yes') {
                    $taxex += $amt[$keys];
                }
                $wtd = $whids[$keys];
                # insert invoice items
                $sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, serno, div) VALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '{$sernos[$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='Print'>";
        }
    } else {
        $_POST["done"] = "";
    }
    /* --- ----------- Clac --------------------- */
    # calculate subtot
    $SUBTOT = 0.0;
    if (isset($amt)) {
        $SUBTOT = array_sum($amt);
    }
    $SUBTOT -= $taxex;
    # duplicate
    $SUBTOTAL = $SUBTOT;
    $VATP = TAX_VAT;
    if ($chrgvat == "exc") {
        $SUBTOTAL = $SUBTOTAL;
        $delexvat = $delchrg;
    } elseif ($chrgvat == "inc") {
        $SUBTOTAL = sprint($SUBTOTAL * 100 / (100 + $VATP));
        $delexvat = sprint($delchrg * 100 / ($VATP + 100));
    } else {
        $SUBTOTAL = $SUBTOTAL;
        $delexvat = $delchrg;
    }
    $SUBTOT = $SUBTOTAL;
    $EXVATTOT = $SUBTOT;
    $EXVATTOT += $delexvat;
    # Minus trade discount from taxex
    if ($traddisc > 0) {
        $traddiscmtt = $traddisc / 100 * $taxex;
    } else {
        $traddiscmtt = 0;
    }
    $taxex -= $traddiscmtt;
    if ($traddisc > 0) {
        $traddiscmt = $EXVATTOT * ($traddisc / 100);
    } else {
        $traddiscmt = 0;
    }
    $EXVATTOT -= $traddiscmt;
    // $EXVATTOT -= $taxex;
    $traddiscmt = sprint($traddiscmt + $traddiscmtt);
    if ($chrgvat != "nov") {
        $VAT = sprint($EXVATTOT * ($VATP / 100));
    } else {
        $VAT = 0;
    }
    $TOTAL = sprint($EXVATTOT + $VAT + $taxex);
    $SUBTOT += $taxex;
    /* --- ----------- Clac --------------------- */
    # insert invoice to DB
    $sql = "UPDATE invoices SET cusnum = '{$cusnum}', deptname = '{$dept['deptname']}', cusacc = '{$cust['accno']}', cusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', cusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', docref = '{$docref}',\n\t\tchrgvat = '{$chrgvat}', terms = '{$terms}', salespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', comm = '{$comm}', serd = 'y', discount='{$traddiscmt}', delivery='{$delexvat}' WHERE invid = '{$invid}'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM inv_data WHERE invid='{$invid}'  AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF);
    # pu in new data
    $sql = "INSERT INTO inv_data(invid, dept, customer, addr1, div) VALUES('{$invid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '" . 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);
    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, "The bar code you selected is not in the system or is not available.");
            }
            $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 inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp,ss, div) VALUES('{$invid}', '{$s['whid']}', '{$stid}', '1','{$s['selamt']}','{$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);
            $Sl = "DELETE FROM " . $tab . " WHERE code = '{$bar}' AND div = '" . USER_DIV . "'";
            $Rs = db_exec($Sl);
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        } else {
            db_conn('cubit');
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $stid = ext_dbget('stock', 'bar', $bar, 'stkid');
            if (!($stid > 0)) {
                return details($_POST, "The bar code you selected is not in the system or is not available.");
            }
            $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 inv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp,ss, div) VALUES('{$invid}', '{$s['whid']}', '{$stid}', '1','{$s['selamt']}','{$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 inv_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);
        }
        # Insert quote to DB
        $sql = "UPDATE 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('invoice-print.php?invid={$invid}');move('main.php');</script>";
        require "template.php";
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t\t<tr><th>New Invoice Saved</th></tr>\n\t\t\t<tr class='bg-even'><td>Invoice for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</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='invoice-view.php'>View 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;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        if (strlen($ria) > 0) {
            $_POST['ria'] = $ria;
        }
        return details($_POST);
    }
    /* --- End button Listeners --- */
}
	include_once(dirname(__FILE__) . "/ressources/class.pdns.inc");
	include_once(dirname(__FILE__) . '/ressources/class.system.network.inc');
	include_once(dirname(__FILE__) . '/ressources/class.squid.inc');
	


	$users=new usersMenus();
	if(!$users->AsProxyMonitor){
		echo FATAL_ERROR_SHOW_128("{ERROR_NO_PRIVS}");
		die();
	}
	if(isset($_GET["graph-hour"])){graph_current_hour();exit;}
	if(isset($_GET["graph-hour-day"])){graph_current_hour_day();exit;}
	if(isset($_GET["graph-hour-month"])){graph_current_month_day();exit;}
	
	if(isset($_GET["details"])){details();exit;}
	if(isset($_GET["page"])){page();exit;}
	if(isset($_GET["cpustats"])){cpustats();exit;}

	
page();


function page(){
	$q=new mysql_squid_builder();
	$timekey=date('Ymd');
	$timekeyMonth=date("Ym");
	$time=time();
	$page=CurrentPageName();
	$tpl=new templates();
	$q=new mysql_squid_builder();
function write($_POST)
{
    #get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    # 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);
    }
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # check if Order has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : Order number <b>{$purid}</b> has already been received.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # remove items
    $sql = "DELETE FROM nons_pur_items WHERE purid='{$purid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Order items in Cubit.", SELF);
    # remove Order
    $sql = "DELETE FROM nons_purchases WHERE purid='{$purid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to remove Order items in Cubit.", SELF);
    # Insert record
    $sql = "INSERT INTO cancelled_purch(purnum, pdate, username, div) VALUES('{$pur['purnum']}', '{$pur['pdate']}', '" . USER_NAME . "', '{$pur['div']}')";
    $rslt = db_exec($sql) or errDie("Unable to remove Order items in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Layout
    $write = "\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Non-Stock Order Cancel</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Non-Stock Order from Supplier <b>{$pur['supplier']}</b> has been cancelled.</td>\n\t\t</tr>\n\t</table>\n\t<p>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='nons-purchase-view.php'>View Orders</a></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t</tr>\n\t</table>";
    return $write;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($budid, "num", 1, 20, "Invalid Budget id.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        return details($_POST, $confirm);
    }
    # Query server
    db_connect();
    $sql = "SELECT * FROM budgets WHERE budid = '{$budid}'";
    $budRslt = db_exec($sql) or errDie("Unable to retrieve Budgets from database.");
    if (pg_numrows($budRslt) < 1) {
        return "<li class=err> - Invalid Budget.";
    }
    $bud = pg_fetch_array($budRslt);
    require "budget.lib.php";
    $vbudfor = $BUDFOR[$bud['budfor']];
    $vbudtype = $TYPES[$bud['budtype']];
    $vfromyr = $YEARS[$bud['fromprd']];
    $vtoyr = $YEARS[$bud['toprd']];
    db_connect();
    # delete budget
    $rs = db_exec("DELETE FROM buditems WHERE budid = '{$budid}'");
    $rs = db_exec("DELETE FROM budgets WHERE budid = '{$budid}'");
    // Start layout
    $write = "<center>\r\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=500>\r\n\t\t<tr><th colspan=2>Remove Yearly Budget</th></tr>\r\n\t\t<tr><td class='bg-odd' colspan=2>Yearly Budget <b>{$bud['budname']}</b> has been removed.</td></tr>\r\n\t</table>\r\n\t<p>\r\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=25%>\r\n\t\t<tr><th>Quick Links</th></tr>\r\n\t\t<tr class='bg-odd'><td align=center><a href='budget-view.php'>View Budgets</td></tr>\r\n\t\t<tr class='bg-odd'><td align=center><a href='../main.php'>Main Menu</td></tr>\r\n\t</table>";
    return $write;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $ddate = $dyear . "-" . $dmon . "-" . $dday;
    if (!checkdate($dmon, $dday, $dyear)) {
        $v->isOk($ddate, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qtys[$keys], "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitamts[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($stkacc[$keys], "num", 1, 10, "Invalid Item Account number : <b>" . ($keys + 1) . "</b>");
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : no products selected.");
    }
    $prd += 0;
    # 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);
    }
    # Get Order info
    db_conn($prd);
    $sql = "SELECT * FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get supplier");
    if (pg_numrows($supRslt) < 1) {
        $error = "<li class='err'> Supplier not Found.</li>";
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    } else {
        $sup = pg_fetch_array($supRslt);
        $pur['supplier'] = $sup['supname'];
        $pur['supaddr'] = $sup['supaddr'];
        # Get department info
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$sup['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            return "<i class='err'>Department Not Found</i>";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $supacc = $dept['credacc'];
    }
    # Insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_connect();
    # Update all supplies xchange rate first
    xrate_update($pur['fcid'], $pur['xrate'], "suppurch", "id");
    sup_xrate_update($pur['fcid'], $pur['xrate']);
    db_connect();
    $retax = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            db_conn($prd);
            $sql = "SELECT * FROM nons_purint_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # the unitcost + delivery charges * qty
            $famt[$keys] = sprint($unitamts[$keys] * $qtys[$keys]);
            # calculate tax
            $ftaxes[$keys] = svat($famt[$keys], $pur['subtot'], $pur['tax']);
            $amt[$keys] = sprint($unitamts[$keys] * $pur['xrate'] * $qtys[$keys]);
            # calculate tax
            $retax += sprint($ftaxes[$keys] * $pur['xrate']);
            # Update Order items
            $sql = "UPDATE nons_purint_items SET rqty = (rqty + '{$qtys[$keys]}'), accid = '{$stkacc[$keys]}' WHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            # keep records for transactions
            if (isset($totstkamt[$stkacc[$keys]])) {
                $totstkamt[$stkacc[$keys]] += $amt[$keys];
            } else {
                $totstkamt[$stkacc[$keys]] = $amt[$keys];
            }
        }
    }
    /* Transactions */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $refnum = getrefnum();
    $sdate = $pur["pdate"];
    //$ddate;
    /* - End Hooks - */
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        # Debit Stock and Credit Suppliers control
        writetrans($supacc, $stkacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. {$pur['purnum']} Returned to Supplier {$sup['supname']}.");
    }
    db_connect();
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['cusid']}'";
    $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 ($retax > 0) {
        writetrans($supacc, $vatacc, date("d-m-Y"), $refnum, $retax, "Returned, Non-Stock Purchase Vat paid on Non-Stock Order No. {$pur['purnum']}.");
    }
    $retot = sprint(array_sum($amt) + $retax);
    vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Returned, Non-Stock Purchase Vat paid on Non-Stock Order No. {$pur['purnum']}.", $retot, $retax);
    $fretot = sprint(array_sum($famt) + array_sum($ftaxes));
    suppledger($sup['supid'], $stkacc, $sdate, $pur['purid'], "Returned, Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'd');
    db_connect();
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance - '{$retot}'), fbalance = (fbalance - '{$fretot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$sup['supid']}','{$sdate}', '{$dept['credacc']}', '-{$fretot}','Returned, Non Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}','" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    db_connect();
    # make transaction record for age analysis
    $sql = "INSERT INTO suppurch(supid, purid, pdate, fcid, balance, fbalance, div) VALUES('{$sup['supid']}', '{$pur['purnum']}', '{$sdate}', '{$pur['fcid']}', '-{$retot}', '-{$fretot}', '" . USER_DIV . "')";
    $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    db_conn($prd);
    # check if there are any outstanding items
    $sql = "SELECT * FROM nons_purint_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # if none the set to received
    if (pg_numrows($stkdRslt) < 1) {
        # update surch_int(received = 'y')
        $sql = "UPDATE nons_purch_int SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        //$rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.",SELF);
    }
    # Update Order on the DB
    $sql = "UPDATE nons_purch_int SET refno = '{$refno}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.",SELF);
    /* End Transactions */
    /* Start moving if Order received */
    db_conn($prd);
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $sql = "SELECT * FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $rdate = date("Y-m-d");
    # copy Order
    db_conn($prd);
    $sql = "INSERT INTO rnons_purch_int(purid, deptid, supid, supplier, supaddr, terms, pdate, ddate, shipchrg, xrate, fcid, curr, currency, shipping, subtot, total, balance, tax, remarks, refno, received, done, div, purnum, rdate)";
    $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['xrate']}', '{$pur['fcid']}', '{$pur['curr']}', '{$pur['currency']}', '{$pur['shipping']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['tax']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}', '{$rdate}')";
    $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Order to Cubit.", SELF);
    db_connect();
    db_conn($prd);
    # get selected stock
    $sql = "SELECT * FROM nons_purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stktcRslt = db_exec($sql);
    while ($stktc = pg_fetch_array($stktcRslt)) {
        # Insert Order items
        db_conn($prd);
        $sql = "INSERT INTO rnons_purint_items(purid, cod, des, qty, unitcost, cunitcost, duty, dutyp, amt, accid, div) VALUES('{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['cunitcost']}', '{$stktc['duty']}', '{$stktc['dutyp']}', '{$stktc['amt']}', '{$stktc['accid']}', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
    }
    db_connect();
    # Remove the Order from running DB
    $sql = "DELETE FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.",SELF);
    # Remove those Order items from running DB
    $sql = "DELETE FROM nons_purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.",SELF);
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving Order received */
    $cc = "<script> CostCenter('dt', 'Returned, International Non-Stock Purchase', '{$pur['pdate']}', 'Returned, Non Stock Purchase No.{$pur['purnum']}', '" . sprint($retot - $retax) . "', ''); </script>";
    // Final Layout
    $write = "{$cc}\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>International Non-Stock Order received</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>International Non-Stock Order receipt has been recorded.</td>\n\t\t</tr>\n\t</table>\n\t<p>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='nons-purch-int-view.php'>View International Orders</a></td>\n\t\t</tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    if (!isset($cusnum)) {
        return details(array(), "<li class='err'>Invalid Customer</li>");
        //$cusnum = "";
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($calloutid, "num", 1, 20, "Invalid Callout Document Number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($def_travel, "string", 0, 255, "Invalid Default Travel.");
    $v->isOk($def_labour, "string", 0, 255, "Invalid Default Labour.");
    $v->isOk($calloutdescrip, "string", 0, 255, "Invalid Callout Description.");
    $v->isOk($sign, "string", 0, 255, "Invalid Sign Data.");
    $v->isOk($calloutp, "string", 1, 255, "Invalid sales person.");
    $v->isOk($call_day, "num", 1, 2, "Invalid Service Date day.");
    $v->isOk($call_month, "num", 1, 2, "Invalid Service Date month.");
    $v->isOk($call_year, "num", 1, 5, "Invalid Service Date year.");
    $odate = $call_year . "-" . $call_month . "-" . $call_day;
    if (!checkdate($call_month, $call_day, $call_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid callout Document Date.");
    }
    //	$v->isOk ($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    # used to generate errors
    $error = "asa@";
    # 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>.");
    //			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.");
        }
    }
    # 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.");
        }
    }
    # 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);
    }
    # Get callout document info
    db_connect();
    $sql = "SELECT * FROM callout_docs WHERE calloutid = '{$calloutid}' AND div = '" . USER_DIV . "'";
    $docRslt = db_exec($sql) or errDie("Unable to get callout document information");
    if (pg_numrows($docRslt) < 1) {
        return "<li>- Callout Document Not Found</li>";
    }
    $doc = pg_fetch_array($docRslt);
    # check if callout document has been printed
    if ($doc['accepted'] == "y") {
        $error = "<li class='err'>Error : Callout Document number <b>{$calloutid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM callout_docs_data WHERE calloutid = '{$calloutid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        $doc['deptid'] = $cust['deptid'];
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$doc['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);
    }
    # insert callout document 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 callout document
    $sql = "SELECT * FROM cubit.callout_docs_items WHERE calloutid = '{$calloutid}' 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]'";
    #	$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    #}
    # remove old items
    $sql = "DELETE FROM cubit.callout_docs_items WHERE calloutid='{$calloutid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update callout document items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod) && in_array($keys, $remprod)) {
            } elseif (isset($accounts[$keys]) && $accounts[$keys] != 0) {
                $accounts[$keys] += 0;
                # Get selamt from selected stock
                $Sl = "SELECT * FROM core.accounts WHERE accid='{$accounts[$keys]}'";
                $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                $ad = pg_fetch_array($Ri);
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                $accounts[$keys] += 0;
                $descriptions[$keys] = remval($descriptions[$keys]);
                $wtd = $whids[$keys];
                # insert invoice items
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.callout_docs_items (\n\t\t\t\t\t\tcalloutid, whid, stkid, qty, \n\t\t\t\t\t\tunitcost, amt, div, \n\t\t\t\t\t\tdescription, account\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$calloutid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', \n\t\t\t\t\t\t'{$unitcost[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "', \n\t\t\t\t\t\t'{$descriptions[$keys]}','{$accounts[$keys]}'\n\t\t\t\t\t)";
                $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 amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                $wtd = $whids[$keys];
                # insert callout document items
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.callout_docs_items (\n\t\t\t\t\t\tcalloutid, whid, stkid, qty, \n\t\t\t\t\t\tunitcost, amt, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$calloutid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', \n\t\t\t\t\t\t'{$unitcost[$keys]}','{$amt[$keys]}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert callout document items to Cubit.", SELF);
                # update stock(alloc + qty)
                # $sql = "UPDATE stock SET alloc = (alloc + '$qtys[$keys]') WHERE stkid = '$stkids[$keys]'";
                # $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='Done'>";
        }
    } else {
        $_POST["done"] = "";
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $subtotal = sprint($sub);
    $SUBTOT = $sub;
    $TOTAL = $subtotal;
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    # insert callout documents to DB
    $sql = "\n\t\tUPDATE callout_docs \n\t\tSET cusnum = '{$cusnum}', deptid = '{$dept['deptid']}', deptname = '{$dept['deptname']}', cusacc = '{$cust['accno']}', \n\t\t\tcusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\tcusvatno = '{$cust['vatnum']}', calloutp = '{$calloutp}', odate = '{$odate}', subtot = '{$SUBTOT}', comm = '{$comm}', \n\t\t\tcalloutdescrip = '{$calloutdescrip}', sign = '{$sign}', def_travel = '{$def_travel}', def_labour = '{$def_labour}' \n\t\tWHERE calloutid = '{$calloutid}'";
    $rslt = db_exec($sql) or errDie("Unable to update callout document in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM callout_docs_data WHERE calloutid='{$calloutid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update callout document data in Cubit.", SELF);
    # pu in new data
    $sql = "\n\t\tINSERT INTO callout_docs_data (\n\t\t\tcalloutid, dept, customer, \n\t\t\taddr1, div\n\t\t) VALUES (\n\t\t\t'{$calloutid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', \n\t\t\t'{$cust['addr1']}', '" . USER_DIV . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert callout document data to Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($doneBtn)) {
        # insert callout document to DB
        $sql = "UPDATE callout_docs SET done = 'y' WHERE calloutid = '{$calloutid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update callout document 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 Callout Document</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Callout Document for client <b>{$cust['cusname']} {$cust['surname']}</b> has been recorded.</td>\n\t\t\t\t\t<td><a target='_blank' href='callout-print.php?calloutid={$calloutid}'>Print Callout Document</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<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New Callout Document Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Callout Document for client <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</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='callout-view.php'>View Callout Documents</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;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        return details($_POST);
    }
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (!isset($cusnum)) {
        return details($_POST, "<li class='err'>Please select a customer.</li>");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($cusnum)) {
        $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    }
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    if (isset($cordno)) {
        $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    }
    if (!isset($ria)) {
        $ria = "";
    }
    $v->isOk($ria, "string", 0, 20, "Invalid stock code(fist letters).");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($docref, "string", 0, 20, "Invalid Document Reference No.");
    $v->isOk($ordno, "string", 0, 20, "Invalid sales order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($rinv_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($rinv_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($rinv_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $rinv_year . "-" . $rinv_month . "-" . $rinv_day;
    if (!checkdate($rinv_month, $rinv_day, $rinv_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.");
    # 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 quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "float", 1, 15, "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>.");
            if ($discp[$keys] > 100) {
                $v->isOk($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than 100 %.");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty <= 0) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be more than zero. 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.");
        }
    }
    # 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.");
        }
    }
    # 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);
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM rec_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</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['chrgvat'] = $chrgvat;
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM inv_data WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        $inv['deptid'] = $cust['deptid'];
        # If customer was just selected, get the following
        if ($inv['cusnum'] == 0) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
        }
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['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 recinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    # remove old items
    $sql = "DELETE FROM recinv_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) && in_array($keys, $remprod)) {
            } elseif (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);
                # Calculate amount
                $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 = "\n\t\t\t\t\t\tINSERT INTO recinv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\t\tamt, disc, discp,  div, vatcode, \n\t\t\t\t\t\t\tdescription, account\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t\t'{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '" . USER_DIV . "', '{$vatcodes[$keys]}', \n\t\t\t\t\t\t\t'{$descriptions[$keys]}', '{$accounts[$keys]}'\n\t\t\t\t\t\t)";
                $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];
                if (!isset($sernos[$keys])) {
                    $sernos[$keys] = "";
                }
                # insert invoice items
                $sql = "\n\t\t\t\t\t\tINSERT INTO recinv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\t\tamt, disc, discp, serno, div, \n\t\t\t\t\t\t\tvatcode\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t\t'{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '{$sernos[$keys]}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$vatcodes[$keys]}'\n\t\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'>";
        }
    } 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 = $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 = $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);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    db_conn('cubit');
    $Sl = "SELECT * FROM costcenters";
    $Ri = db_exec($Sl);
    $i = 0;
    $Sl = "DELETE FROM invc WHERE inv='{$invid}'";
    $Rl = db_exec($Sl);
    while ($data = pg_fetch_array($Ri)) {
        if ($ct[$data['ccid']] > 0) {
            $Sl = "INSERT INTO invc (cid,inv,amount) VALUES ('{$data['ccid']}','{$invid}','" . $ct[$data['ccid']] . "')";
            $Rl = db_exec($Sl);
        }
        $i++;
    }
    /* --- ----------- Clac ---------------------
    
    		# calculate subtot
    		$SUBTOT = 0.00;
    		if(isset($amt))
    			$SUBTOT = array_sum($amt);
    
    		$SUBTOT -= $taxex;
    
    		# duplicate
    		$SUBTOTAL = $SUBTOT;
    
    		$VATP = TAX_VAT;
    		if($chrgvat == "exc"){
    			$SUBTOTAL = $SUBTOTAL;
    			$delexvat= ($delchrg);
    		}elseif($chrgvat == "inc"){
    			$SUBTOTAL = sprint(($SUBTOTAL * 100)/(100 + $VATP));
    			$delexvat = sprint(($delchrg * 100)/($VATP + 100));
    		}else{
    			$SUBTOTAL = ($SUBTOTAL);
    			$delexvat = ($delchrg);
    		}
    
    		$SUBTOT = $SUBTOTAL;
    		$EXVATTOT = $SUBTOT;
    		$EXVATTOT += $delexvat;
    
    		# Minus trade discount from taxex
    		if($traddisc > 0){
    			$traddiscmtt = (($traddisc/100) * $taxex);
    		}else{
    			$traddiscmtt = 0;
    		}
    		$taxext = ($taxex - $traddiscmtt);
    
    		if($traddisc > 0) {
    			$traddiscmt = ($EXVATTOT * ($traddisc/100));
    		}else{
    			$traddiscmt = 0;
    		}
    		$EXVATTOT -= $traddiscmt;
    		// $EXVATTOT -= $taxex;
    
    		$traddiscmt = sprint($traddiscmt  + $traddiscmtt);
    
    		if($chrgvat != "nov"){
    			$VAT = sprint($EXVATTOT * ($VATP/100));
    		}else{
    			$VAT = 0;
    		}
    
    		$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    		$SUBTOT += $taxex;
    
    /* --- ----------- Clac --------------------- */
    # insert invoice to DB
    $sql = "\n\t\t\tUPDATE rec_invoices \n\t\t\tSET delvat='{$delvat}', cusnum = '{$cusnum}', deptid = '{$dept['deptid']}', deptname = '{$dept['deptname']}', \n\t\t\t\tcusacc = '{$cust['accno']}', cusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\t\tcusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', docref = '{$docref}',\n\t\t\t\tchrgvat = '{$chrgvat}', terms = '{$terms}', salespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', \n\t\t\t\tdelchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', \n\t\t\t\tcomm = '{$comm}', serd = 'y', discount='{$traddiscmt}', delivery='{$delexvat}' \n\t\t\tWHERE invid = '{$invid}'";
    $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 (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, "<a href='pos-set.php'>Please set the point of sale setting by clicking here.</a>");
        }
        $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, "The bar code you selected is not in the system or is not available.");
            }
            $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 = "\n\t\t\t\tINSERT INTO recinv_items (\n\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp, ss, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$invid}', '{$s['whid']}', '{$stid}', '1','{$s['selamt']}', '{$s['selamt']}', '0', '0', '{$bar}', '" . USER_DIV . "'\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);
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        } else {
            db_conn('cubit');
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $stid = ext_dbget('stock', 'bar', $bar, 'stkid');
            if (!($stid > 0)) {
                return details($_POST, "The bar code you selected is not in the system or is not available.");
            }
            $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 = "\n\t\t\t\tINSERT INTO recinv_items (\n\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp,ss, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$invid}', '{$s['whid']}', '{$stid}', '1', '{$s['selamt']}', '{$s['selamt']}', '0', '0', '{$bar}',  '" . USER_DIV . "'\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);
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        }
    }
    /* --- Start button Listeners --- */
    if (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Recurring Invoice Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Recurring Invoice for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</td>\n\t\t\t\t</tr>\n\t\t\t</table>" . mkQuickLinks(ql("rec-invoice-view.php", "View Recurring Invoices"), ql("customers-new.php", "New Customer"));
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        if (strlen($ria) > 0) {
            $_POST['ria'] = $ria;
        }
        return details($_POST);
    }
    /* --- End button Listeners --- */
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    if (!isset($ria)) {
        $ria = "";
    }
    $v->isOk($ria, "string", 0, 20, "Invalid stock code(fist letters).");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($docref, "string", 0, 20, "Invalid Document Reference No.");
    $v->isOk($ordno, "num", 0, 20, "Invalid sales order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($o_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($o_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($o_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $o_year . "-" . $o_month . "-" . $o_day;
    if (!checkdate($o_month, $o_day, $o_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.");
    # 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 serai 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, "float", 1, 15, "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>.");
            if ($discp[$keys] > 100) {
                $v->isOk($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than 100 %.");
            }
            $unitcost[$keys] += 0;
            $cunitcost[$keys] += 0;
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($cunitcost[$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.");
        }
    }
    # 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.");
        }
    }
    # 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);
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM 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</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;
    }
    db_connect();
    if (isset($printdel)) {
        $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('Delivery Note','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='Delivery Note' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='Delivery Note' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM inv_data WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
        # currency
        $currs = getSymbol($inv['fcid']);
    } else {
        $cust = pg_fetch_array($custRslt);
        # If customer was just selected/changed, get the following
        if ($inv['cusnum'] != $cusnum) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
            $xrate = getRate($cust['fcid']);
        }
        # currency
        $currs = getSymbol($cust['fcid']);
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['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
    $xrate += 0;
    if ($xrate == 0) {
        $xrate = 1;
    }
    $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 inv_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 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) && in_array($keys, $remprod)) {
                // 				if(isset($remprod)){
                // 					if(in_array($keys, $remprod)){
                // 						# skip product (wonder if $keys still align)
                // 						$amt[$keys] = 0;
                // 						continue;
                // 					}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);
                //
                // 						$t=$cunitcost[$keys];
                //
                // 						# Calculate the unitcost
                // 						if($cunitcost[$keys] > 0 && $unitcost[$keys] == 0){
                // 							$unitcost[$keys] = ($cunitcost[$keys] * $xrate);
                // 						}else{
                // 							$cunitcost[$keys] = ($unitcost[$keys]/$xrate);
                // 						}
                //
                // 						# Calculate the Discount discount
                // 						if($disc[$keys] < 1){
                // 							if($discp[$keys] > 0){
                // 								$disc[$keys] = (($discp[$keys]/100) * $t);
                // 							}
                // 						}else{
                // 							$discp[$keys] = (($disc[$keys] * 100) / $t);
                // 						}
                //
                // 						# Calculate amount
                // 						$funitcost[$keys] = $unitcost[$keys];
                // 						$famt[$keys] = ($qtys[$keys] * ($funitcost[$keys]));
                //
                // 						# Calculate amount
                // 						// $amt[$keys] = ($qtys[$keys] * ($unitcost[$keys] - $disc[$keys]));
                // 						$unitcost[$keys] = sprint($funitcost[$keys]/$xrate);
                // 						$amt[$keys] = sprint($famt[$keys]/$xrate-($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);
                //
                // 						# Check Tax Excempt
                // 						if($stk['exvat'] == 'yes'||$vd['zero']=="Yes"){
                // 							$taxex += $amt[$keys];
                // 						}
                //
                // 						# insert invoice items
                // 						$sql = "INSERT INTO inv_items(invid, whid, stkid, qty, unitcost, funitcost, amt, famt, disc, discp, serno, div,vatcode,del) VALUES('$invid', '$whids[$keys]', '$stkids[$keys]', '$qtys[$keys]', '$unitcost[$keys]', '$funitcost[$keys]', '$amt[$keys]', '$famt[$keys]', '$disc[$keys]', '$discp[$keys]', '$sernos[$keys]', '".USER_DIV."','$vatcodes[$keys]','0')";
                // 						$rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.",SELF);
                //
                // 						if(strlen($stkt['serno']) > 0)
                // 							ext_resvSer($stkt['serno'], $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);
                // 					}
            } 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 unitcost
                		if($cunitcost[$keys] > 0 && $unitcost[$keys] == 0){
                			$unitcost[$keys] = ($cunitcost[$keys] * $xrate);
                		}else{
                			$cunitcost[$keys] = ($unitcost[$keys]/$xrate);
                		}*/
                $t = $cunitcost[$keys];
                # Calculate the unitcost
                if ($unitcost[$keys] > 0 && $cunitcost[$keys] == 0) {
                    $cunitcost[$keys] = $unitcost[$keys] / $xrate;
                } else {
                    $unitcost[$keys] = $cunitcost[$keys] * $xrate;
                }
                # Calculate the Discount discount
                if ($disc[$keys] < 1) {
                    if ($discp[$keys] > 0) {
                        $disc[$keys] = $discp[$keys] / 100 * $t;
                    }
                } else {
                    $discp[$keys] = $disc[$keys] * 100 / $t;
                }
                if ($xrate < 1) {
                    $xrate = 1;
                }
                //$disc[$keys]=$disc[$keys]*$xrate;
                # Calculate amount
                $funitcost[$keys] = $unitcost[$keys];
                $famt[$keys] = $qtys[$keys] * $funitcost[$keys];
                //$famt[$keys] = ($qtys[$keys] * ($funitcost[$keys] - $disc[$keys]));
                # Calculate amount
                // $amt[$keys] = ($qtys[$keys] * ($unitcost[$keys] - $disc[$keys]));
                $unitcost[$keys] = sprint($funitcost[$keys] / $xrate);
                $amt[$keys] = sprint($famt[$keys] / $xrate - $disc[$keys]);
                //$amt[$keys] = sprint($famt[$keys]/$xrate);
                $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];
                }
                # insert invoice items
                $sql = "\n\t\t\t\t\t\tINSERT INTO inv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\t\tfunitcost, amt, famt, disc, \n\t\t\t\t\t\t\tdiscp, serno, div, vatcode, del\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t\t'{$funitcost[$keys]}', '{$amt[$keys]}', '{$famt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', \n\t\t\t\t\t\t\t'{$sernos[$keys]}', '" . USER_DIV . "', '{$vatcodes[$keys]}', '0'\n\t\t\t\t\t\t)";
                $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);
    $vd = pg_fetch_array($Ri);
    // 		if(pg_num_rows($Ri)>0) {
    // 			$taxex += $delchrg;
    // 		}
    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 = $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 = $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);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- ----------- Clac ---------------------
    
    		# calculate subtot
    		$SUBTOT = 0.00;
    		if(isset($amt))
    			$SUBTOT = array_sum($amt);
    
    		$SUBTOT -= $taxex;
    
    		# duplicate
    		$SUBTOTAL = $SUBTOT;
    
    		$VATP = TAX_VAT;
    		if($chrgvat == "exc"){
    			$SUBTOTAL = $SUBTOTAL;
    			$delexvat= ($delchrg);
    		}elseif($chrgvat == "inc"){
    			$SUBTOTAL = sprint(($SUBTOTAL * 100)/(100 + $VATP));
    			$delexvat = sprint(($delchrg * 100)/($VATP + 100));
    		}else{
    			$SUBTOTAL = ($SUBTOTAL);
    			$delexvat = ($delchrg);
    		}
    
    		$SUBTOT = $SUBTOTAL;
    		$EXVATTOT = $SUBTOT;
    		$EXVATTOT += $delexvat;
    
    		# Minus trade discount from taxex
    		if($traddisc > 0){
    			$traddiscmtt = (($traddisc/100) * $taxex);
    		}else{
    			$traddiscmtt = 0;
    		}
    		$taxext = ($taxex - $traddiscmtt);
    
    		if($traddisc > 0) {
    			$traddiscmt = ($EXVATTOT * ($traddisc/100));
    		}else{
    			$traddiscmt = 0;
    		}
    		$EXVATTOT -= $traddiscmt;
    		// $EXVATTOT -= $taxex;
    
    		$traddiscmt = sprint($traddiscmt  + $traddiscmtt);
    
    		if($chrgvat != "nov"){
    			$VAT = sprint($EXVATTOT * ($VATP/100));
    		}else{
    			$VAT = 0;
    		}
    
    		$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    		$SUBTOT += $taxex;
    
    /* --- ----------- Clac --------------------- */
    $FTOTAL = sprint($TOTAL * $xrate);
    /* --- ----------- Clac --------------------- */
    # insert invoice to DB
    $sql = "\n\t\t\tUPDATE invoices \n\t\t\tSET delvat='{$delvat}', cusnum = '{$cusnum}', deptname = '{$dept['deptname']}', cusacc = '{$cust['accno']}', \n\t\t\t\tcusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\t\tcusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', chrgvat = '{$chrgvat}', docref = '{$docref}', \n\t\t\t\tterms = '{$terms}', salespn = '{$salespn}', fcid = '{$cust['fcid']}', currency = '{$currs['symbol']}', xrate = '{$xrate}', \n\t\t\t\todate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', \n\t\t\t\ttotal = '{$TOTAL}', balance = '{$FTOTAL}', fbalance = '{$TOTAL}', comm = '{$comm}', location = '{$cust['location']}', \n\t\t\t\tserd = 'y', discount='{$traddiscmt}', delivery='{$delexvat}' \n\t\t\tWHERE invid = '{$invid}'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM inv_data WHERE invid='{$invid}'  AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF);
    # pu in new data
    $sql = "INSERT INTO inv_data(invid, dept, customer, addr1, div) VALUES('{$invid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '" . 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);
    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, "<a href='pos-set.php'>Please set the point of sale setting by clicking here.</a>");
        }
        $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, "The bar code you selected is not in the system or is not available.");
            }
            $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 = "\n\t\t\t\tINSERT INTO inv_items (\n\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp,ss, div, del\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$invid}', '{$s['whid']}', '{$stid}', '1', '{$s['selamt']}', '{$s['selamt']}', '0', '0', '{$bar}', '" . USER_DIV . "', '0'\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);
            pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        } else {
            db_conn('cubit');
            pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
            $stid = ext_dbget('stock', 'bar', $bar, 'stkid');
            if (!($stid > 0)) {
                return details($_POST, "The bar code you selected is not in the system or is not available.");
            }
            $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 = "\n\t\t\t\tINSERT INTO inv_items (\n\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp,ss, div, del\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$invid}', '{$s['whid']}', '{$stid}', '1', '{$s['selamt']}', '{$s['selamt']}', '0', '0','{$bar}', '" . USER_DIV . "', '0'\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);
            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 inv_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.</li>";
            return details($_POST, $error);
        }
        # Insert quote to DB
        $sql = "UPDATE 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);
        $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        $data = pg_fetch_array($Ri);
        if ($data['value'] == "Yes") {
            # Print the invoice
            $OUTPUT = "<script>nhprinter('invoice-delnote.php?invid={$invid}','Delivery Note');printer('intinvoice-print.php?invid={$invid}');move('main.php');</script>";
        } else {
            # Print the invoice
            $OUTPUT = "<script>printer('intinvoice-print.php?invid={$invid}');move('main.php');</script>";
        }
        require "template.php";
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New International Invoice Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>International Invoice for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</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='invoice-view.php'>View 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;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        if (strlen($ria) > 0) {
            $_POST['ria'] = $ria;
        }
        return details($_POST);
    }
}
function write($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($cordno, "num", 0, 20, "Invalid Customer Order Number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($ordno, "num", 0, 20, "Invalid order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($oday, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($omon, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($oyear, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $oyear . "-" . $omon . "-" . $oday;
    if (!checkdate($omon, $oday, $oyear)) {
        $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.");
    # used to generate errors
    $error = "asa@";
    # 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($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>.");
            if ($discp[$keys] > 100) {
                $v->isOk($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than 100 %.");
            }
            $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.");
        }
    }
    # 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.");
        }
    }
    # 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 invoice info
    db_connect();
    $sql = "SELECT * FROM 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</li>";
    }
    $inv = pg_fetch_array($invRslt);
    # 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 selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($custRslt) < 1) {
        $sql = "SELECT * FROM inv_data WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to get customer information data");
        $cust = pg_fetch_array($custRslt);
        $cust['cusname'] = $cust['customer'];
        $cust['surname'] = "";
        $cust['addr1'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['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;
    # 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
    db_connect();
    $sql = "SELECT * FROM inv_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);
    }
    # remove old items
    $sql = "DELETE FROM 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($stkids)) {
        foreach ($stkids as $keys => $value) {
            if (isset($remprod)) {
                if (in_array($keys, $remprod)) {
                    # skip product (wonder if $keys still align)
                    $amt[$keys] = 0;
                    continue;
                } 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]);
                    # Check Tax Excempt
                    if ($stk['exvat'] == 'yes') {
                        $taxex += $amt[$keys];
                    }
                    # insert invoice items
                    $sql = "INSERT INTO inv_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);
                    # 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);
                }
            } 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]);
                $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]);
                if ($stk['exvat'] == 'yes') {
                    $taxex += $amt[$keys];
                }
                # insert invoice items
                $sql = "INSERT INTO inv_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);
                # 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='Done'>";
        }
    } else {
        $_POST["done"] = "";
    }
    /* --- Clac --- */
    # calculate subtot
    if (isset($amt)) {
        $SUBTOT = array_sum($amt);
    } else {
        $SUBTOT = 0.0;
    }
    # Calculate tradediscm
    if ($traddisc > 0) {
        $traddiscm = round($traddisc / 100 * $SUBTOT, 2);
    } else {
        $traddiscm = 0;
    }
    /* Trade discount fix */
    # Calculate tradediscm
    if ($traddisc > 0) {
        $traddiscmt = sprint($traddisc / 100 * $taxex);
    } else {
        $traddiscmt = 0.0;
    }
    $taxex -= $traddiscmt;
    /* Trade discount fix */
    # minus discount
    # $SUBTOT -= $disc; --> already minused
    # duplicate
    $SUBTOTAL = $SUBTOT;
    # minus trade discount
    $SUBTOTAL -= $traddiscm;
    # add del charge
    $SUBTOTAL += $delchrg;
    # If vat must be charged
    if ($chrgvat == "exc") {
        $VATP = TAX_VAT;
        $VAT = sprint($VATP / 100 * ($SUBTOTAL - $taxex));
    } elseif ($chrgvat == "inc") {
        $VATP = TAX_VAT;
        $VAT = sprint(($SUBTOTAL - $taxex) / ($VATP + 100) * $VATP);
    } else {
        $VATP = 0;
        $VAT = "0.00";
    }
    # total
    if ($chrgvat == "exc") {
        $TOTAL = sprint($SUBTOTAL + $VAT);
    } else {
        $TOTAL = sprint($SUBTOTAL);
        $SUBTOT = sprint($SUBTOT - $VAT);
    }
    /* --- End Clac --- */
    # insert invoice to DB
    $sql = "UPDATE invoices SET cusnum = '{$cusnum}', deptname = '{$dept['deptname']}', cusacc = '{$cust['accno']}', cusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', cusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', chrgvat = '{$chrgvat}', terms = '{$terms}', salespn = '{$salespn}',\n\t\todate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', comm = '{$comm}' WHERE invid = '{$invid}'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM inv_data WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF);
    # pu in new data
    $sql = "INSERT INTO inv_data(invid, dept, customer, addr1, div) VALUES('{$invid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '" . 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);
    /* --- Start button Listeners --- */
    if (isset($doneBtn)) {
        # check if stock was selected(yes = put done button)
        db_connect();
        $sql = "SELECT stkid FROM inv_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);
        }
        # insert quote to DB
        $sql = "UPDATE 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
        header("Location:invoice-print.php?invid={$invid}");
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t\t<tr><th>New Invoice Saved</th></tr>\n\t\t\t<tr class='bg-even'><td>Invoice for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved.</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='invoice-view.php'>View Invoices</a></td></tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
        return $write;
    } else {
        return details($_POST);
    }
    /* --- End button Listeners --- */
}
Example #26
0
function process($cmds, $rig)
{
    global $error, $devs;
    global $warnfont, $warnoff;
    $count = count($cmds);
    foreach ($cmds as $cmd => $des) {
        $process = api($rig, $cmd);
        if ($error != null) {
            otherrow("<td colspan=100>Error getting {$des}: {$warnfont}{$error}{$warnoff}</td>");
            break;
        } else {
            details($cmd, $process, $rig);
            if ($cmd == 'devs') {
                $devs = $process;
            }
            if ($cmd == 'pools') {
                showpoolinputs($rig, $process);
            }
            # Not after the last one
            if (--$count > 0) {
                otherrow('<td><br><br></td>');
            }
        }
    }
}
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 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;
    }
}
#
#
#
#
#
#
#
#
#
# Get settings
require "settings.php";
require "core-settings.php";
require "libs/ext.lib.php";
# Decide what to do
if (isset($_GET["invid"])) {
    $OUTPUT = details($_GET);
} else {
    $OUTPUT = "<li class=err>Invalid use of module.";
}
# Get templete
require "template.php";
# Details
function details($_GET)
{
    # get vars
    foreach ($_GET as $key => $value) {
        ${$key} = $value;
    }
    $prd += 0;
    # validate input
    require_lib("validate");
function recvpayment_write()
{
    if (isset($_POST["btn_back"])) {
        return details($_POST);
    }
    extract($_POST);
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 10, "Invalid customer id.");
    $v->isOk($bank_acc, "num", 1, 10, "Invalid cash account selected.");
    $v->isOk($pcc, "float", 1, 40, "Invalid credit card amount.");
    $v->isOk($pcash, "float", 1, 40, "Invalid cash amount.");
    $v->isOk($pcheque, "float", 1, 40, "Invalid cheque amount.");
    $v->isOk($amt, "float", 1, 40, "Invalid total received amount.");
    $v->isOk($out, "float", 1, 40, "Invalid unallocated amount.");
    $v->isOk($descript, "string", 1, 255, "Invalid description.");
    $v->isOk($date, "date", 1, 1, "Invalid invoice date.");
    if ($v->isError()) {
        return details($_POST, $v->genErrors());
    }
    $sdate = $date;
    $cus = qryCustomer($cusnum);
    $dept = qryDepartment($cus["deptid"], "debtacc");
    $refnum = getrefnum();
    pglib_transaction("BEGIN");
    /* do the calculations/recordings */
    # update the customer (make balance less)
    $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt}'::numeric(13,2))\n\t\t\tWHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $ii = $invids[$key];
            /* OPTION 1: STOCK INVOICES */
            if (!isset($itype[$ii]) && !isset($ptype[$ii])) {
                $sql = "SELECT prd,invnum,odate FROM cubit.invoices\n\t\t\t\t\t\tWHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class=err>Invalid Invoice Number.";
                }
                $inv = pg_fetch_array($invRslt);
                $inv['invnum'] += 0;
                // reduce invoice balance
                $sql = "UPDATE cubit.invoices\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt \n\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}', '" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                if ($inv['prd'] == "0") {
                    $inv['prd'] = PRD_DB;
                }
                $invprds .= "|{$inv['prd']}";
                $rages .= "|0";
                $invidsers .= " - {$inv['invnum']}";
                /* OPTION 1: NONS STOCK INVOICES */
            } else {
                if (!isset($ptype[$ii])) {
                    $sql = "SELECT prd,invnum,descrip,age,odate FROM cubit.nons_invoices\n\t\t\t\t\t\tWHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class=err>Invalid Invoice Number.";
                    }
                    $inv = pg_fetch_array($invRslt);
                    $inv['invnum'] += 0;
                    # reduce the money that has been paid
                    $sql = "UPDATE cubit.nons_invoices\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt \n\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}', '" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                    recordCT($paidamt[$key], $cus['cusnum'], $inv['age'], $sdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                } else {
                    /* pos invoices */
                    $sql = "SELECT * FROM cubit.prd_pinvoices\n\t\t\t\t\t\tWHERE invid='{$invids[$key]}' AND div='" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce the invoice balance
                    $sql = "UPDATE \"{$inv['iprd']}\".pinvoices\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(13,2))\n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt\n\t\t\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$cus['cusnum']}','{$inv['invnum']}', '" . ($paidamt[$key] - $paidamt[$key] * 2) . "','{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                    recordCT($paidamt[$key], $cus['cusnum'], 0, $sdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    //$rages .= "|$inv[age]";
                    $invidsers .= " - {$inv['invnum']}";
                }
            }
        }
    }
    writetrans($bank_acc, $dept['debtacc'], $sdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
    db_conn('cubit');
    if ($out > 0) {
        /* START OPEN ITEMS */
        $openstmnt = new dbSelect("open_stmnt", "cubit", grp(m("where", "balance>0 AND cusnum='{$cusnum}'"), m("order", "date")));
        $openstmnt->run();
        $open_out = $out;
        $i = 0;
        $ox = "";
        while ($od = $openstmnt->fetch_array()) {
            if ($open_out == 0) {
                continue;
            }
            $oid = $od['id'];
            if ($open_out >= $od['balance']) {
                $open_amount[$oid] = $od['balance'];
                $open_out = sprint($open_out - $od['balance']);
                $ox .= "<tr class='" . bg_class() . "'><td><input type=hidden size=20 name=open[{$oid}] value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td><td>{$od['date']}</td><td><input type=hidden name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t" . CUR . " {$open_amount[$oid]}</td></tr>";
                $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                $Ri = db_exec($Sl) or errDie("Unable to update statement.");
            } elseif ($open_out < $od['balance']) {
                $open_amount[$oid] = $open_out;
                $open_out = 0;
                $ox .= "<tr class='" . bg_class() . "'><td><input type=hidden size=20 name=open[{$oid}] value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td><td>{$od['date']}</td><td><input type=hidden name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t" . CUR . " {$open_amount[$oid]}</td></tr>";
                $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                $Ri = db_exec($Sl) or errDie("Unable to update statement.");
            }
            $i++;
        }
        if (open()) {
            $bout = $out;
            $out = $open_out;
            if ($out > 0) {
                $sql = "INSERT INTO cubit.open_stmnt(cusnum, invid, amount, balance, date, type, st, div) VALUES('{$cus['cusnum']}', '0', '-{$out}', '-{$out}', '{$sdate}', 'Payment Received', 'n', '" . USER_DIV . "')";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";
            }
            $out = $bout;
        } else {
            //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";}
        }
    }
    if ($out > 0) {
        recordCT($out, $cus['cusnum'], 0, $sdate);
        $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$out), m("date", $sdate), m("type", "Payment Received"), m("div", USER_DIV), m("allocation_date", $sdate));
        $dbobj = new dbUpdate("stmnt", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        custledger($cus['cusnum'], $bank_acc, $sdate, "PAYMENT", "Payment received.", $out, "c");
    }
    $sql = "INSERT INTO cubit.payrec(date,by,multiinv,amount,method,prd,note)\n\t\t\tVALUES('{$sdate}','" . USER_NAME . "', '{$invidsers}', '{$pcash}','Cash','" . PRD_DB . "','0')";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.payrec(date,by,multiinv,amount,method,prd,note)\n\t\t\tVALUES('{$sdate}','" . USER_NAME . "', '{$invidsers}', '{$pcc}','Credit Card','" . PRD_DB . "','0')";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.payrec(date,by,multiinv,amount,method,prd,note)\n\t\t\tVALUES('{$sdate}','" . USER_NAME . "', '{$invidsers}', '{$pcheque}','Cheque','" . PRD_DB . "','0')";
    db_exec($sql) or errDie("Unable to insert data.");
    pglib_transaction("COMMIT");
    $_POST["pcc"] = $_POST["pcheque"] = $_POST["pcash"] = "0.00";
    return details($_POST, "<li class='err'>Payment received successfully</li>");
}