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;
    }
    # Get Invoice info
    db_connect();
    $sql = "SELECT * FROM hire.hire_nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoices information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    /* --- Start Products Display --- */
    # Products layout
    $products = "\r\n\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th width='5%'>#</th>\r\n\t\t\t\t\t\t<th width='40%'>DESCRIPTION</th>\r\n\t\t\t\t\t\t<th width='10%'>QTY</th>\r\n\t\t\t\t\t\t<th width='10%'>UNIT PRICE</th>\r\n\t\t\t\t\t\t<th width='10%'>AMOUNT</th>\r\n\t\t\t\t\t\t<th width='25%'>ACCOUNT</th>\r\n\t\t\t\t\t<tr>";
    # get selected stock in this Invoice
    $any = false;
    $i = 0;
    $vatmin = 0;
    $vatamount = 0;
    foreach ($ids as $key => $id) {
        if ($qtys[$key] <= 0) {
            continue;
        }
        $any = true;
        db_connect();
        $sql = "SELECT * FROM hire.hire_nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        $stkacc = $stkd['accid'];
        $accRs = get("core", "accname,topacc,accnum", "accounts", "accid", $stkacc);
        $acc = pg_fetch_array($accRs);
        # Calculate amount
        $amt[$key] = $qtys[$key] * $stkd['unitcost'];
        db_connect();
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $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 (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        if ($vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        $vr = vatcalc($amt[$key], $inv['chrgvat'], $excluding, 0, $vd['vat_amount']);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        $vatamount += $ivat;
        // 		if($stkd['vatex']=="y"||$vd['zero']=="Yes") {
        // 			$vatmin+=$amt[$key];
        // 		}
        $amt[$key] = sprint($amt[$key]);
        $any = true;
        $i++;
        # put in product
        $products .= "\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td align=center>{$i}<input type='hidden' name=ids[] value='{$stkd['id']}'></td>\r\n\t\t\t\t\t\t<td>{$stkd['description']}</td>\r\n\t\t\t\t\t\t<td><input type='hidden' name='qtys[]' value='{$qtys[$key]}'>{$qtys[$key]}</td>\r\n\t\t\t\t\t\t<td nowrap>" . CUR . " {$stkd['unitcost']}</td>\r\n\t\t\t\t\t\t<td nowrap><input type='hidden' name='amts[]' value='{$amt[$key]}'>" . CUR . " {$amt[$key]}</td>\r\n\t\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\r\n\t\t\t\t\t</tr>";
    }
    $products .= "</table>";
    # if there isn't any products
    if (!$any) {
        $err = "<li class='err'> Error : There are no products selected.";
        return details($_POST, $err);
        return "<li class='err'> Error : There are no products selected.";
    }
    $taxex = sprint($vatmin);
    $chrgvat = $inv['chrgvat'];
    /* --- Start Some calculations --- */
    /*
    	# calculate subtot
    	if( isset($amt) ){
    		$TOTAL = array_sum($amt);
    	}else{
    		$TOTAL = 0.00;
    	}
    
    	$vatmin=sprint($vatmin);
    
    	$temp_TOTAL=$TOTAL;
    
    	$TOTAL=$TOTAL-$vatmin;
    
    
    	# if vat is not included
    	$VATP = TAX_VAT;
    	if($inv['chrgvat'] == "yes"){
    		$SUBTOT = sprintf("%0.2f", $TOTAL * 100 / (100 + $VATP) );
    	} elseif($inv['chrgvat'] == "no") {
    		$SUBTOT = $TOTAL;
    		$TOTAL = sprintf("%0.2f", $TOTAL * (100 + $VATP) /100 );
    	}else{
    		$SUBTOT = $TOTAL;
    	}
    
    	$TOTAL=sprint($TOTAL+$vatmin);
    	$SUBTOT=sprint($SUBTOT+$vatmin);
    
    	// compute the sub total (total - vat), done this way because the specified price already includes vat
    	$VAT = sprint($TOTAL - $SUBTOT);*/
    $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 = sprint($vatamount);
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
    } elseif ($chrgvat == "yes") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        //	$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = sprint($vatamount);
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
    } else {
        $subtotal = sprint($sub);
        $traddiscmt = sprint($subtotal);
        $subtotal = sprint($subtotal);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
    }
    /* --- End Some calculations ---
    
    	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;
    
    	# Format date
    	// list($ninv_year, $ninv_month, $ninv_day) = explode("-", $inv['sdate']);
    */
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    /* -- Final Layout -- */
    $details = "\r\n\t\t\t<center>\r\n\t\t\t<h3>Non-Stock Credit Note</h3>\r\n\t\t\t<form action='" . SELF . "' method='POST' name='form'>\r\n\t\t\t\t<input type='hidden' name='key' value='write'>\r\n\t\t\t\t<input type='hidden' name='invid' value={$invid}>\r\n\t\t\t\t<input type='hidden' name='remarks' value='{$remarks}'>\r\n\t\t\t<table " . TMPL_tblDflts . " width='95%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<th colspan='2'> Customer Details </th>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>{$inv['cusname']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer Address</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'><pre>{$inv['cusaddr']}</pre></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Customer VAT Number</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>{$inv['cusvatno']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t\t<td valign='top' align='right'>\r\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<th colspan='2'> Non-Stock Invoice Details </th>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Non-Stock Invoice No.</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>{$inv['invnum']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>Date</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>\r\n\t\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\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\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\t</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>VAT Inclusive</td>\r\n\t\t\t\t\t\t\t\t<td valign='center'>{$inv['chrgvat']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr><td><br></td></tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'>{$products}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<th width='40%'>Quick Links</th>\r\n\t\t\t\t\t\t\t\t<th width='45%'>Remarks</th>\r\n\t\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='15%'><br></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='nons-invoice-new.php'>New Non-Stock Invoices</a></td>\r\n\t\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\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\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\t</tr>\r\n\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t\t<td align='right'>\r\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>SUBTOTAL</td>\r\n\t\t\t\t\t\t\t\t<td align='right' nowrap><input type='hidden' name='subtot' value='{$SUBTOT}'>" . CUR . " {$SUBTOT}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<td>VAT {$vat14}</td>\r\n\t\t\t\t\t\t\t\t<td align='right' nowrap><input type='hidden' name='vat' value='{$VAT}'>" . CUR . " {$VAT}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\r\n\t\t\t\t\t\t\t\t<td align='right' nowrap><input type='hidden' name='total' value='{$TOTAL}'>" . CUR . " {$TOTAL}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td></tr>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td align='right'><input type='submit' value='Write &raquo'></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</table>\r\n\t\t\t\t</form>\r\n\t\t\t\t</center>";
    return $details;
}
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.");
    $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"] . "</li>";
        }
        return details($_POST, $err);
    }
    # 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);
    # 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>";
    }
    //	$td = $pur['pdate'];
    $td = "{$p_year}-{$p_month}-{$p_day}";
    # 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.</li>";
        $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);
    $refnum = getrefnum();
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkd = pg_fetch_array($stktRslt)) {
        $iq = $qty[$stkd['id']];
        $iq += 0;
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if ($pur['vatinc'] == "yes") {
            $iamount = $stkd['amt'];
        } else {
            $iamount = sprint($stkd['amt'] + $stkd['svat']);
        }
        //$pur['pdate'] -> $td
        vatr($vd['id'], $td, "INPUT", $vd['code'], $refnum, "VAT for Purchase No. {$pur['purnum']}", -$iamount, -$stkd['svat']);
        $Sl = "UPDATE pur_items SET iqty=iqty-'{$iq}' WHERE id='{$stkd['id']}'";
        $Ri = db_exec($Sl) or errDie("Unable to update invoice qty.");
    }
    ###################VAT CALCS#######################
    $pur['delvat'] += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    $vr = vatcalc($pur['shipchrg'], $pur['vatinc'], $excluding, 0, $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat_tmp = $vrs[0];
    $iamount_tmp = $vrs[1];
    vatr($vd['id'], $td, "INPUT", $vd['code'], $refnum, "VAT Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.", sprint(-$iamount_tmp), -$ivat_tmp);
    ####################################################
    /* - 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");
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$TOTAL}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    //$pur['pdate'] -> $td
    $sql = "\n\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\tsupid, edate, cacc, amount, descript, \n\t\t\t\tref, ex, div\n\t\t\t) VALUES (\n\t\t\t\t'{$pur['supid']}', '{$td}', '{$wh['conacc']}', '{$TOTAL}', 'Stock Received - Purchase {$pur['purnum']} Inv:{$supinv}', \n\t\t\t\t'{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t)";
    $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, sprint($SUBTOT + $del), "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Transfer vat
    writetrans($vatacc, $dept['credacc'], $td, $refnum, $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.", $TOTAL, 'c');
    /* 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 = "\n\t\t\t\t\tUPDATE suppurch \n\t\t\t\t\tSET balance = (balance + '{$TOTAL}') \n\t\t\t\t\tWHERE 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 {
        //$pur['pdate'] -> $td
        /* Make transaction record for age analysis */
        $sql = "\n\t\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$pur['supid']}', '{$pur['purnum']}', '{$td}', '{$TOTAL}', '" . USER_DIV . "'\n\t\t\t\t\t)";
        $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
    }
    /* Make transaction record  for age analysis */
    # commit updating
    $sql = "UPDATE purchases SET iamount = iamount+'{$TOTAL}',ivat=ivat+'{$VAT}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    $p = pg_fetch_array($purRslt);
    //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    $sql = "SELECT SUM(iqty) FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    $data = pg_fetch_array($stktRslt);
    $left = $data['sum'];
    if ($left == 0) {
        /* Start moving if purchase */
        if ($pur['received'] == "y") {
            if (strlen($pur['appdate']) < 8) {
                $pur['appdate'] = date("Y-m-d");
            }
            # copy purchase
            db_conn($pur['prd']);
            //$pur['pdate'] -> $td
            $sql = "\n\t\t\t\tINSERT INTO purchases (\n\t\t\t\t\tpurid, deptid, supid, supname, supaddr, supno, terms, \n\t\t\t\t\tpdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, \n\t\t\t\t\tshipping, remarks, refno, received, done, div, purnum, supinv, \n\t\t\t\t\tordernum, appname, appdate, delvat\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', '{$pur['terms']}', \n\t\t\t\t\t'{$td}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', \n\t\t\t\t\t'{$pur['shipping']}', '{$remarks}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}', '{$supinv}', \n\t\t\t\t\t'{$pur['ordernum']}', '{$pur['appname']}', '{$pur['appdate']}', '{$pur['delvat']}'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
            /*-- Cost varience -- */
            //$nsubtot = sprint($pur['total'] - $pur['vat']);
            $nsubtot = sprint($p['iamount'] - $p['ivat']);
            if ($p['rsubtot'] > $nsubtot) {
                $diff = sprint($p['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 > $p['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)) {
                db_conn($pur['prd']);
                $sql = "\n\t\t\t\t\tINSERT INTO pur_items (\n\t\t\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, \n\t\t\t\t\t\tamt, svat, ddate, div, vatcode, \n\t\t\t\t\t\taccount, description, udiscount\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', \n\t\t\t\t\t\t'{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "', '{$stktc['vatcode']}', \n\t\t\t\t\t\t'{$stktc['account']}', '{$stktc['description']}', '{$stktc['udiscount']}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            }
            # begin updating
            //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
            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
            //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
        } else {
            # insert Order to DB
            $sql = "UPDATE purchases SET invcd = 'y', supinv='{$supinv}', remarks = '{$remarks}' 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\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Purchase Invoiced</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Purchase Invoice from Supplier <b>{$pur['supname']}</b> has been recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='purchase-view.php'>View purchases</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (!isset($cusnum)) {
        return details($_POST, "<li class='err'>Please select customer/department first.</li>");
    }
    $delvat += 0;
    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($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);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($branch, "num", 1, 20, "Invalid Branch, Please select a branch.");
    $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, 1024, "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($inv_date_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($inv_date_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($inv_date_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $inv_date_year . "-" . $inv_date_month . "-" . $inv_date_day;
    if (!checkdate($inv_date_month, $inv_date_day, $inv_date_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)) {
        $tmp_sernos = $sernos;
        // only check for uniqueness among items not selected for removal
        foreach ($sernos as $k => $serno_val) {
            if (isset($remprod) && in_array($k, $remprod)) {
                unset($tmp_sernos[$k]);
            }
        }
        if (!ext_isUnique(ext_remBlnk($tmp_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>");
            }
        }
    }
    if (!isset($qtys) && isset($qtemp)) {
        $qtys[] = $qtemp;
    } elseif (isset($qtys) && isset($qtemp)) {
        //array_unshift ($qtys,$qtemp);
        $qtys[] = $qtemp;
    }
    # 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);
    }
    # 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;
    if ($cusnum != $inv['cusnum'] or $branch != $inv['branch']) {
        $get_addr = "SELECT branch_descrip FROM customer_branches WHERE id = '{$branch}' AND div = '" . USER_DIV . "' LIMIT 1";
        $run_addr = db_exec($get_addr);
        if (pg_numrows($run_addr) < 1) {
            #no branch addres ? since we NEED to update the address, add the customer's here
            $get_cadd = "SELECT del_addr1 FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
            $run_cadd = db_exec($get_cadd) or errDie("Unable to get customer delivery address");
            if (pg_numrows($run_cadd) < 1) {
                #no customer ??
                return details($_POST, "<li class='err'>Invalid customer selected.</li>");
            } else {
                $carr = pg_fetch_array($run_cadd);
                $update_addr = "UPDATE invoices SET del_addr  = '{$carr['del_addr1']}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $run_update = db_exec($update_addr) or errDie("Unable to update invoice information");
            }
        } else {
            $arr = pg_fetch_array($run_addr);
            $cust['addr1'] = $arr['branch_descrip'];
            if ($inv['del_addr'] != $arr['branch_descrip']) {
                $update_addr = "UPDATE invoices SET del_addr  = '{$arr['branch_descrip']}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $run_update = db_exec($update_addr) or errDie("Unable to update invoice information");
            }
        }
    }
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get 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 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 -- */
    $newvat = 0;
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            /* set the serial ss field for serials selected from list */
            if ($sernos_ss[$keys] == "*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*") {
                $sernos_ss[$keys] = $sernos[$keys];
            }
            if (isset($remprod) && in_array($keys, $remprod)) {
                $amt[$keys] = 0;
                if ($sernos[$keys] == $sernos_ss[$keys] && $sernos_ss[$keys] != "") {
                    $chr = substr($sernos[$keys], strlen($sernos[$keys]) - 1, 1);
                    $tab = "ss{$chr}";
                    /* mark barcoded item as unavailable */
                    $sql = "UPDATE " . $tab . " SET active='yes' WHERE code = '{$sernos[$keys]}' AND div = '" . USER_DIV . "'";
                    db_exec($sql);
                }
            } 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 inv_items (\n\t\t\t\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, \n\t\t\t\t\t\t\tdisc, discp, serno, div, vatcode, description, \n\t\t\t\t\t\t\taccount, 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]}', '{$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]}', '0'\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";
                }
                //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                $wtd = $whids[$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, amt, \n\t\t\t\t\t\t\tdisc, discp, ss, serno, div, \n\t\t\t\t\t\t\tvatcode, 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]}', '{$amt[$keys]}', \n\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '{$sernos_ss[$keys]}', '{$sernos[$keys]}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$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"] = "\t| <input name='doneBtn' type='submit' value='Process'>";
            //if ($cust["email"] != "") {
            $_POST["done"] .= " | <input name='emailBtn' type='submit' value='Process and Email to Customer'>";
            //}
        }
    } else {
        $_POST["done"] = "";
    }
    //$newvat+=vatcalc($delchrg,$chrgvat,"no",$traddisc);
    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;
    #get traddisc setting ...
    $traddisc_setting = getCSetting("SET_INV_TRADDISC");
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        if ($traddisc_setting == "include") {
            $tradvar = $subtotal;
        } else {
            $tradvar = $sub;
        }
        $traddiscmt = sprint($tradvar * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $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);
        if ($traddisc_setting == "include") {
            $tradvar = $subtotal;
        } else {
            $tradvar = $sub;
        }
        $traddiscmt = sprint($tradvar * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        if ($traddisc_setting == "include") {
            $tradvar = $subtotal;
        } else {
            $tradvar = $sub;
        }
        $traddiscmt = sprint($tradvar * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- ----------- Clac ---------------------
    ----------------------OLD----------------------
    		# 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;
    */
    #override address
    if ($branch != 0) {
        $get_addr = "SELECT branch_descrip FROM customer_branches WHERE id = '{$branch}' AND div = '" . USER_DIV . "' LIMIT 1";
        $run_addr = db_exec($get_addr);
        if (pg_numrows($run_addr) < 1) {
            #address missing ... do nothing
        } else {
            $arr = pg_fetch_array($run_addr);
            $cust['addr1'] = $arr['branch_descrip'];
        }
    }
    // Delivery Date
    $deldate = "{$del_date_year}-{$del_date_month}-{$del_date_day}";
    /* --- ----------- Clac --------------------- */
    if (!isset($bankid)) {
        $bankid = cust_bank_id($cusnum);
    }
    # insert invoice to DB
    $sql = "\n\t\t\tUPDATE 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}', branch = '{$branch}', \n\t\t\t\tdeldate = '{$deldate}', bankid = '{$bankid}' \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);
    if (strlen($bar) > 0) {
        /* check if there a stock item with global barcode matching input barcode */
        $sql = "SELECT * FROM stock WHERE bar='{$bar}' AND div = '" . USER_DIV . "'";
        $barRslt = db_exec($sql);
        if (pg_num_rows($barRslt) <= 0) {
            /* fetch last character of barcode */
            $chr = substr($bar, strlen($bar) - 1, 1);
            /* invalid barcode */
            if (!is_numeric($chr)) {
                return details($_POST, "The code you selected is invalid");
            }
            /* which barcode table to scan for stock id */
            $tab = "ss{$chr}";
            $stid = barext_dbget($tab, 'code', $bar, 'stock');
            $stab = "serial{$chr}";
            $sstid = serext_dbget($stab, 'serno', $bar, 'stkid');
            /* non-existing barcode, check for serial number */
            if ($stid <= 0) {
                if ($sstid <= 0) {
                    return details($_POST, "<li class='err'>The serial number/bar code you selected is not in the system or is not available.</li>");
                }
                if (serext_dbnum($stab, 'serno', $bar, 'stkid') > 1) {
                    return details($_POST, "<li class='err'>Duplicate serial numbers found, please scan barcode or select stock item.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $stab . " SET rsvd='y' WHERE serno='{$bar}'";
                db_exec($sql);
                $serno_bar = "{$bar}";
                $stid = $sstid;
            } else {
                if ($sstid > 0) {
                    return details($_POST, "<li class='err'>A serial and barcode with same value, please scan other value or select product manually.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $tab . " SET active='no' WHERE code='{$bar}' AND div='" . USER_DIV . "'";
                db_exec($sql);
                $serno_bar = "{$bar}";
            }
            /* fetch stock row for selected item */
            $sql = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $barRslt = db_exec($sql);
        } else {
            $serno_bar = "";
        }
        $s = pg_fetch_array($barRslt);
        /* allocate stock item */
        $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$s['stkid']}' AND div = '" . USER_DIV . "'";
        db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        $sql = "\n\t\t\tINSERT INTO inv_items (\n\t\t\t\tinvid, whid, stkid, qty, unitcost, amt, disc, discp, ss, serno, \n\t\t\t\tdiv, vatcode\n\t\t\t) VALUES (\n\t\t\t\t'{$invid}', '{$s['whid']}', '{$s['stkid']}', '1','{$s['selamt']}', '{$s['selamt']}','0','0','{$bar}', '{$serno_bar}', \n\t\t\t\t'" . USER_DIV . "', (SELECT id FROM cubit.vatcodes LIMIT 1)\n\t\t\t)";
        db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($doneBtn) || isset($emailBtn)) {
        # 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);
        $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        $data = pg_fetch_array($Ri);
        if (isset($emailBtn)) {
            $email = "email=true";
        } else {
            $email = "";
        }
        if ($data['value'] == "Yes") {
            //		move('cust-credit-stockinv.php');
            //move('cust-credit-stockinv-newsetting.php');
            $OUTPUT = "\n\t\t\t\t<script>\n\t\t\t\t\tnhprinter('invoice-delnote.php?invid={$invid}','Delivery Note');\n\t\t\t\t\tprinter('invoice-print.php?invid={$invid}&type=inv&salespn={$salespn}&{$email}');\n\t\t\t\t\tmove('settings/cust-credit-stockinv-newsetting.php');\n\t\t\t\t</script>";
        } else {
            //		move('cust-credit-stockinv.php');
            //move('cust-credit-stockinv-newsetting.php');
            $OUTPUT = "\n\t\t\t\t<script>\n\t\t\t\t\tprinter('invoice-print.php?invid={$invid}&type=inv&{$email}');\n\t\t\t\t\tmove('settings/cust-credit-stockinv-newsetting.php');\n\t\t\t\t</script>";
        }
        # Print the invoice
        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 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>Invoice for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been saved. To view it go to 'View incomplete invoices'</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);
    }
    /* --- End button Listeners --- */
}
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($odate, "date", 1, 14, "Invalid Invoice note date.");
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    $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, "float", 1, 15, "Invalid Returned Quantity.");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount.");
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "Invalid Returned Quantity.");
    }
    # check stkids[]
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "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.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "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 error($_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 "<i class=err>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    cus_xrate_update($inv['fcid'], $inv['xrate']);
    $notenum = divlastid('note', USER_DIV);
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $taxex = 0;
    foreach ($qtys as $keys => $value) {
        db_connect();
        # 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);
        # get selected stock in this invoice
        $sql = "SELECT * FROM inv_items  WHERE stkid = '{$stkids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        # get warehouse name
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # Calculate the Discount discount
        if ($disc[$keys] < 1) {
            if ($discp[$keys] > 0) {
                $disc[$keys] = $discp[$keys] / 100 * $stkd['unitcost'];
            }
        } else {
            $discp[$keys] = $disc[$keys] * 100 / $stkd['unitcost'];
        }
        # Calculate amount
        $amt[$keys] = $qtys[$keys] * ($stkd['unitcost'] - $disc[$keys]);
        db_connect();
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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);
        # Check Tax Excempt
        if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
            $taxex += $amt[$keys];
        }
        # put in product
        $products .= "\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stk['stkid']}'>{$stk['stkcod']}</td>\n\t\t\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t\t\t<td><input type='hidden' size='5' name='qtys[]' value='{$qtys[$keys]}'>{$qtys[$keys]}</td>\n\t\t\t\t\t\t\t<td>{$stkd['unitcost']}</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='amt[]' value='{$amt[$keys]}'>{$inv['currency']} {$amt[$keys]}</td>\n\t\t\t\t\t\t</tr>";
    }
    # 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);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($inv['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);
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($inv['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));
        $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);
    }
    $SUBTOTAL = sprint($SUBTOT);
    $traddiscm = $traddiscmt;
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- ----------- Clac ---------------------
    
    		# calculate subtot
    		$SUBTOT = 0.00;
    		if(isset($amt))
    			$SUBTOT = sprint(array_sum($amt));
    
    		$SUBTOT -= $taxex;
    
    		# duplicate
    		$SUBTOTAL = sprint($SUBTOT);
    
    		$VATP = TAX_VAT;
    		if($inv['chrgvat'] == "exc"){
    			$SUBTOTAL = $SUBTOTAL;
    			$delexvat= ($delchrg);
    		}elseif($inv['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);
    
    		$traddiscm = $traddiscmt;
    
    		if($inv['chrgvat'] != "nov"){
    			$VAT = sprint($EXVATTOT * ($VATP/100));
    		}else{
    			$VAT = 0;
    		}
    
    		$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    		$SUBTOT += $taxex;
    
    /* --- ----------- Clac --------------------- */
    $FSUBTOT = sprint($SUBTOT * $inv['xrate']);
    $FSUBTOTAL = sprint($SUBTOTAL * $inv['xrate']);
    $FVAT = sprint($VAT * $inv['xrate']);
    $FTOTAL = sprint($TOTAL * $inv['xrate']);
    $fdelchrg = sprint($delchrg * $inv['xrate']);
    $ftraddiscm = sprint($traddiscm * $inv['xrate']);
    /* --- ----------- Clac --------------------- */
    # 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 class=err>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    /* A quick fix by jupiter
    	$allnoted = true;
    	foreach($qtys as $keys => $value){
    		# get selected stock in this invoice
    		$sql = "SELECT * FROM inv_items  WHERE id = '$ids[$keys]' AND invid ='$invid' AND div = '".USER_DIV."'";
    		$stkdRslt = db_exec($sql);
    		$stkd = pg_fetch_array($stkdRslt);
    		if($stkd['qty'] != $qtys[$keys]){
    			$allnoted = false;
    		}
    	}
    
    	if($allnoted){
    		$SUBTOT = sprint($inv['subtot']);
    		$VAT = sprint($inv['vat']);
    		$TOTAL = sprint($inv['total']);
    		$delchrg = sprint($inv['delivery']);
    		$traddiscm = sprint($inv['discount']);
    		$SUBTOTAL = sprint($TOTAL - $VAT);
    
    		$FSUBTOT = sprint($SUBTOT * $inv['xrate']);
    		$FSUBTOTAL = sprint($SUBTOTAL * $inv['xrate']);
    		$FVAT = sprint($VAT * $inv['xrate']);
    		$FTOTAL = sprint($TOTAL * $inv['xrate']);
    		$fdelchrg = sprint($delchrg * $inv['xrate']);
    		$ftraddiscm = sprint($traddiscm * $inv['xrate']);
    	}
    /*End A quick fix by jupiter */
    $invpay = $TOTAL;
    /*if($inv['fbalance'] >= $TOTAL) {
    		$invpay = $TOTAL;
    		$examt = 0;
    	} else {
    		$invpay = $inv['fbalance'];
    		$examt = ($TOTAL-$invpay);
    	}
    
    	# Make it local
    	 $examt = ($examt * $inv['xrate']);*/
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    # Todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*refnum*/
    # Insert invoice to period DB
    db_conn($inv['prd']);
    # Format date
    $odate = explode("-", $odate);
    $rodate = $odate[2] . "-" . $odate[1] . "-" . $odate[0];
    $td = $rodate;
    # Insert invoice credit note to DB
    $sql = "INSERT INTO inv_notes(deptid, notenum, invnum, invid, cusnum, cordno, ordno, chrgvat, fcid, currency, xrate, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, comm, username, div, surname, cusaddr, cusvatno, deptname, location, prd)";
    $sql .= " VALUES('{$inv['deptid']}', '{$notenum}', '{$inv['invnum']}', '{$inv['invid']}', '{$inv['cusnum']}', '{$inv['cordno']}', '{$inv['ordno']}', '{$inv['chrgvat']}', '{$inv['fcid']}', '{$inv['currency']}', '{$inv['xrate']}', '{$terms}', '{$traddiscm}', '{$inv['salespn']}', '{$rodate}', '{$delexvat}', '{$SUBTOT}', '{$VAT}' , '{$TOTAL}', '{$comm}', '" . USER_NAME . "', '" . USER_DIV . "', '{$inv['surname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['deptname']}', '{$inv['location']}', {$inv['prd']})";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice to Cubit.", SELF);
    # Get next ordnum
    $noteid = pglib_lastid("inv_notes", "noteid");
    db_connect();
    # Begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $nbal = $inv['nbal'] + $TOTAL;
    # Update the invoice (make balance less)
    $sql = "UPDATE invoices SET nbal = '{$nbal}', rdelchrg = (rdelchrg + '{$delchrg}'), fbalance = fbalance - '{$invpay}', balance = balance - '{$FTOTAL}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Update the customer (make balance less)
    $sql = "UPDATE customers SET balance = (balance - '{$FTOTAL}'), fbalance = (fbalance - '{$TOTAL}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Update invoice's discounts
    # $sql = "UPDATE inv_discs SET traddisc = (traddisc - '$traddiscm'), itemdisc = (itemdisc - '$discs') WHERE cusnum = '$inv[cusnum]' AND invid = '$invid'";
    # $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.",SELF);
    # Record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt \n\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\tVALUES \n\t\t\t\t('{$inv['cusnum']}','{$inv['invnum']}','" . ($TOTAL - $TOTAL * 2) . "', '{$rodate}', 'Credit Note for invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$rodate}')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    $disc = 0;
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Make ledge record
    custledger($inv['cusnum'], $dept['incacc'], $td, $notenum, "Credit Note No. {$notenum} for invoice No. {$inv['invnum']}", $FTOTAL, "c");
    /*
    if($examt > 0) {
    	# Make record for age analisys
    	custCTP($examt, $inv['cusnum']);
    }
    */
    foreach ($qtys as $keys => $value) {
        $famt[$keys] = sprint($amt[$keys] * $inv['xrate']);
        db_connect();
        # 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);
        # get selected stock in this invoice
        $sql = "SELECT * FROM inv_items  WHERE id = '{$ids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        # Keep track of discounts
        $disc += $stkd['disc'] * $stkd['qty'] * $inv['xrate'];
        # cost amount
        $cosamt = round($qtys[$keys] * $stk['csprice'], 2);
        # Update stock(onhand + qty)
        $sql = "UPDATE stock SET csamt = (csamt + '{$cosamt}'), units = (units + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if ($stk['serd'] == 'yes') {
            ext_InSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $notenum, 'note', $td);
        }
        # negetive values to minus profit
        $nqty = $qtys[$keys] * 1;
        $namt = $amt[$keys] * -1;
        $ncsprice = $cosamt * -1;
        $noted = $stkd['noted'] + $qtys[$keys];
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        stockrec($stkd['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $td, $nqty, $cosamt, "Credit note for Customer : {$inv['surname']} - Credit note No. {$notenum}");
        db_connect();
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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);
        # Get amount exluding vat if including and not exempted
        $VATP = TAX_VAT;
        $amtexvat = $famt[$keys];
        if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes' && $vd['zero'] != "Yes") {
            $amtexvat = sprint($famt[$keys] * 100 / (100 + $VATP));
        }
        ###################VAT CALCS#######################
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc']);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        $iamount = $iamount * $inv['xrate'];
        $ivat = $ivat * $inv['xrate'];
        vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "VAT for Credit note: {$notenum} Customer : {$inv['cusname']} {$inv['surname']}", -$iamount, -$ivat);
        ####################################################
        $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\tVALUES('{$td}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'note', '{$qtys[$keys]}', '{$amtexvat}', '{$cosamt}', 'Credit note for Customer : {$inv['surname']} - Credit note No. {$notenum}', '" . USER_DIV . "')";
        $recRslt = db_exec($sql);
        # Get selected stock in this invoice
        $sql = "UPDATE inv_items SET noted = '{$noted}' WHERE id = '{$ids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
        $stkdsRslt = db_exec($sql);
        $stkds = pg_fetch_array($stkdsRslt);
        # get accounts
        db_conn("exten");
        $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        $stockacc = $wh['stkacc'];
        $cosacc = $wh['cosacc'];
        # sales rep commission
        # coms($inv['salespn'], $amt[$keys], $stk['com'], 'anything');
        # dt(stock) ct(cos)
        writetrans($stockacc, $cosacc, $td, $refnum, $cosamt, "Cost Of Sales for Credit note No. {$notenum} for Customer : {$inv['cusname']} {$inv['surname']}");
        db_conn($inv['prd']);
        # insert invoice items
        $sql = "INSERT INTO inv_note_items(noteid, whid, stkid, qty, amt, div,vatcode) VALUES('{$noteid}', '{$stkd['whid']}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "','{$stkd['vatcode']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
    }
    db_connect();
    # save invoice discount
    $sql = "INSERT INTO inv_discs(cusnum, invid, traddisc, itemdisc, inv_date, delchrg, div) VALUES('{$inv['cusnum']}', '{$invid}', '0', '-{$disc}', '{$inv['odate']}', '0', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    /* - Start Transactoins - */
    # dt(income) ct(debtors)
    writetrans($dept['incacc'], $dept['debtacc'], $td, $refnum, $FTOTAL - $FVAT, "Debtors Control for Credit note No. {$notenum} for Customer : {$inv['cusname']} {$inv['surname']}");
    # dt(vat) ct(debtors)
    writetrans($vatacc, $dept['debtacc'], $td, $refnum, $FVAT, "Vat Return for Credit note No. {$notenum} for Customer : {$inv['cusname']} {$inv['surname']}");
    db_connect();
    $date = date("Y-m-d");
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\tVALUES('{$rodate}', '{$noteid}', '{$notenum}', '{$dept['debtacc']}', '{$FVAT}', '{$FTOTAL}', 'nstk', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    db_conn('cubit');
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t('{$inv['cusnum']}','{$inv['surname']}','Credit Note: {$notenum}, International Invoice {$inv['invnum']}','{$rodate}','" . -sprint($FTOTAL - $FVAT) . "','-{$FVAT}','" . -sprint($FTOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    /* - End Transactoins - */
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h2>Credit Note</h2>\n\t\t\t\t\t<table cellpadding='0' cellspacing='4' border=0 width=750>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>{$inv['surname']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>" . nl2br($inv['cusaddr']) . "</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>(Vat No. {$inv['cusvatno']})</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='top' width='25%'>\n\t\t\t\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td width='20%'><img src='compinfo/getimg.php' width=230 height=47></td>\n\t\t\t\t\t\t\t<td valign='bottom' align='right' width='25%'>\n\t\t\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border=1 bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Credit Note No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$notenum}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Order No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['ordno']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Terms</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$terms} Days</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Credit note Date</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$rodate}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='4'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border=1 width=100% bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t\t\t\t\t\t\t<th width='45%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t\t\t\t<th>QTY RETURNED</th>\n\t\t\t\t\t\t\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t\t\t\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t{$products}\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</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<td>\n\t\t\t\t\t\t\t\t<table border='1' cellspacing='0' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr><td>" . nl2br($comm) . "</td></tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td align='right' colspan='3'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border=1 width=50% bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$SUBTOT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Trade Discount</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$traddiscmt}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Delivery Charge</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$delexvat}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>VAT @ {$VATP}%</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$VAT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th><b>GRAND TOTAL<b></th>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " border=1>\n\t\t\t\t\t\t        \t<tr>\n\t\t\t\t\t\t        \t\t<th>VAT No.</th>\n\t\t\t\t\t\t        \t\t<td align='center'>" . COMP_VATNO . "</td>\n\t\t\t\t\t\t        \t</tr>\n\t\t\t\t\t\t        </table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td><br></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</center>";
    $OUTPUT = "<script>printer('intinvoice-note-reprint.php?noteid={$noteid}&prd={$inv['prd']}&cccc=yes');move('main.php');</script>";
    require "template.php";
}
function details($_GET)
{
    $showvat = TRUE;
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $td = $inv['odate'];
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($td) >= strtotime($blocked_date_from) and strtotime($td) <= 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>";
    }
    $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 <b>{$invid}</b> has no items.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # 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;
    }
    # check if invoice has been serialised
    if ($inv['serd'] == "n") {
        $error = "<li class='err'> Error : You must select serial numbers for some Items on Invoice No. <b>T {$invid}</b> before you can print it.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    cus_xrate_update($inv['fcid'], $inv['xrate']);
    # Begin Updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $invnum = divlastid('inv', USER_DIV);
    $Sl = "INSERT INTO ncsrec (oldnum, newnum, div) VALUES ('{$invid}', '{$invnum}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert into db");
    # 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);
    }
    /* --- Start Products Display --- */
    # Products layout
    $commision = 0;
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $taxex = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # get warehouse name
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # get selected stock in this warehouse
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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);
        $sp = "";
        # Check Tax Excempt
        if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
            $taxex += $stkd['amt'];
            $ex = "#";
        } else {
            $ex = "";
        }
        # all must be excempted
        if ($inv['chrgvat'] == 'nov') {
            $ex = "#";
        }
        # Keep track of discounts
        $disc += $stkd['disc'] * $stkd['qty'];
        # Insert stock record
        $sdate = date("Y-m-d");
        $csprice = sprint($stk['csprice'] * $stkd['qty']);
        # Get amount exluding vat if including and not exempted
        $VATP = TAX_VAT;
        $amtexvat = sprint($stkd['famt']);
        if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes') {
            $amtexvat = sprint($stkd['famt'] * 100 / (100 + $VATP));
        }
        db_connect();
        $sql = "\n\t\t\tINSERT INTO stockrec (\n\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, \n\t\t\t\tdetails, div\n\t\t\t) VALUES (\n\t\t\t\t'{$td}', '{$stkd['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'invoice', '{$stkd['qty']}', '{$amtexvat}', '{$csprice}', \n\t\t\t\t'Stock sold - Invoice No. {$invnum}', '" . USER_DIV . "'\n\t\t\t)";
        $recRslt = db_exec($sql);
        # Sales rep commission
        $commision = $commision + coms($inv['salespn'], $stkd['amt'], $stk['com']);
        # Put in product
        $products .= "\n\t\t\t<tr valign='top'>\n\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t<td>{$ex} {$sp} {$stk['stkdes']}</td>\n\t\t\t\t<td>" . sprint3($stkd['qty']) . "</td>\n\t\t\t\t<td>{$inv['currency']} " . sprint($stkd['unitcost']) . "</td>\n\t\t\t\t<td>{$inv['currency']} {$stkd['disc']}</td>\n\t\t\t\t<td>{$inv['currency']} {$stkd['amt']}</td>\n\t\t\t</tr>";
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOTAL = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    $FSUBTOT = sprint($inv['subtot'] * $inv['xrate']);
    $FVAT = sprint($inv['vat'] * $inv['xrate']);
    $FTOTAL = sprint($inv['total'] * $inv['xrate']);
    $fdelchrg = sprint($inv['delchrg'] * $inv['xrate']);
    $ftraddiscm = sprint($inv['discount'] * $inv['xrate']);
    com_invoice($inv['salespn'], $FTOTAL, $commision * $inv['xrate'], $invnum, $td);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "int");
    /* - End Hooks - */
    # Todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*$refnum*/
    /* --- Updates ---- */
    db_connect();
    $Sql = "UPDATE invoices SET printed ='y', done ='y', invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
    # Record the payment on the statement
    $sql = "\n\t\tINSERT INTO stmnt (\n\t\t\tcusnum, invid, amount, date, type, div, allocation_date\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}','{$invnum}', '{$TOTAL}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Record the payment on the statement
    $sql = "\n\t\tINSERT INTO open_stmnt (\n\t\t\tcusnum, invid, amount, balance, date, type, div\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$TOTAL}', '{$TOTAL}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "'\n\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Save invoice discount
    $sql = "\n\t\tINSERT INTO inv_discs (\n\t\t\tcusnum, invid, traddisc, itemdisc, inv_date, delchrg, div, \n\t\t\ttotal\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$ftraddiscm}', '{$disc}', '{$inv['odate']}', '{$fdelchrg}', '" . USER_DIV . "', \n\t\t\t({$FSUBTOT}+{$fdelchrg})\n\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$FTOTAL}'), fbalance = (fbalance + '{$TOTAL}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Make ledge record
    custledger($inv['cusnum'], $dept['incacc'], $td, $invnum, "Invoice No. {$invnum}", $FTOTAL, "d");
    db_connect();
    # get selected stock in this invoice
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        db_connect();
        # get selamt from selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        # cost amount
        $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
        # update stock(alloc - qty)
        $sql = "UPDATE stock SET csamt = (csamt - '{$cosamt}'),units = (units - '{$stkd['qty']}'),alloc = (alloc - '{$stkd['qty']}')  WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        ###################VAT CALCS#######################
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        $iamount = $iamount * $inv['xrate'];
        $ivat = $ivat * $inv['xrate'];
        vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
        ####################################################
        if ($stk['serd'] == 'yes') {
            ext_invSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $invnum);
        }
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        $sdate = date("Y-m-d");
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, $stkd['qty'], $cosamt, "Sold to Customer : {$inv['surname']} - Invoice No. {$invnum}");
        # get accounts
        db_conn("exten");
        $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        $stockacc = $wh['stkacc'];
        $cosacc = $wh['cosacc'];
        # dt(cos) ct(stock)
        writetrans($cosacc, $stockacc, $td, $refnum, $cosamt, "Cost Of Sales for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
        $tcosamt += $cosamt;
    }
    ###################VAT CALCS#######################
    $inv['delvat'] += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    $vr = vatcalc($inv['delchrg'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $iamount = $iamount * $inv['xrate'];
    $ivat = $ivat * $inv['xrate'];
    vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
    ####################################################
    /* - Start Transactoins - */
    # dt(debtors) ct(income/sales)
    writetrans($dept['debtacc'], $dept['incacc'], $td, $refnum, $FTOTAL - $FVAT, "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    # dt(debtors) ct(vat account)
    writetrans($dept['debtacc'], $vatacc, $td, $refnum, $FVAT, "VAT Received on Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    db_connect();
    $sql = "\n\t\tINSERT INTO salesrec (\n\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t) VALUES (\n\t\t\t'{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$FVAT}', '{$FTOTAL}', 'stk', '" . USER_DIV . "'\n\t\t)";
    $recRslt = db_exec($sql);
    db_conn('cubit');
    $Sl = "\n\t\tINSERT INTO sj (\n\t\t\tcid, name, des, date, exl, vat, inc, div\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$inv['surname']}', 'International Invoice {$invnum}', '{$inv['odate']}', '" . sprint($FTOTAL - $FVAT) . "', \n\t\t\t'{$FVAT}', '" . sprint($FTOTAL) . "', '" . USER_DIV . "'\n\t\t)";
    $Ri = db_exec($Sl);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* - End Transactoins - */
    # vat explanation
    if ($inv['chrgvat'] == 'nov') {
        $expl = "VAT Exempt indicator";
    } else {
        $expl = "0% VAT indicator";
        $expl = "VAT Exempt indicator";
    }
    # Avoid little box, <table border=1> <-- ehhhemm !!
    if (strlen($inv['comm']) > 0) {
        $inv['comm'] = "\n\t\t\t<table border='1' cellspacing='0' bordercolor='#000000'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>" . nl2br($inv['comm']) . "</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    $cc = "<script> sCostCenter('dt', 'Sales', '{$inv['odate']}', 'Invoice No.{$invnum} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($FTOTAL - $FVAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', ''); </script>";
    /* -- Final Layout -- */
    $details = "\n\t\t<center>\n\t\t{$cc}\n\t\t<h2>Tax Invoice</h2>\n\t\t<table cellpadding='0' cellspacing='4' border='0' width='750'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top' width='30%'>\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>{$inv['surname']}</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<td>" . nl2br($inv['cusaddr']) . "</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<td>(VAT No. {$inv['cusvatno']})</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t" . COMP_PADDR . "<br>\n\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\tReg No. " . COMP_REGNO . "<br>\n\t\t\t\t\tVAT No. " . COMP_VATNO . "<br>\n\t\t\t\t</td>\n\t\t\t\t<td width='20%'>\n\t\t\t\t\t<img src='compinfo/getimg.php' width='230' height='47'>\n\t\t\t\t</td>\n\t\t\t\t<td valign='bottom' align='right' width='20%'>\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$invnum}</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<td><b>Proforma Inv No.</b></td>\n\t\t\t\t\t\t\t<td>{$inv['docref']}</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<td><b>Order No.</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['ordno']}</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<td><b>Terms</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['terms']} Days</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<td><b>Invoice Date</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['odate']}</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<td><b>VAT</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['chrgvat']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='4'>\n\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='100%' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>ITEM NUMBER</b></td>\n\t\t\t\t\t\t\t<td width='45%'><b>DESCRIPTION</b></td>\n\t\t\t\t\t\t\t<td><b>QTY</b></td>\n\t\t\t\t\t\t\t<td><b>UNIT PRICE</b></td>\n\t\t\t\t\t\t\t<td><b>DISCOUNT</b></td>\n\t\t\t\t\t\t\t<td><b>AMOUNT</b></td>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t{$products}\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>{$inv['comm']}</td>\n\t\t\t\t<td>" . BNK_BANKDET . "</td>\n\t\t\t\t<td align='right' colspan='2'>\n\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='50%' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$SUBTOT}</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<td><b>Trade Discount</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$inv['discount']}</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<td><b>Delivery Charge</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$inv['delivery']}</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<td><b>VAT {$vat14}</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$VAT}</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<td><b>GRAND TOTAL<b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'>{$expl} = #</td>\n\t\t\t\t\t\t</tr>\n\t\t\t        </table>\n\t\t\t\t</td>\n\t\t\t\t<td><br></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</center>";
    $OUTPUT = $details;
    require "tmpl-print.php";
}
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
    extract($_POST);
    // prevent from updating
    if (isset($cusnum) && customer_overdue($cusnum)) {
        return details($_POST);
    }
    db_conn('cubit');
    if (isset($printsales)) {
        $Sl = "SELECT * FROM settings WHERE constant='SALES'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('SALES','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='SALES' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='SALES' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    if (!isset($bodydata)) {
        $bodydata = "";
    }
    if (!isset($counter)) {
        $counter = "";
    }
    $bodydata = str_replace("'", "", $bodydata);
    $bodydata = str_replace("  ", " ", $bodydata);
    $bodydata = str_replace("&nbsp;&nbsp;", " ", $bodydata);
    $bodydata = str_replace(" &nbsp;", " ", $bodydata);
    $bodydata = str_replace("&nbsp; ", " ", $bodydata);
    $des[$counter] = $bodydata;
    # validate input
    require_lib("validate");
    $v = new validate();
    if (empty($ninv_year)) {
        list($ninv_year, $ninv_month, $ninv_day) = date("Y-m-d");
    }
    $odate = mkdate($ninv_year, $ninv_month, $ninv_day);
    $v->isOk($odate, "date", 1, 1, "Invalid Date.");
    # used to generate errors
    $error = "asa@";
    // check the invoice details
    $v->isOK($cusname, "string", 1, 100, "Invalid customer name");
    $v->isOK($cusaddr, "string", 0, 400, "Invalid customer address");
    $v->isOK($cusvatno, "string", 0, 50, "Invalid customer vat number");
    $v->isOK($docref, "string", 0, 20, "Invalid Document Reference No.");
    $v->isOK($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    if ($chrgvat != "yes" && $chrgvat != "no" && $chrgvat != "none") {
        $v->addError($chrgvat, "Invalid vat option");
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "float", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            //		$v->isOk ($des[$keys], "url", 1, 255, "Invalid Description.");
            if ($qty <= 0) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity can't be zero or less. Product number: <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 16, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['chrgvat'] = $chrgvat;
    # check if purchase has been printed
    if ($inv['done'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $vatamount = 0;
    $showvat = TRUE;
    # insert purchase to DB
    db_conn("cubit");
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # remove old items
    $sql = "DELETE FROM nons_inv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod)) {
                if (in_array($keys, $remprod)) {
                    # skip product (wonder if $keys still align)
                    $amt[$keys] = 0;
                    continue;
                } else {
                    # Calculate amount
                    $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                    if (!isset($vatcodes[$keys])) {
                        $vatcodes[$keys] = 0;
                    }
                    db_connect();
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                    $Ri = db_exec($Sl);
                    // 					if(pg_num_rows($Ri)<1) {
                    // 						return "Please select the vatcode for all your stock.";
                    // 					}
                    $vd = pg_fetch_array($Ri);
                    if ($vd['zero'] == "Yes") {
                        $excluding = "y";
                    } else {
                        $excluding = "";
                    }
                    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                        $showvat = FALSE;
                    }
                    $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, 0, $vd['vat_amount']);
                    $vrs = explode("|", $vr);
                    $ivat = $vrs[0];
                    $iamount = $vrs[1];
                    $vatamount += $ivat;
                    $vate = 'n';
                    if (isset($vatex) && in_array($keys, $vatex) || $vd['zero'] == "Yes") {
                        $taxex += $amt[$keys];
                        $vate = 'y';
                    }
                    $vate = $vatcodes[$keys];
                    # insert purchase items
                    $sql = "\n\t\t\t\t\t\tINSERT INTO nons_inv_items (\n\t\t\t\t\t\t\tinvid, qty, amt, unitcost, description, vatex, div\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}', '{$vate}', '" . USER_DIV . "'\n\t\t\t\t\t\t)";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                }
            } else {
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                if (!isset($vatcodes[$keys])) {
                    $vatcodes[$keys] = 0;
                }
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                // 				if(pg_num_rows($Ri) < 1) {
                // 					return "Please select the vatcode for all your stock.";
                // 				}
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, 0, $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                $vate = 'n';
                if (isset($vatex) && in_array($keys, $vatex) || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $vate = 'y';
                }
                $vate = $vatcodes[$keys];
                db_connect();
                # insert purchase items
                $sql = "\n\t\t\t\t\tINSERT INTO nons_inv_items (\n\t\t\t\t\t\tinvid, qty, amt, unitcost, description, vatex, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}', '{$vate}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Done'>| <input name='print' type='submit' value='Process'>";
        }
    } else {
        $_POST["done"] = "";
    }
    $_POST['showvat'] = $showvat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "no") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        // 		$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
    } elseif ($chrgvat == "yes") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        // 		$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
    } else {
        $subtotal = sprint($sub);
        $traddiscmt = sprint($subtotal);
        $subtotal = sprint($subtotal);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- Clac ---
    	# calculate subtot
    	if( isset($amt) ){
    		$SUBTOT = array_sum($amt);
    	}else{
    		$SUBTOT = 0.00;
    	}
    
    	$SUBTOT -= $taxex;
    
    	$VATP = TAX_VAT;
    	if($chrgvat == "no"){
    		$SUBTOT = $SUBTOT;
    	}elseif($chrgvat == "yes"){
    		$SUBTOT = sprint(($SUBTOT * 100)/(100 + $VATP));
    	}else{
    		$SUBTOT = ($SUBTOT);
    	}
    
    	if($chrgvat != "none"){
    		$VAT = sprint($SUBTOT * ($VATP/100));
    	}else{
    		$VAT = 0;
    	}
    
    	$TOTAL = sprint($SUBTOT + $VAT + $taxex);
    	$SUBTOT += $taxex;
    
    	/* --- End Clac --- */
    $salespn = remval($salespn);
    if (!isset($bankid)) {
        if (isset($cusnum) and strlen($cusnum) > 0) {
            #get bankid from customer info
            $get_cbank = "SELECT bankid FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
            $run_cbank = db_exec($get_cbank) or errDie("Unable to get bank information for customer.");
            if (pg_numrows($run_cbank) > 0) {
                $bankid = pg_fetch_result($run_cbank, 0, 0);
            } else {
                $bankid = "2";
            }
        } else {
            $bankid = "2";
        }
    }
    # insert purchase to DB
    $sql = "\n\t\tUPDATE nons_invoices \n\t\tSET salespn='{$salespn}', cusname = '{$cusname}', cusaddr = '{$cusaddr}', \n\t\t\tcusvatno = '{$cusvatno}', cordno = '{$cordno}', docref = '{$docref}', \n\t\t\tchrgvat = '{$chrgvat}', odate = '{$odate}', terms = '{$terms}', \n\t\t\tsubtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', \n\t\t\tremarks = '{$remarks}', bankid = '{$bankid}' \n\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (isset($print)) {
        $OUTPUT = "<script>printer('nons-invoice-print.php?invid={$invid}');move('nons-invoice-new.php');</script>";
        require "template.php";
    }
    if (!isset($doneBtn)) {
        return details($_POST);
    } else {
        //$rslt = db_exec($sql) or errDie("Unable to update invoices status in Cubit.$sql",SELF);
        # Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>New Non-Stock Invoices</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Non-Stock Invoices for Customer <b>{$cusname}</b> has been recorded.</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='nons-invoice-view.php'>View Non-Stock Invoices</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    }
}
function write($_POST)
{
    extract($_POST);
    #only process details if we are not changing the customer
    if (isset($customer_select) and isset($old_customer_select) and $customer_select != $old_customer_select) {
        return details($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $sdate = $sord_year . "-" . $sord_month . "-" . $sord_day;
    if (!checkdate($sord_month, $sord_day, $sord_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    // check the sales order details
    $v->isOK($cusname, "string", 1, 100, "Invalid customer name");
    $v->isOK($cusaddr, "string", 0, 100, "Invalid customer address");
    $v->isOK($cusvatno, "string", 0, 50, "Invalid customer vat number");
    if ($chrgvat != "yes" && $chrgvat != "no" && $chrgvat != "none") {
        $v->addError($chrgvat, "Invalid vat option");
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($des[$keys], "string", 1, 255, "Invalid Description.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- invoices Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['chrgvat'] = $chrgvat;
    # check if purchase has been printed
    if ($inv['done'] == "y") {
        $error = "<li class='err'> Error : sales order number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $taxex = 0;
    $vatamount = 0;
    $showvat = TRUE;
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_connect();
    /* -- Start remove old items -- */
    # remove old items
    $sql = "DELETE FROM nons_inv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update sales order items in Cubit.", SELF);
    /* -- End remove old items -- */
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod) && in_array($keys, $remprod)) {
            } else {
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                if (!isset($vatcodes[$keys])) {
                    $vatcodes[$keys] = 0;
                }
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                // 				if(pg_num_rows($Ri)<1) {
                // 					return "Please select the vatcode for all your stock.";
                // 				}
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, 0, $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                $vate = 'n';
                if (isset($vatex) && in_array($keys, $vatex) || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $vate = 'y';
                }
                $vate = $vatcodes[$keys];
                # insert purchase items
                $sql = "\n\t\t\t\t\tINSERT INTO nons_inv_items (\n\t\t\t\t\t\tinvid, qty, amt, unitcost, description, div, vatex\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}', '" . USER_DIV . "', '{$vate}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert sales order items to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = "&nbsp; | &nbsp;<input name='doneBtn' type='submit' value='Done'>\n\t\t\t&nbsp; | &nbsp;<input type='submit' name='donePrnt' value='Done, Print and make another'>";
        }
    } else {
        $_POST["done"] = "";
    }
    $_POST['showvat'] = $showvat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "no") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        //	$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
    } elseif ($chrgvat == "yes") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        // 		$VAT = sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = $vatamount;
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
    } else {
        $subtotal = sprint($sub);
        $traddiscmt = sprint($subtotal);
        $subtotal = sprint($subtotal);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- Clac ---
    	# calculate subtot
    	if( isset($amt) ){
    		$SUBTOT = array_sum($amt);
    	}else{
    		$SUBTOT = 0.00;
    	}
    
    	$SUBTOT -= $taxex;
    
    	$VATP = TAX_VAT;
    	if($chrgvat == "no"){
    		$SUBTOT = $SUBTOT;
    	}elseif($chrgvat == "yes"){
    		$SUBTOT = sprint(($SUBTOT * 100)/(100 + $VATP));
    	}else{
    		$SUBTOT = ($SUBTOT);
    	}
    
    	if($chrgvat != "none"){
    		$VAT = sprint($SUBTOT * ($VATP/100));
    	}else{
    		$VAT = 0;
    	}
    
    	$TOTAL = sprint($SUBTOT + $VAT + $taxex);
    	$SUBTOT += $taxex;*/
    # insert purchase to DB
    $sql = "\n\t\tUPDATE nons_invoices \n\t\tSET cusname = '{$cusname}', cusaddr = '{$cusaddr}', cusvatno = '{$cusvatno}', cusordno = '{$cusordno}', \n\t\t\tchrgvat = '{$chrgvat}', odate = '{$sdate}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', \n\t\t\tremarks = '{$remarks}' \n\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update sales order in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (isset($donePrnt)) {
        $OUTPUT = "\n\t\t\t<script>\n\t\t\t\tprinter('nons-sorder-print.php?invid={$invid}');\n\t\t\t\tmove('nons-sorder-new.php');\n\t\t\t</script>";
        return $OUTPUT;
    }
    if (!isset($doneBtn)) {
        return details($_POST);
    } else {
        $rslt = db_exec($sql) or errDie("Unable to update invoices status in Cubit.", SELF);
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>New Non-Stock Sales Orders</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Non-Stock Sales Orders for Customer <b>{$cusname}</b> has been recorded.</td>\n\t\t\t\t\t<td><a target='_blank' href='nons-sorder-print.php?invid={$invid}'>Print Order</a></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='nons-sorder-view.php'>View Non-Stock Sales Orders</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    }
}
function write($_POST)
{
    #get vars
    extract($_POST);
    if (isset($Cancel)) {
        db_connect();
        $Sl = "DELETE FROM sorders WHERE sordid='{$sordid}' AND cusnum=0 AND div = '" . USER_DIV . "'";
        $Rs = db_exec($Sl) or errDie("Unable to delete Sales Order information");
        $sordid--;
        $Sql = "SELECT setval('sorders_sordid_seq', '{$sordid}')";
        $Rslt = db_exec($Sql) or errDie("Unable to set salesorder id.");
        header("Location: main.php");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($sordid, "num", 1, 20, "Invalid Sales Order 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($sord_day, "num", 1, 2, "Invalid Sales Order Date day.");
    $v->isOk($sord_month, "num", 1, 2, "Invalid Sales Order Date month.");
    $v->isOk($sord_year, "num", 1, 5, "Invalid Sales Order Date year.");
    $v->isOk($ddate_day, "num", 1, 2, "Invalid Delivery Date day.");
    $v->isOk($ddate_month, "num", 1, 2, "Invalid Delivery Date month.");
    $v->isOk($ddate_year, "num", 1, 5, "Invalid Delivery Date year.");
    $v->isOk($proforma, "string", 1, 3, "Invalid Proforma Invoice Selection.");
    $v->isOk($pinvnum, "num", 1, 20, "Invalid Proforma Invoice Number.");
    if (!isset($ria)) {
        $ria = "";
    }
    $v->isOk($ria, "string", 0, 20, "Invalid stock code(fist letters).");
    $odate = $sord_year . "-" . $sord_month . "-" . $sord_day;
    if (!checkdate($sord_month, $sord_day, $sord_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Sales Order Date.");
    }
    $ddate = $ddate_year . "-" . $ddate_month . "-" . $ddate_day;
    if (!checkdate($ddate_month, $ddate_day, $ddate_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Sales Order 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);
    }
    $msg = "";
    if (isset($pur)) {
        print $pur[0];
        foreach ($pur as $id => $value) {
            for ($i = 0; $i < $pqty[$id]; $i++) {
                $sql = "INSERT INTO manufact.required_purchases (stock_id, jobcard_id) VALUES ('{$id}', '{$job_id[$id]}')";
                db_exec($sql) or errDie("Unable to create new required purchases.");
            }
        }
        return details($_POST);
    }
    # Get Sales Order info
    db_connect();
    $sql = "SELECT * FROM sorders WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
    $sordRslt = db_exec($sql) or errDie("Unable to get Sales Order information");
    if (pg_numrows($sordRslt) < 1) {
        return "<li>- Sales Order Not Found</li>";
    }
    $sord = pg_fetch_array($sordRslt);
    $sord['chrgvat'] = $chrgvat;
    # check if Sales Order has been printed
    if ($sord['accepted'] == "y") {
        $error = "<li class='err'> Error : Sales Order number <b>{$sordid}</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 sord_data WHERE sordid = '{$sordid}' 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);
        $sord['deptid'] = $cust['deptid'];
        # If customer was just selected, get the following
        if ($sord['cusnum'] == 0) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
        }
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$sord['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 Sales Order to DB
    db_connect();
    $vatamount = 0;
    $showvat = TRUE;
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    // Add to required purchases
    if (isset($pur)) {
        foreach ($pur as $key => $value) {
            for ($i = 0; $i < $qtys[$key]; $i++) {
                $sql = "INSERT INTO manufact.required_purchases (jobcard_id, stock_id) VALUES ('{$job_id[$key]}', '{$stkids[$key]}')";
                db_exec($sql) or errDie("Unable to add required purchase.");
            }
        }
    }
    /* -- Start remove old items -- */
    # get selected stock in this Sales Order
    db_connect();
    $sql = "SELECT * FROM sorders_items  WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(alloc + qty)
        $sql = "SELECT alloc FROM cubit.stock WHERE stkid='{$stkt['stkid']}'";
        $stkalloc_rslt = db_exec($sql) or errDie("Unable to retrieve allocation.");
        $stkalloc = pg_fetch_result($stkalloc_rslt, 0);
        // Prevent minus minus a minus going positive
        if ($stkalloc < 0 && $stkt["qty"] < 0) {
            $alloc_amt = $stkalloc + $stkt["qty"];
        } else {
            $alloc_amt = $stkalloc - $stkt["qty"];
        }
        $sql = "UPDATE stock SET alloc='{$alloc_amt}' 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 sorders_items WHERE sordid='{$sordid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Sales Order 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) {
                $sql = "SELECT csprice, selamt FROM cubit.stock WHERE stkid='{$stkids[$keys]}'";
                $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
                list($csprice, $selamt) = pg_fetch_array($stock_rslt);
                if ($csprice > $unitcost[$keys]) {
                    if ($csprice > $selamt) {
                        $unitcost[$keys] = $csprice;
                    } else {
                        $unitcost[$keys] = $selamt;
                    }
                    $msg .= "<li class='err'>Unit price cannot be lower than cost price.</li>";
                }
                $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], $sord['chrgvat'], $excluding, $sord['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
                if (!isset($job_id[$keys]) || empty($job_id[$keys])) {
                    $job_id[$keys] = 0;
                }
                $sql = "\n\t\t\t\t\tINSERT INTO sorders_items (\n\t\t\t\t\t\tsordid, whid, stkid, qty, unitcost, amt, \n\t\t\t\t\t\tdisc, discp, div, vatcode, description, \n\t\t\t\t\t\taccount, jobcard_id\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sordid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '" . USER_DIV . "', '{$vatcodes[$keys]}', '{$descriptions[$keys]}', \n\t\t\t\t\t\t'{$accounts[$keys]}', '{$job_id[$keys]}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            } else {
                $sql = "SELECT csprice, selamt FROM cubit.stock WHERE stkid='{$stkids[$keys]}'";
                $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
                list($csprice, $selamt) = pg_fetch_array($stock_rslt);
                if ($csprice > $unitcost[$keys]) {
                    $unitcost[$keys] = $selamt;
                    $msg .= "<li class='err'>Unit price cannot be lower than cost price.</li>";
                }
                # 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], $sord['chrgvat'], $excluding, $sord['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($job_id[$keys]) || empty($job_id[$keys])) {
                    $job_id[$keys] = 0;
                }
                # insert Sales Order items
                $sql = "\n\t\t\t\t\tINSERT INTO sorders_items (\n\t\t\t\t\t\tsordid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\tamt, disc, discp, div,vatcode, jobcard_id\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sordid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t'{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '" . USER_DIV . "','{$vatcodes[$keys]}', '{$job_id[$keys]}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert Sales Order 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"] = "&nbsp; | &nbsp;<input name='doneBtn' type='submit' value='Done'>\n\t\t\t&nbsp; | &nbsp;<input type='submit' name='donePrnt' value='Done, Print and make another'>";
        }
    } else {
        $_POST["done"] = "";
    }
    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, $sord['chrgvat'], $excluding, $sord['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;
    # insert Sales Order to DB
    $sql = "\n\t\t\tUPDATE sorders \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}', \n\t\t\t\tterms = '{$terms}', salespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', \n\t\t\t\tsubtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', comm = '{$comm}', \n\t\t\t\tdiscount='{$traddiscmt}', delivery='{$delexvat}', display_costs='{$costs}', proforma = '{$proforma}', \n\t\t\t\tpinvnum = '{$pinvnum}', ddate = '{$ddate}' \n\t\t\tWHERE sordid = '{$sordid}'";
    $rslt = db_exec($sql) or errDie("Unable to update Sales Order in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM sord_data WHERE sordid='{$sordid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Sales Order data in Cubit.", SELF);
    # pu in new data
    $sql = "INSERT INTO sord_data(sordid, dept, customer, addr1, div) VALUES ('{$sordid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert Sales Order data to Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($donePrnt)) {
        // Accepted ?
        $sql = "SELECT set FROM cubit.picking_slip_setting";
        $set_rslt = db_exec($sql) or errDie("Unable to retrieve setting.");
        $set = pg_fetch_result($set_rslt, 0);
        if ($set == "y") {
            $accepted = ", accepted='y'";
        } else {
            $accepted = "";
        }
        $sql = "UPDATE sorders SET done='y' WHERE sordid='{$sordid}' AND div='" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to retrieve Sales Order status in Cubit.");
        $OUTPUT = "\n\t\t\t<script>\n\t\t\t\tprinter('sorder-print.php?invid={$sordid}');\n\t\t\t\tmove('sorder-new.php');\n\t\t\t</script>";
        return $OUTPUT;
    }
    if (isset($doneBtn)) {
        // Accepted ?
        $sql = "SELECT set FROM cubit.picking_slip_setting";
        $set_rslt = db_exec($sql) or errDie("Unable to retrieve setting.");
        $set = pg_fetch_result($set_rslt, 0);
        if ($set == "y") {
            $accepted = ", accepted='y'";
        } else {
            $accepted = "";
        }
        # insert Sales Order to DB
        $sql = "UPDATE sorders SET done = 'y' WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Sales 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 Sales Order</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>\n\t\t\t\t\t\tSales Order for customer <b>{$cust['cusname']} {$cust['surname']}</b>\n\t\t\t\t\t\thas been recorded.\n\t\t\t\t\t</td>\n\t\t\t\t\t<td><a href='javascript: printer(\"sorder-print.php?invid={$sordid}\");'>Print Sales Order</a></td>\n\t\t\t\t</tr>\n\t\t\t</table>" . mkQuickLinks(ql("sorder-view.php", "View Sales Orders"), ql("customers-new.php", "New Customer"));
        return $write;
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr><th>New Sales Order Saved</th></tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Sales Order 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("sorder-view.php", "View Sales Orders"), 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, $msg);
    }
    /* --- End button Listeners --- */
}
function write($_POST)
{
    # get vars
    extract($_POST);
    if (isset($back)) {
        return details($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($odate, "date", 1, 14, "Invalid Invoice note date.");
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    $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, "float", 1, 15, "Invalid Returned Quantity.");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount.");
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "Invalid Returned Quantity.");
    }
    # check stkids[]
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "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.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "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 "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $notenum = divlastid('note', USER_DIV);
    /* --- Start Products Display --- */
    $vatamount = 0;
    # Products layout
    $products = "";
    $taxex = 0;
    $ai = 0;
    $amt = array();
    foreach ($qtys as $keys => $value) {
        db_connect();
        # 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);
        # get selected stock in this invoice
        $sql = "SELECT * FROM inv_items  WHERE id = '{$ids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        if ($stkd['account'] == 0) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # Calculate the Discount discount
            if ($disc[$keys] < 1) {
                if ($discp[$keys] > 0) {
                    $disc[$keys] = $discp[$keys] / 100 * $stkd['unitcost'];
                }
            } else {
                $discp[$keys] = $disc[$keys] * 100 / $stkd['unitcost'];
            }
            # Calculate amount
            $amt[$keys] = $qtys[$keys] * ($stkd['unitcost'] - $disc[$keys]);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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);
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $taxex += $amt[$keys];
            }
            if ($vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            $vatamount += $ivat;
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            db_conn("exten");
            # put in product
            $products .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td><input type='hidden' name='stkids[{$ai}]' value='{$stk['stkid']}'>{$stk['stkcod']}</td>\n\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t<td><input type='hidden' size='5' name='qtys[{$ai}]' value='{$qtys[$keys]}'>{$qtys[$keys]}</td>\n\t\t\t\t\t<td nowrap>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t\t<td nowrap><input type='hidden' name='amt[{$ai}]' value='{$amt[$keys]}'>" . CUR . " {$amt[$keys]}</td>\n\t\t\t\t</tr>";
            ++$ai;
        } else {
            # get warehouse name
            db_conn("core");
            $sql = "SELECT accname FROM accounts WHERE accid = '{$stkd['account']}'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $discp[$keys] = 0;
            # Calculate amount
            $amt[$keys] = $qtys[$keys] * ($stkd['unitcost'] - $disc[$keys]);
            $nons_amt[$keys] = $qtys[$keys] * ($stkd['unitcost'] - $disc[$keys]);
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $taxex += $amt[$keys];
            }
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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);
            $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            $vatamount += $ivat;
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            db_conn("exten");
            $wh['whname'] = "";
            $stk['stkid'] = 0;
            $stk['stkcod'] = $wh['accname'];
            $stk['stkdes'] = $stkd['description'];
            # put in product
            $products .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td><input type='hidden' name='stkids[{$ai}]' value='{$stk['stkid']}'>{$stk['stkcod']}</td>\n\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t<td><input type='hidden' size='5' name='qtys[{$ai}]' value='{$qtys[$keys]}'>{$qtys[$keys]}</td>\n\t\t\t\t\t<td nowrap>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t\t<td nowrap><input type='hidden' name='amt[{$ai}]' value='{$amt[$keys]}'>" . CUR . " {$amt[$keys]}</td>\n\t\t\t\t</tr>";
            ++$ai;
        }
    }
    # 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);
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
    $Ri = db_exec($Sl);
    $vd = pg_fetch_array($Ri);
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    $vr = vatcalc($delchrg, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $DELVAT = $vrs[0];
    if ($vd['zero'] == "Yes") {
        $DELVAT = 0;
    }
    // 		db_conn('cubit');
    // 		$Sl="SELECT * FROM vatcodes WHERE id='$inv[delvat]'";
    // 		$Ri=db_exec($Sl);
    //
    // 		$vd=pg_fetch_array($Ri);
    //
    // 		$vr=vatcalc($amt[$keys],$inv['chrgvat'],$excluding,$inv['traddisc'],$vd['vat_amount']);
    // 		$vrs=explode("|",$vr);
    // 		$ivat=$vrs[0];
    // 		$iamount=$vrs[1];
    //
    // 		$vatamount += $ivat;
    // 		if(pg_num_rows($Ri)>0) {
    // 			$taxex += $delchrg;
    // 		}
    /* --- ----------- Clac ---------------------
    
    	# calculate subtot
    	$SUBTOT = 0.00;
    	if(isset($amt))
    		$SUBTOT = array_sum($amt);
    
    	$SUBTOT -= $taxex;
    
    	# duplicate
    	$SUBTOTAL = $SUBTOT;
    
    	$VATP = TAX_VAT;
    	if($inv['chrgvat'] == "exc"){
    		$SUBTOTAL = $SUBTOTAL;
    		$delexvat= ($delchrg);
    	}elseif($inv['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($inv['chrgvat'] != "nov"){
    		$VAT = sprint($EXVATTOT * ($VATP/100));
    	}else{
    		$VAT = 0;
    	}
    
    	$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    	$SUBTOT += $taxex;
    
    /* --- ----------- Clac --------------------- */
    # 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 class='err'>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    /* A quick fix by jupiter
    	$allnoted = true;
    	foreach($qtys as $keys => $value) {
    		$sql = "SELECT * FROM inv_items  WHERE id = '$ids[$keys]' AND invid ='$invid' AND div = '".USER_DIV."'";
    		$stkdRslt = db_exec($sql);
    		$stkd = pg_fetch_array($stkdRslt);
    		if($stkd['qty'] != $qtys[$keys]){
    			$allnoted = false;
    		}
    	}
    
    	if($allnoted){
    		$SUBTOT = sprint($inv['subtot']);
    		$VAT = sprint($inv['vat']);
    		$TOTAL = sprint($inv['total']);
    		$delchrg = sprint($inv['delivery']);
    		$traddiscmt = sprint($inv['discount']);
    		$SUBTOTAL = sprint($TOTAL - $VAT);
    	}
    /* End A quick fix by jupiter */
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $nons_total = 0.0;
    if (isset($nons_amt)) {
        $nons_total = sprint(array_sum($nons_amt));
    }
    $VATP = TAX_VAT;
    if ($inv['chrgvat'] == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //	$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = sprint($vatamount + $DELVAT);
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($inv['chrgvat'] == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = sprint($vatamount + $DELVAT);
        $TOTAL = sprint($subtotal);
        //$SUBTOT=sprint($TOTAL - $VAT - ($delchrg - $DELVAT));
        $SUBTOT = sprint($sub);
        $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----------------------
    if ($inv['balance'] >= $TOTAL) {
        $invpay = $TOTAL;
        $examt = 0;
    } else {
        $invpay = $inv['balance'];
        $examt = $TOTAL - $invpay;
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "z");
    /* - End Hooks - */
    # Todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $td = $odate;
    $refnum = getrefnum();
    /*refnum*/
    # Insert invoice to period DB
    db_conn($inv['prd']);
    # Insert invoice credit note to DB
    $sql = "\n\t\tINSERT INTO inv_notes (\n\t\t\tdeptid, notenum, invnum, invid, cusnum, cordno, ordno, \n\t\t\tchrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, \n\t\t\ttotal, comm, username, div, surname, cusaddr, cusvatno, \n\t\t\tdeptname, branch, bankid, prd\n\t\t) VALUES (\n\t\t\t'{$inv['deptid']}', '{$notenum}', '{$inv['invnum']}', '{$inv['invid']}', '{$inv['cusnum']}', '{$inv['cordno']}', '{$inv['ordno']}', \n\t\t\t'{$inv['chrgvat']}', '{$terms}', '{$traddiscmt}', '{$inv['salespn']}', '{$odate}', '{$delexvat}', '{$SUBTOT}', '{$VAT}' , \n\t\t\t'{$TOTAL}', '{$comm}', '" . USER_NAME . "', '" . USER_DIV . "', '{$inv['surname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', \n\t\t\t'{$inv['deptname']}', '{$inv['branch']}', '{$inv['bankid']}', '{$inv['prd']}'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice to Cubit.", SELF);
    # Get next ordnum
    $noteid = pglib_lastid("inv_notes", "noteid");
    db_connect();
    # Begin updating
    $nbal = $inv['nbal'] + $TOTAL;
    # Update the invoice (make balance less)
    $sql = "UPDATE invoices SET nbal = '{$nbal}', rdelchrg = (rdelchrg + '{$delchrg}'), balance = balance - '{$invpay}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Update the invoice (make balance less)
    $sql = "UPDATE open_stmnt SET balance = balance-'{$TOTAL}' WHERE invid = '{$inv['invnum']}'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Update the customer (make balance less)
    $sql = "UPDATE customers SET balance = (balance - '{$TOTAL}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Update invoice's discounts
    # $sql = "UPDATE inv_discs SET traddisc = (traddisc - '$traddiscm'), itemdisc = (itemdisc - '$discs') WHERE cusnum = '$inv[cusnum]' AND invid = '$invid'";
    # $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.",SELF);
    # record the payment on the statement
    $sql = "\n\t\tINSERT INTO stmnt (\n\t\t\tcusnum, invid, amount, date, \n\t\t\ttype, div, allocation_date\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$notenum}', '" . ($TOTAL - $TOTAL * 2) . "', '{$odate}', \n\t\t\t'Credit Note for invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$odate}'\n\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    $disc = 0;
    $commision = 0;
    # Commit updating
    $nsp = 0;
    # Make ledge record
    custledger($inv['cusnum'], $dept['incacc'], $td, $notenum, "Credit Note No. {$notenum} for invoice No. {$inv['invnum']}", $TOTAL, "c");
    $salesp = qrySalesPersonN($inv["salespn"]);
    if ($examt > 0) {
        # Make record for age analisys
        custCTP($examt, $inv['cusnum'], $td);
    }
    #recalculate the total cost amount for ONLY THE CREDITED ITEMS
    $ntcosamt = 0;
    foreach ($qtys as $keys => $value) {
        db_connect();
        # 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);
        # get selected stock in this invoice
        $sql = "SELECT * FROM inv_items  WHERE id = '{$ids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        if ($stkd['account'] == 0) {
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            db_connect();
            $Sl = "SELECT * FROM scr WHERE inv='{$inv['invnum']}' AND stkid='{$stkd['stkid']}' AND invid = '{$stkd['id']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) > 0) {
                $cd = pg_fetch_array($Ri);
                $stk['csprice'] = $cd['amount'];
            } else {
                $stk['csprice'] = 0;
            }
            # cost amount
            if ($stk['csprice'] == "0.00") {
                $cosamt = sprint($qtys[$keys] * $stk['lcsprice']);
            } else {
                $cosamt = sprint($qtys[$keys] * $stk['csprice']);
            }
            #add this cost amount to the new total
            $ntcosamt += $cosamt;
            db_connect();
            # Update stock(onhand + qty)
            $sql = "UPDATE stock SET csamt = (csamt + '{$cosamt}'), units = (units + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            # fix stock cost amount
            $Sl = "UPDATE stock set csprice=csamt/units WHERE stkid = '{$stkids[$keys]}' AND units>0";
            $Ri = db_exec($Sl) or errDie("Unable to update stock cost price in Cubit.", SELF);
            if ($stk['serd'] == 'yes') {
                ext_InSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $notenum, 'note', $td);
            }
            # negetive values to minus profit
            $nqty = $qtys[$keys] * 1;
            $namt = $amt[$keys] * -1;
            $ncsprice = $cosamt * -1;
            $noted = $stkd['noted'] + $qtys[$keys];
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            stockrec($stkd['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $td, $nqty, $cosamt, "Credit note for Customer : {$inv['surname']} - Credit note No. {$notenum}");
            # Get amount exluding vat if including and not exempted
            $VATP = TAX_VAT;
            $amtexvat = $amt[$keys];
            ###################VAT CALCS#######################
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            $vatamount += $ivat;
            vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "VAT for Credit note: {$notenum} Customer : {$inv['cusname']} {$inv['surname']}", -$iamount, -$ivat);
            if ($excluding == "y") {
                $exvatamt = $iamount;
            } else {
                $exvatamt = $iamount - $ivat;
            }
            ####################################################
            $sql = "\n\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, \n\t\t\t\t\tcsamt, details, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$td}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'note', '{$qtys[$keys]}', '{$amtexvat}', \n\t\t\t\t\t'{$cosamt}', 'Credit note for Customer : {$inv['surname']} - Credit note No. {$notenum}', '" . USER_DIV . "'\n\t\t\t\t)";
            $recRslt = db_exec($sql);
            # Get selected stock in this invoice
            $sql = "UPDATE inv_items SET noted = '{$noted}' WHERE id = '{$ids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
            $stkdsRslt = db_exec($sql);
            $stkds = pg_fetch_array($stkdsRslt);
            # get accounts
            db_conn("exten");
            $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $stockacc = $wh['stkacc'];
            $cosacc = $wh['cosacc'];
            # sales rep commission
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = $stk["com"];
            }
            $commision = $commision + coms($inv['salespn'], $exvatamt, $itemcommission);
            writetrans($stockacc, $cosacc, $td, $refnum, $cosamt, "Cost Of Sales for Credit note No. {$notenum} for Customer: {$inv['cusname']} {$inv['surname']}");
            db_conn($inv['prd']);
            # insert invoice items
            $sql = "\n\t\t\t\tINSERT INTO inv_note_items (\n\t\t\t\t\tnoteid, whid, stkid, qty, amt, div, vatcode\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$noteid}', '{$stkd['whid']}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "', '{$stkd['vatcode']}'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            db_connect();
            $sql = "\n\t\t\t\tINSERT INTO salesrec (\n\t\t\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$odate}', '{$noteid}', '{$notenum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'nstk', '" . USER_DIV . "'\n\t\t\t\t)";
            $recRslt = db_exec($sql);
        } else {
            # Keep track of discounts
            //$disc += ($stkd['disc'] * $stkd['qty']);
            # negetive values to minus profit
            $nqty = $qtys[$keys] * 1;
            $namt = $amt[$keys] * -1;
            //$ncsprice = ($cosamt * (-1));
            $noted = $stkd['noted'] + $qtys[$keys];
            # Get amount exluding vat if including and not exempted
            $VATP = TAX_VAT;
            $amtexvat = $amt[$keys];
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            $vatamount += $ivat;
            vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "VAT for Credit note: {$notenum} Customer : {$inv['cusname']} {$inv['surname']}", -$iamount, -$ivat);
            if ($excluding == "y") {
                $exvatamt = $iamount;
            } else {
                $exvatamt = $iamount - $ivat;
            }
            ####################################################
            if ($inv['chrgvat'] == "exc") {
                $nvat = $stkd['amt'] / 100 * $vd['vat_amount'];
                $ncosamt = round($stkd['qty'] * $stkd['amt'] + $nvat, 2);
            } else {
                $nvat = $stkd['amt'] / (100 + $vd['vat_amount']) * $vd['vat_amount'];
                $ncosamt = round($stkd['qty'] * $stkd['amt'], 2);
            }
            $ntcosamt += $ncosamt;
            ####################################################
            # Get selected stock in this invoice
            $sql = "UPDATE inv_items SET noted = '{$noted}' WHERE id = '{$ids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
            $stkdsRslt = db_exec($sql);
            $stkds = pg_fetch_array($stkdsRslt);
            $nsp += sprint($iamount - $ivat);
            //writetrans($cosacc, $stockacc,$inv['odate'] , $refnum, $cosamt, "Cost Of Sales for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
            writetrans($stkd['account'], $dept['debtacc'], $td, $refnum, $iamount - $ivat, "Debtors control for Credit note: {$notenum} Customer : {$inv['cusname']} {$inv['surname']}");
            //# dt(stock) ct(cos)
            //	writetrans($stockacc, $cosacc, $td, $refnum, $cosamt, "Cost Of Sales for Credit note No. $notenum for Customer : $inv[cusname] $inv[surname]");
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = $stk["com"];
            }
            $commision = $commision + coms($inv['salespn'], $exvatamt, $itemcommission);
            db_conn($inv['prd']);
            # insert invoice items
            $sql = "\n\t\t\t\tINSERT INTO inv_note_items (\n\t\t\t\t\tnoteid, whid, stkid, qty, amt, div, description, vatcode\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$noteid}', '{$stkd['account']}', '0', '{$qtys[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "', '{$stkd['description']}', '{$stkd['vatcode']}'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            db_connect();
            $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\tVALUES('{$odate}', '{$noteid}', '{$notenum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'nnon', '" . USER_DIV . "')";
            $recRslt = db_exec($sql);
        }
    }
    db_connect();
    # save invoice discount
    $sql = "INSERT INTO inv_discs(cusnum, invid, traddisc, itemdisc, inv_date, delchrg, div) VALUES('{$inv['cusnum']}', '{$invid}', '0', '-{$disc}', '{$inv['odate']}', '0', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    /* - Start Transactoins - */
    //	###################VAT CALCS#######################
    //	db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    //
    $vd = pg_fetch_array($Ri);
    //
    $excluding = "";
    //
    $vr = vatcalc($delexvat, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    //
    //	if($vd['zero']=="Yes") {
    //		$ivat=0;
    //	}
    //
    //	$vatamount += $ivat;
    //
    vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "VAT for Credit note No. {$notenum}, Customer : {$inv['cusname']} {$inv['surname']}", sprint(-$iamount - $ivat), -$ivat);
    //
    //	####################################################
    com_invoice($inv['salespn'], -($TOTAL - $VAT), -$commision, $inv['invnum'], $td, true);
    if ($TOTAL - $VAT - $nsp > 0) {
        # dt(income) ct(debtors)
        writetrans($dept['incacc'], $dept['debtacc'], $td, $refnum, $TOTAL - $VAT - $nsp, "Debtors Control for Credit note No. {$notenum} for Customer : {$inv['cusname']} {$inv['surname']}");
    }
    # dt(vat) ct(debtors)
    writetrans($vatacc, $dept['debtacc'], $td, $refnum, $VAT, "VAT Return for Credit note No. {$notenum} for Customer : {$inv['cusname']} {$inv['surname']}");
    db_connect();
    //	$sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)
    //	VALUES('$odate', '$noteid', '$notenum', '$dept[debtacc]', '$VAT', '$TOTAL', 'nstk', '".USER_DIV."')";
    //	$recRslt = db_exec($sql);
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t('{$inv['cusnum']}','{$inv['surname']}','Credit Note:{$notenum}, Invoice {$inv['invnum']}','{$odate}','" . -sprint($TOTAL - $VAT) . "','-{$VAT}','" . -sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* - End Transactoins - */
    $OUTPUT = "\n\t\t<script>\n\t\t\tsCostCenter('ct', 'Credit Note', '{$odate}', 'Credit Note for Invoice No.{$inv['invnum']} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($TOTAL - $VAT - $nons_total) . "', 'Cost Of Sales for Credit Note for Invoice No.{$inv['invnum']}', '{$ntcosamt}', '');\n\t\t\tprinter('invoice-note-reprint.php?noteid={$noteid}&prd={$inv['prd']}&cccc=yes&reprint=no');\n\t\t\tmove('main.php');\n\t\t</script>";
    require "template.php";
}
Esempio n. 11
0
/**
 * calculates vat, returns array(vat, total, subtotal)
 *
 * @param float $sub subtotal
 * @param string $chrgvat do vat calculation
 * @param string $exvat exempt from vat
 * @param float $traddisc trade discount percentage
 * @param float $VATP vat percentage
 * @param array
 */
function vatcalca($sub, $chrgvat, $exvat, $traddisc, $vatperc)
{
    $a = explode("|", vatcalc($sub, $chrgvat, $exvat, $traddisc, $vatperc));
    return array("vat" => $a[0], "total" => $a[1], "subtotal" => $a[2]);
}
function write($_POST)
{
    # Set max execution time to 12 hours
    ini_set("max_execution_time", 43200);
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($invids as $key => $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid recuring invoice number.");
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $err;
    }
    $i = 0;
    foreach ($invids as $key => $invid) {
        # Get recuring invoice info
        db_connect();
        $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $invRslt = db_exec($sql) or errDie("Unable to get recuring invoice information");
        if (pg_numrows($invRslt) < 1) {
            return "<i class='err'>Not Found</i>";
        }
        $inv = pg_fetch_array($invRslt);
        # check if invoice has been printed
        if ($inv['printed'] == "y") {
            $error = "<li class='err'> Error : Invoice number <b>{$inv['invnum']}</b> has already been printed.";
            $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $error;
        }
        # check if invoice has been serialised
        if ($inv['serd'] == "n") {
            $error = "<li class='err'> Error : You must select serial numbers for some Items on Invoice No. <b>T {$invid}</b> before you can print it.";
            $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $error;
        }
        # Begin Updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        $invnum = divlastid('inv', USER_DIV);
        $Sl = "INSERT INTO ncsrec (oldnum, newnum, div) VALUES ('{$invid}', '{$invnum}', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert into db");
        # 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);
        }
        /* --- Start Products Display --- */
        # Products layout
        $commision = 0;
        $products = "";
        $disc = 0;
        # get selected stock in this invoice
        db_connect();
        $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        if (pg_numrows($stkdRslt) < 1) {
            $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has no items.</li>";
            if (($r2sid = r2sListCheck("invoice_stk_view")) !== false) {
                $error .= "<p><input type='button' onClick='document.location.href=\"r2srestore.php?r2sid={$r2sid}\";' value='List Invoices'>";
            } else {
                $error .= "<p><input type='button' onClick='document.location.href=\"invoice-view.php\";' value='List Invoices'>";
            }
            $OUTPUT = $error;
            pglib_transaction("ROLLBACK");
            require "template.php";
        }
        $taxex = 0;
        while ($stkd = pg_fetch_array($stkdRslt)) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            $sp = "&nbsp;&nbsp;&nbsp;&nbsp;";
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes') {
                $taxex += $stkd['amt'];
            }
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            # Insert stock record
            $sdate = date("Y-m-d");
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            # Get amount exluding vat if including and not exempted
            //			$VATP = TAX_VAT;
            #get the actual vat perc of this item
            $get_vat = "SELECT vat_amount FROM vatcodes WHERE id = '{$stkd['vatcode']}' LIMIT 1";
            $run_vat = db_exec($get_vat) or errDie("Unable to get vat percentage information");
            if (pg_numrows($run_vat) < 1) {
                $VATP = 0;
            } else {
                $varr = pg_fetch_array($run_vat);
                $VATP = $varr['vat_amount'];
            }
            $amtexvat = sprint($stkd['amt']);
            if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes') {
                $amtexvat = sprint($stkd['amt'] * 100 / (100 + $VATP));
            }
            if ($stkd['account'] == 0) {
                db_connect();
                $sql = "\n\t\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, \n\t\t\t\t\t\tcsprice, csamt, details, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sdate}', '{$stkd['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'invoice', '{$stkd['qty']}', \n\t\t\t\t\t\t'{$amtexvat}', '{$csprice}', 'Stock sold - Invoice No. {$invnum}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $recRslt = db_exec($sql);
                # Sales rep commission
                //				$commision = $commision + coms($inv['salespn'], $stkd['amt'], $stk['com']);
                $commision = $commision + coms($inv['salespn'], $amtexvat, $stk['com']);
            }
        }
        /* --- Start Some calculations --- */
        # Subtotal
        $SUBTOT = sprint($inv['subtot']);
        # Calculate tradediscm
        if (strlen($inv['traddisc']) > 0) {
            $traddiscm = sprint($inv['traddisc'] / 100 * $SUBTOT);
        } else {
            $traddiscm = "0.00";
        }
        # Calculate subtotal
        $VATP = TAX_VAT;
        $SUBTOTAL = sprint($inv['subtot']);
        $VAT = sprint($inv['vat']);
        $TOTAL = sprint($inv['total']);
        $inv['delchrg'] = sprint($inv['delchrg']);
        com_invoice($inv['salespn'], $TOTAL - $VAT, $commision, $invnum, $inv["odate"]);
        /* --- End Some calculations --- */
        /* - Start Hooks - */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "out");
        /* - End Hooks - */
        # Todays date
        $date = date("d-m-Y");
        $sdate = date("Y-m-d");
        $refnum = getrefnum();
        /* --- Updates ---- */
        db_connect();
        $Sql = "UPDATE invoices SET printed ='y', done ='y', invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
        # Record the payment on the statement
        $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "', '{$inv['odate']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Record the payment on the statement
        $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}','{$inv['total']}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Save invoice discount
        $sql = "INSERT INTO inv_discs(cusnum, invid, traddisc, itemdisc, inv_date, delchrg, div,total) VALUES('{$inv['cusnum']}', '{$invnum}', '{$traddiscm}', '{$disc}', '{$inv['odate']}', '{$inv['delchrg']}', '" . USER_DIV . "', ({$SUBTOT}+{$inv['delchrg']}))";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance more)
        $sql = "UPDATE customers SET balance = (balance + '{$inv['total']}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Make ledge record
        custledger($inv['cusnum'], $dept['incacc'], $inv["odate"], $invnum, "Invoice No. {$invnum}", $inv['total'], "d");
        $nsp = 0;
        db_connect();
        # get selected stock in this invoice
        $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $tcosamt = 0;
        while ($stkd = pg_fetch_array($stkdRslt)) {
            $stkd['account'] += 0;
            if ($stkd['account'] == 0) {
                db_connect();
                # get selamt from selected stock
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                if ($stk['units'] - $stkd['qty'] < 0) {
                    if ($stk['units'] <= 0) {
                        $cosamt = 0;
                    } else {
                        $cosamt = round($stk['units'] * $stk['csprice'], 2);
                    }
                } else {
                    $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
                }
                $uc = sprint($cosamt / $stkd['qty']);
                if ($stk['csprice'] > 0) {
                    $Sl = "INSERT INTO scr(inv,stkid,amount) VALUES ('{$invnum}','{$stkd['stkid']}','{$uc}')";
                    $Rg = db_exec($Sl);
                }
                # update stock(alloc - qty)
                $sql = "UPDATE stock SET csamt = (csamt - '{$cosamt}'),units = (units - '{$stkd['qty']}'),alloc = (alloc - '{$stkd['qty']}')  WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
                if ($stk['serd'] == 'yes') {
                    ext_invSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $invnum);
                }
                # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
                $sdate = date("Y-m-d");
                if ($stkd['account'] == 0) {
                    stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $sdate, $stkd['qty'], $cosamt, "Sold to Customer : {$inv['surname']} - Invoice No. {$invnum}");
                }
            }
            ###################VAT CALCS#######################
            db_connect();
            $stkd['vatcode'] += 0;
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            ####################################################
            if ($stkd['account'] == 0) {
                # get accounts
                db_conn("exten");
                $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                $stockacc = $wh['stkacc'];
                $cosacc = $wh['cosacc'];
                if ($cosamt > 0) {
                    # dt(cos) ct(stock)
                    //						writetrans($cosacc, $stockacc, $date, $refnum, $cosamt, "Cost Of Sales for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
                    writetrans($cosacc, $stockacc, $inv['odate'], $refnum, $cosamt, "Cost Of Sales for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
                }
                $tcosamt += $cosamt;
                db_connect();
                $date = date("Y-m-d");
                $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\t\t\tVALUES('{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'stk', '" . USER_DIV . "')";
                $recRslt = db_exec($sql);
            } else {
                $amtexvat = sprint($stkd['amt']);
                db_connect();
                $sdate = date("Y-m-d");
                $nsp += sprint($iamount - $ivat);
                //writetrans($cosacc, $stockacc,$inv['odate'] , $refnum, $cosamt, "Cost Of Sales for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
                writetrans($dept['debtacc'], $stkd['account'], $inv['odate'], $refnum, $iamount - $ivat, "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
                db_connect();
                $date = date("Y-m-d");
                $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\t\t\tVALUES('{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'non', '" . USER_DIV . "')";
                $recRslt = db_exec($sql);
            }
        }
        /* - Start Transactoins - */
        # dt(debtors) ct(income/sales)
        //			writetrans($dept['debtacc'], $dept['incacc'], $date, $refnum, sprint($TOTAL-$VAT-$nsp), "Debtors Control for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
        writetrans($dept['debtacc'], $dept['incacc'], $inv['odate'], $refnum, sprint($TOTAL - $VAT - $nsp), "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
        # dt(debtors) ct(vat account)
        writetrans($dept['debtacc'], $vatacc, $inv['odate'], $refnum, $VAT, "VAT Received on Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
        db_conn('cubit');
        $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t\t\t('{$inv['cusnum']}','{$inv['surname']}','Invoice {$invnum}','{$inv['odate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
        $Ri = db_exec($Sl);
        $ecost = sprint($TOTAL - $VAT);
        db_conn('cubit');
        $inv['jobid'] += 0;
        $Sl = "SELECT * FROM invc WHERE inv='{$inv['jobid']}'";
        $Ri = db_exec($Sl);
        if (CC_USE == "use") {
            if (pg_num_rows($Ri) > 0) {
                while ($data = pg_fetch_array($Ri)) {
                    db_conn('cubit');
                    $sql = "SELECT * FROM costcenters WHERE ccid = '{$data['cid']}'";
                    $ccRslt = db_exec($sql) or errDie("Unable to retrieve Cost centers from database.");
                    $cc = pg_fetch_array($ccRslt);
                    $amount = sprint($ecost * $data['amount'] / 100);
                    db_conn(PRD_DB);
                    $sql = "INSERT INTO cctran(ccid, trantype, typename, edate, description, amount, username, div)\n\t\t\t\t\t\tVALUES('{$cc['ccid']}', 'dt', 'Invoice', '{$inv['odate']}', 'Invoice No.{$invnum}', '{$amount}', '" . USER_NAME . "', '" . USER_DIV . "')";
                    $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
                }
            }
        }
        ####/*###*/############VAT CALCS#######################
        $inv['delvat'] += 0;
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            $Sl = "SELECT * FROM vatcodes";
            $Ri = db_exec($Sl);
        }
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        $vr = vatcalc($inv['delchrg'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
        ####################################################
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        $i++;
    }
    // Retrieve template settings
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        pdf($_POST);
    } else {
        templatePdf($_POST);
    }
    // Final Laytout
    $write = "\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>{$i} Invoices Proccesed</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Invoices has been successfully printed.</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='invoice-view.php'>View Invoices</a></td>\n\t\t</tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function details($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($inv['odate']) >= strtotime($blocked_date_from) and strtotime($inv['odate']) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    if ($inv['rounding'] > 0) {
        db_conn('core');
        $Sl = "SELECT * FROM salesacc WHERE name='rounding'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set the rounding account, under sales settings.";
        }
        $ad = pg_fetch_array($Ri);
        $rac = $ad['accnum'];
    }
    if ($inv['cusnum'] != "0") {
        #then get the actual customer
        db_connect();
        $get_cus = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' LIMIT 1";
        $run_cus = db_exec($get_cus) or errDie("Unable to get customer information");
        if (pg_numrows($run_cus) < 1) {
            #do nothing
        } else {
            $carr = pg_fetch_array($run_cus);
            $inv['cusname'] = "{$carr['cusname']}";
            $inv['surname'] = "{$carr['surname']}";
        }
    }
    $td = $inv['odate'];
    # 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;
    }
    db_conn('cubit');
    $sql = "SELECT stkid FROM pinv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
    $crslt = db_exec($sql);
    if (pg_numrows($crslt) < 1) {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has no items.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    if ($inv['terms'] == 1) {
        db_conn('core');
        $Sl = "SELECT * FROM salacc WHERE name='cc'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set a link for the POS credit card control account";
        }
        $cd = pg_fetch_array($Ri);
        $cc = $cd['accnum'];
    }
    $change = sprint(sprint($inv['pcash'] + $inv['pcheque'] + $inv['pcc'] + $inv['pcredit']) - sprint($inv['total'] - $inv['rounding']));
    $inv['pcash'] = sprint($inv['pcash'] - $change);
    if ($inv['pcash'] < 0) {
        $inv['pcash'] = 0;
    }
    if (sprint($inv['pcash'] + $inv['pcheque'] + $inv['pcc'] + $inv['pcredit']) != sprint($inv['total'] - $inv['rounding'])) {
        return "<li class='err'>The total of all the payments is not equal to the invoice total.<br>\n\t\tPlease edit the invoice and try again(You can only overpay with cash)</li>";
    }
    db_connect();
    # Begin updates
    #
    //lock(2);
    $invnum = divlastid('inv', USER_DIV);
    $Sl = "INSERT INTO ncsrec (oldnum,newnum, div) VALUES ('{$invid}','{$invnum}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert into db");
    //unlock(2);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # 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);
    }
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM pinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $taxex = 0;
    $commision = 0;
    $salesp = qrySalesPersonN($inv["salespn"]);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            db_connect();
            //this was set to the stock vatcode ??? must be the pur_item code ...
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "<li class='err'>Please select the vatcode for all your stock.</li>";
            }
            $vd = pg_fetch_array($Ri);
            $sp = "&nbsp;&nbsp;&nbsp;&nbsp;";
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "&nbsp;&nbsp;";
            }
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            # Insert stock record
            $sdate = date("Y-m-d");
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            # put in product
            $products .= "\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t\t<td>{$ex} {$sp} {$stk['stkdes']}</td>\n\t\t\t\t\t<td>{$stkd['qty']}</td>\n\t\t\t\t\t<td>" . sprint($stk["selamt"]) . "</td>\n\t\t\t\t\t<td>" . CUR . sprint($stkd["amt"]) . "</td>\n\t\t\t\t</tr>";
            # Get amount exluding vat if including and not exempted
            $VATP = TAX_VAT;
            $amtexvat = sprint($stkd['amt']);
            if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes') {
                $amtexvat = sprint($stkd['amt'] * 100 / (100 + $VATP));
            }
            $sql = "\n\t\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, \n\t\t\t\t\t\tcsamt, details, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$td}', '{$stkd['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'invoice', '{$stkd['qty']}', '{$stkd['amt']}', \n\t\t\t\t\t\t'{$csprice}', 'Stock sold - Invoice No. {$invnum}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = $stk["com"];
            }
            $commision = $commision + coms($inv['salespn'], $amtexvat, $itemcommission);
        } else {
            db_conn('core');
            $Sl = "SELECT * FROM accounts WHERE accid='{$stkd['account']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get account data.");
            $ad = pg_fetch_array($Ri);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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);
            $sp = "";
            # Check Tax Excempt
            if ($vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "";
            }
            # all must be excempted
            if ($inv['chrgvat'] == 'nov') {
                $ex = "#";
            }
            $VATP = TAX_VAT;
            $amtexvat = sprint($stkd['amt']);
            if ($inv['chrgvat'] == "inc") {
                $amtexvat = sprint($stkd['amt'] * 100 / (100 + $VATP));
            }
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = 0;
            }
            $commision = $commision + coms($inv['salespn'], $amtexvat, $itemcommission);
            # Put in product
            $products .= "\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>{$ex} {$sp} {$stkd['description']}</td>\n\t\t\t\t\t<td>{$stkd['qty']}</td>\n\t\t\t\t\t<td>" . sprint($stkd["unitcost"]) . "</td>\n\t\t\t\t\t<td>{$stkd['disc']}</td>\n\t\t\t\t\t<td>" . CUR . sprint($stkd["amt"]) . "</td>\n\t\t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOTAL = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $av = $VAT;
    $at = $TOTAL - $VAT;
    $nt = sprint($inv['pcredit']);
    $sd = date("Y-m-d");
    $ro = $inv['rounding'];
    $ro += 0;
    com_invoice($inv['salespn'], $TOTAL - $VAT, $commision, $invnum, $td, true);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "novat");
    /* - End Hooks - */
    $nsp = 0;
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    db_conn('cubit');
    if ($inv['cusnum'] > 0 && $nt > 0) {
        # Record the payment on the statement
        $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$inv['cusnum']}', '{$invnum}', '0', '{$nt}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "', '{$inv['odate']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Record the payment on the statement
        $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('{$inv['cusnum']}', '{$invnum}', '0', '{$nt}', '{$nt}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance more)
        $sql = "UPDATE customers SET balance = (balance + '{$nt}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        custledger($inv['cusnum'], $dept['incacc'], $inv['odate'], $invnum, "Invoice No. {$invnum}", $nt, "d");
        recordDT($nt, $inv['cusnum'], $inv['odate']);
        db_conn('cubit');
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$nt}','Credit','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    db_conn('cubit');
    if ($inv['terms'] == 1) {
        $Sl = "INSERT INTO crec(userid,username,amount,pdate,inv) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}')";
        $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    } else {
        $Sl = "INSERT INTO posrec(userid,username,amount,pdate,inv) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}')";
        $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    }
    if (!isset($inv['cusname']) or strlen($inv['cusname']) < 1) {
        $custname = $inv['surname'];
    } else {
        $custname = $inv['cusname'];
    }
    $Sl = "INSERT INTO pr(userid,username,amount,pdate,inv,cust,t) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}','{$custname}','{$inv['terms']}')";
    $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    $refnum = getrefnum();
    /*refnum*/
    $fcash = $inv['pcash'];
    $fccp = $inv['pcc'];
    $fcheque = $inv['pcheque'];
    $fcredit = $inv['pcredit'];
    /* --- Updates ---- */
    db_connect();
    $Sql = "UPDATE pinvoices SET pchange='{$change}',printed ='y', done ='y',invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
    # save invoice discount
    $sql = "INSERT INTO inv_discs(cusnum, invid, traddisc, itemdisc, inv_date, delchrg, div,total) VALUES('0','{$invnum}','{$inv['delivery']}','{$disc}', '{$inv['odate']}', '{$inv['delivery']}', '" . USER_DIV . "',({$SUBTOT}+{$inv['delivery']}))";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # get selected stock in this invoice
    $sql = "SELECT * FROM pinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            db_connect();
            # get selamt from selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            if ($stk['units'] - $stkd['qty'] < 0) {
                if ($stk['units'] < 0) {
                    $stk['units'] = 0;
                }
                $cosamt = round($stk['units'] * $stk['csprice'], 2);
            } else {
                $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
            }
            # cost amount
            //$cosamt = round(($stkd['qty'] * $stk['csprice']), 2);
            if ($stk['csprice'] > 0) {
                $Sl = "INSERT INTO scr(inv,stkid,amount) VALUES ('{$invnum}','{$stkd['stkid']}',' {$stk['csprice']}')";
                $Rg = db_exec($Sl);
            }
            # update stock(alloc - qty)
            $sql = "UPDATE stock SET csamt = (csamt - '{$cosamt}'),units = (units - '{$stkd['qty']}'),alloc = (alloc - '{$stkd['qty']}')  WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vat code for all your stock.";
            }
            $VATP = TAX_VAT;
            $amtexvat = sprint($stkd['amt']);
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            ####################################################
            if ($stk['serd'] == 'yes') {
                ext_invSer($stkd['serno'], $stkd['stkid'], "POS Cash", $invnum);
            }
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            $sdate = date("Y-m-d");
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, $stkd['qty'], $cosamt, "POS Sales - Invoice No. {$invnum}");
            # get accounts
            db_conn("exten");
            $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $stockacc = $wh['stkacc'];
            $cosacc = $wh['cosacc'];
            # dt(cos) ct(stock)
            writetrans($cosacc, $stockacc, $td, $refnum, $cosamt, "Cost Of Sales POS Cash on POS Invoice No.{$invnum}.");
            $tcosamt += $cosamt;
            db_connect();
            $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\t\tVALUES('{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'stk', '" . USER_DIV . "')";
            $recRslt = db_exec($sql);
        } else {
            db_connect();
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            $av -= $ivat;
            $at -= $iamount;
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            db_connect();
            $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\t\tVALUES('{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'non', '" . USER_DIV . "')";
            $recRslt = db_exec($sql);
            ####################################################
            $amtexvat = sprint($stkd['amt']);
            db_connect();
            $sdate = date("Y-m-d");
            $nsp += sprint($iamount - $ivat);
            // 				//writetrans($cosacc, $stockacc,$inv['odate'] , $refnum, $cosamt, "Cost Of Sales for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
            // 				writetrans($dept['debtacc'], $stkd['account'],$inv['odate'], $refnum, ($iamount-$ivat), "Debtors Control for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
            if ($inv['pcash'] > 0) {
                $min = $ro;
                $inv['pcash'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcash'] >= $ivat) {
                    writetrans($dept['pca'], $vatacc, $td, $refnum, $ivat, "VAT Received for POS Invoice No.{$invnum}.");
                    $inv['pcash'] = sprint($inv['pcash'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcash'] > 0) {
                        if ($inv['pcash'] >= $iamount) {
                            writetrans($dept['pca'], $stkd['account'], $td, $refnum, $iamount, "Sales for POS Invoice No.{$invnum}.");
                            $inv['pcash'] = sprint($inv['pcash'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcash'] < $iamount) {
                            writetrans($dept['pca'], $stkd['account'], $td, $refnum, $inv['pcash'], "Sales for POS Invoice No.{$invnum}.");
                            $iamount = sprint($iamount - $inv['pcash']);
                            $inv['pcash'] = 0;
                        }
                    }
                } else {
                    writetrans($dept['pca'], $vatacc, $td, $refnum, $inv['pcash'], "VAT Received for POS Invoice No.{$invnum}.");
                    $ivat = sprint($ivat - $inv['pcash']);
                    $inv['pcash'] = 0;
                }
                // 					db_conn('cubit');
                //
                // 					$inv['pcash']-=$min;
                //
                // 					$Sl="INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('$sd','".USER_NAME."','$invnum','$inv[pcash]','Cash','".PRD_DB."','0')";
                // 					$Ri=db_exec($Sl) or errDie("Unable to insert data.");
            }
            if ($inv['pcheque'] > 0) {
                $min = $ro;
                $inv['pcheque'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcheque'] >= $ivat) {
                    writetrans($dept['pca'], $vatacc, $td, $refnum, $ivat, "VAT Received for POS Invoice No.{$invnum}.");
                    $inv['pcheque'] = sprint($inv['pcheque'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcheque'] > 0) {
                        if ($inv['pcheque'] >= $iamount) {
                            writetrans($dept['pca'], $stkd['account'], $td, $refnum, $iamount, "Sales for POS Invoice No.{$invnum}.");
                            $inv['pcheque'] = sprint($inv['pcheque'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcheque'] < $iamount) {
                            writetrans($dept['pca'], $stkd['account'], $td, $refnum, $inv['pcheque'], "Sales for POS Invoice No.{$invnum}.");
                            $iamount = sprint($iamount - $inv['pcheque']);
                            $inv['pcheque'] = 0;
                        }
                    }
                } else {
                    writetrans($dept['pca'], $vatacc, $td, $refnum, $inv['pcheque'], "VAT Received for POS Invoice No.{$invnum}.");
                    $ivat = sprint($ivat - $inv['pcheque']);
                    $inv['pcheque'] = 0;
                }
                // 					db_conn('cubit');
                //
                // 					$inv['pcash']-=$min;
                //
                // 					$Sl="INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('$sd','".USER_NAME."','$invnum','$inv[pcash]','Cash','".PRD_DB."','0')";
                // 					$Ri=db_exec($Sl) or errDie("Unable to insert data.");
            }
            if ($inv['pcc'] > 0) {
                db_conn('core');
                $Sl = "SELECT * FROM salacc WHERE name='cc'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return "Please set a link for the POS credit card control account";
                }
                $cd = pg_fetch_array($Ri);
                $cc = $cd['accnum'];
                $min = $ro;
                $inv['pcc'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcc'] >= $ivat) {
                    writetrans($cc, $vatacc, $td, $refnum, $ivat, "VAT Received for POS Invoice No.{$invnum}.");
                    $inv['pcc'] = sprint($inv['pcc'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcc'] > 0) {
                        if ($inv['pcc'] >= $iamount) {
                            writetrans($cc, $stkd['account'], $td, $refnum, $iamount, "Sales for POS Invoice No.{$invnum}.");
                            $inv['pcc'] = sprint($inv['pcc'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcc'] < $iamount) {
                            writetrans($cc, $stkd['account'], $td, $refnum, $inv['pcc'], "Sales for POS Invoice No.{$invnum}.");
                            $iamount = sprint($iamount - $inv['pcc']);
                            $inv['pcc'] = 0;
                        }
                    }
                } else {
                    writetrans($cc, $vatacc, $td, $refnum, $inv['pcc'], "VAT Received for POS Invoice No.{$invnum}.");
                    $ivat = sprint($ivat - $inv['pcc']);
                    $inv['pcc'] = 0;
                }
                // 					db_conn('cubit');
                //
                // 					$inv['pcash']-=$min;
                //
                // 					$Sl="INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('$sd','".USER_NAME."','$invnum','$inv[pcash]','Cash','".PRD_DB."','0')";
                // 					$Ri=db_exec($Sl) or errDie("Unable to insert data.");
            }
            if ($inv['pcredit'] > 0) {
                db_conn('core');
                $min = $ro;
                $inv['pcredit'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcredit'] >= $ivat) {
                    writetrans($dept['debtacc'], $vatacc, $td, $refnum, $ivat, "VAT Received for POS Invoice No.{$invnum}.");
                    $inv['pcredit'] = sprint($inv['pcredit'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcredit'] > 0) {
                        if ($inv['pcredit'] >= $iamount) {
                            writetrans($dept['debtacc'], $stkd['account'], $td, $refnum, $iamount, "Sales for POS Invoice No.{$invnum}.");
                            $inv['pcredit'] = sprint($inv['pcredit'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcredit'] < $iamount) {
                            writetrans($dept['debtacc'], $stkd['account'], $td, $refnum, $inv['pcredit'], "Sales for POS Invoice No.{$invnum}.");
                            $iamount = sprint($iamount - $inv['pcredit']);
                            $inv['pcredit'] = 0;
                        }
                    }
                } else {
                    writetrans($dept['debtacc'], $vatacc, $td, $refnum, $inv['pcredit'], "VAT Received for POS Invoice No.{$invnum}.");
                    $ivat = sprint($ivat - $inv['pcredit']);
                    $inv['pcredit'] = 0;
                }
                // 					db_conn('cubit');
                //
                // 					$inv['pcash']-=$min;
                //
                // 					$Sl="INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('$sd','".USER_NAME."','$invnum','$inv[pcash]','Cash','".PRD_DB."','0')";
                // 					$Ri=db_exec($Sl) or errDie("Unable to insert data.");
            }
        }
    }
    /* - Start Transactoins - */
    ###################VAT CALCS#######################
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    $excluding = "";
    $vr = vatcalc($inv['delchrg'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
    ####################################################
    //print $inv['pcash'];exit;
    if ($inv['pcash'] > 0) {
        $min = $ro;
        $inv['pcash'] += $ro;
        $ro = 0;
        $amount = $inv['pcash'];
        if ($amount >= $av) {
            writetrans($dept['pca'], $vatacc, $td, $refnum, $av, "VAT Received for POS Invoice No.{$invnum}.");
            // PROBLEM HERE?
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['pca'], $dept['pia'], $td, $refnum, $amount, "Sales for POS Invoice No.{$invnum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($dept['pca'], $vatacc, $td, $refnum, $amount, "VAT Received for POS Invoice No.{$invnum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcash'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fcash}','Cash','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
        $fcash = 0;
    }
    db_conn('cubit');
    if ($fcash > 0) {
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fcash}','Cash','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['pcheque'] > 0) {
        $min = $ro;
        $inv['pcheque'] += $ro;
        $ro = 0;
        $amount = $inv['pcheque'];
        if ($amount >= $av) {
            writetrans($dept['pca'], $vatacc, $td, $refnum, $av, "VAT Received for POS Invoice No.{$invnum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['pca'], $dept['pia'], $td, $refnum, $amount, "Sales for POS Invoice No.{$invnum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($dept['pca'], $vatacc, $td, $refnum, $amount, "VAT Received for POS Invoice No.{$invnum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcheque'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fcheque}','Cheque','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
        $fcheque = 0;
    }
    db_conn('cubit');
    if ($fcheque > 0) {
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fcheque}','Cheque','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['pcc'] > 0) {
        db_conn('core');
        $Sl = "SELECT * FROM salacc WHERE name='cc'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set a link for the POS credit card control account";
        }
        $cd = pg_fetch_array($Ri);
        $cc = $cd['accnum'];
        $min = $ro;
        $inv['pcc'] += $ro;
        $ro = 0;
        $amount = $inv['pcc'];
        if ($amount >= $av) {
            writetrans($cc, $vatacc, $td, $refnum, $av, "VAT Received for POS Invoice No.{$invnum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($cc, $dept['pia'], $td, $refnum, $amount, "Sales for POS Invoice No.{$invnum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($cc, $vatacc, $td, $refnum, $amount, "VAT Received for POS Invoice No.{$invnum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcc'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fccp}','Credit Card','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
        $fccp = 0;
    }
    db_conn('cubit');
    if ($fccp > 0) {
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fccp}','Credit Card','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['pcredit'] > 0) {
        db_conn('core');
        $min = $ro;
        $inv['pcredit'] += $ro;
        $ro = 0;
        $amount = $inv['pcredit'];
        if ($amount >= $av) {
            writetrans($dept['debtacc'], $vatacc, $td, $refnum, $av, "VAT Received for POS Invoice No.{$invnum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['debtacc'], $dept['pia'], $td, $refnum, $amount, "Sales for POS Invoice No.{$invnum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($dept['debtacc'], $vatacc, $td, $refnum, $amount, "VAT Received for POS Invoice No.{$invnum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcc'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fcredit}','Credit','" . PRD_DB . "','0')";
        //$Ri=db_exec($Sl) or errDie("Unable to insert data.");
        $fcredit = 0;
    }
    db_conn('cubit');
    if ($fcredit > 0) {
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fcredit}','Credit','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['rounding'] > 0) {
        if ($inv['pcash'] > 0) {
            writetrans($rac, $dept['pca'], $td, $refnum, $inv['rounding'], "Rounding  on Invoice No.{$invnum}.");
        } elseif ($inv['pcheque'] > 0) {
            writetrans($rac, $dept['pca'], $td, $refnum, $inv['rounding'], "Rounding on Invoice No.{$invnum}.");
        } elseif ($inv['pcc'] > 0) {
            writetrans($rac, $cc, $td, $refnum, $inv['rounding'], "Rounding on Invoice No.{$invnum}.");
        } elseif ($inv['pcredit'] > 0) {
            writetrans($rac, $dept['debtacc'], $td, $refnum, $inv['rounding'], "Rounding on Invoice No.{$invnum}.");
        }
    }
    // 	if($inv['terms']==1) {
    // 		$dept['pca']=$cc;
    // 	}
    //
    // 	# dt(debtors) ct(income/sales)
    // 	writetrans($dept['pca'], $dept['pia'], $td, $refnum, ($TOTAL-$VAT), "Sales for POS Invoice No.$invnum.");
    //
    // 	# dt(debtors) ct(vat account)
    // 	writetrans($dept['pca'], $vatacc, $td, $refnum, $VAT, "VAT Received for POS Invoice No.$invnum.");
    //	db_connect();
    //	$sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)
    //	VALUES('$inv[odate]', '$invid', '$invnum', '$dept[debtacc]', '$VAT', '$TOTAL', 'stk', '".USER_DIV."')";
    //	$recRslt = db_exec($sql);
    db_conn('cubit');
    if ($inv['cusnum'] > 0) {
        db_conn('cubit');
        $Sl = "SELECT * FROM customers WHERE cusnum='{$inv['cusnum']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $cd = pg_fetch_array($Ri);
        $inv['cusname'] = $cd['surname'];
    }
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t('{$inv['cusnum']}','{$inv['cusname']}','POS Invoice {$invnum}','{$inv['odate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    if ($change > 0) {
        $Sl = "INSERT INTO pc(date,by,inv,amount) VALUES ('{$sd}','" . USER_NAME . "','{$invnum}','{$change}')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    db_conn('cubit');
    if ($inv['rounding'] > 0) {
        $Sl = "INSERT INTO varrec(inv,date,amount) VALUES('{$invnum}','" . date("Y-m-d") . "','{$inv['rounding']}')";
        $Ri = db_exec($Sl);
    }
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (strlen($inv['comm']) > 0) {
        $Com = "<table><tr><td>" . nl2br($inv['comm']) . "</td></tr></table>";
    } else {
        $Com = "";
    }
    $cc = "<script> sCostCenter('dt', 'Sales', '{$inv['odate']}', 'POS Invoice No.{$invnum}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', ''); </script>";
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    /* - End Transactoins - */
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t<center>\n\t\t\t\t\t{$cc}\n\t\t\t\t\t<h2>Tax Invoice</h2>\n\t\t\t\t\t<table cellpadding='0' cellspacing='1' border=0 width=750>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td valign='top' width='40%'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr><td>{$inv['surname']}</td></tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='top' width='35%'>\n\t\t\t\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\t\t\t\tReg No. " . COMP_REGNO . "<br>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='bottom' align='right' width='25%'>\n\t\t\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$invnum}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Order No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['ordno']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Terms</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>Cash</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Invoice Date</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['odate']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>VAT</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['chrgvat']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='3'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width=100% bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t\t\t\t\t\t\t<th width='45%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t\t\t\t<th>QTY</th>\n\t\t\t\t\t\t\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t\t\t\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t{$products}\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</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<td>{$Com}</td>\n\t\t\t\t\t\t\t<td align='right' colspan='2'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='50%' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$SUBTOT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Trade Discount</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$inv['discount']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Delivery Charge</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$inv['delivery']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>VAT @ {$VATP}%</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$VAT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th><b>GRAND TOTAL<b></th>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " border='1'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td colspan='2'>VAT Exempt indicator = #</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th>VAT No.</th>\n\t\t\t\t\t\t\t\t\t\t<td align='center'>" . COMP_VATNO . "</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t        </table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td><br></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</center>";
    /* Start moving invoices */
    db_connect();
    # Move invoices that are fully paid
    $sql = "SELECT * FROM pinvoices WHERE printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    while ($invb = pg_fetch_array($invbRslt)) {
        db_conn($invb['prd']);
        $invb['invnum'] += 0;
        # Insert invoice to period DB
        $sql = "INSERT INTO pinvoices(invid,invnum, deptid, cusnum, deptname, cusacc, cusname, telno,\n\t\t\t\t\tsurname, cusaddr, cusvatno, cordno, ordno, chrgvat, terms, traddisc, salespn,\n\t\t\t\t\todate, delchrg, subtot, vat, total, balance, comm, printed, done, div, username,\n\t\t\t\t\trounding,delvat,vatnum,pcash,pcheque,pcc,pcredit, pslip_sordid)\n\t\t\t\tVALUES('{$invb['invid']}','{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}',\n\t\t\t\t\t'{$invb['deptname']}', '{$invb['cusacc']}', '{$invb['cusname']}', '{$invb['telno']}', '{$invb['surname']}',\n\t\t\t\t\t'{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}',\n\t\t\t\t\t'{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}',\n\t\t\t\t\t'{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' ,\n\t\t\t\t\t'{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', 'y', 'y', '" . USER_DIV . "',\n\t\t\t\t\t'" . USER_NAME . "','{$invb['rounding']}','{$invb['delvat']}','{$invb['vatnum']}',\n\t\t\t\t\t'{$invb['pcash']}','{$invb['pcheque']}','{$invb['pcc']}','{$invb['pcredit']}', '{$invb['pslip_sordid']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.", SELF);
        db_connect();
        $sql = "INSERT INTO movinv(invtype, invnum, prd, docref, div) VALUES('pos', '{$invb['invnum']}', '{$invb['prd']}', '', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.", SELF);
        # get selected stock in this invoice
        db_connect();
        $sql = "SELECT * FROM pinv_items WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        while ($stkd = pg_fetch_array($stkdRslt)) {
            db_conn($invb['prd']);
            # insert invoice items
            $stkd['vatcode'] += 0;
            $stkd['account'] += 0;
            $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, serno, div,vatcode,account,description) VALUES('{$invb['invid']}', '{$stkd['whid']}', '{$stkd['stkid']}', '{$stkd['qty']}', '{$stkd['unitcost']}', '{$stkd['amt']}', '{$stkd['disc']}', '{$stkd['discp']}', '{$stkd['serno']}', '" . USER_DIV . "','{$stkd['vatcode']}','{$stkd['account']}','{$stkd['description']}')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
        }
        db_connect();
        # Remove those invoices from running DB
        $sql = "DELETE FROM pinvoices WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        # Remove those invoice items from running DB
        $sql = "DELETE FROM pinv_items WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    }
    /* end moving invoices */
    /* OLD
    	$OUTPUT = $details;
    	require("tmpl-print.php");*/
    header("Location: pos-slip.php?invid={$inv['invid']}&prd={$inv['prd']}&cccc=yes");
    exit;
}
function write()
{
    # Get vars
    extract($_REQUEST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order 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.");
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($recvd)) {
        foreach ($recvd as $sk => $keys) {
            $v->isOk($qtys[$keys], "float", 1, 15, "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 ($qtys[$keys] <= 0) {
                $v->isOk("#", "num", 0, 0, "Error : Item Quantity must be more than zero. Product number : <b>" . ($keys + 1) . "</b>");
            }
            if ($qtys[$keys] > $qts[$keys]) {
                $v->isOk("#", "num", 0, 0, "Error : Item Quantity returned is more than the bought quantity : <b>" . ($keys + 1) . "</b>");
            }
            $v->isOk($stkids[$keys], "num", 1, 10, "Invalid Stock number, please enter all details.");
            # Validate ddate[]
            $v->isOk($d_day[$keys], "num", 1, 2, "Invalid Delivery Date day.");
            $v->isOk($d_month[$keys], "num", 1, 2, "Invalid Delivery Date month.");
            $v->isOk($d_year[$keys], "num", 1, 5, "Invalid Delivery Date year.");
            $ddate[$keys] = $d_year[$keys] . "-" . $d_month[$keys] . "-" . $d_day[$keys];
            if (!checkdate($d_month[$keys], $d_day[$keys], $d_year[$keys])) {
                $v->isOk($ddate[$keys], "num", 1, 1, "Invalid Delivery Date.");
            }
        }
        if (isset($sers)) {
            foreach ($sers as $stkid => $sernos) {
                if (!ext_isUnique(ext_remBlnk($sernos))) {
                    $v->isOk("error", "num", 1, 1, "Error : Serial numbers must be unique per Stock Item.");
                } else {
                    foreach ($recvd as $sk => $keys) {
                        if (isset($sernos[$keys]) && $v->isOk($sernos[$keys], "string", 1, 20, "Error : Invalid Serial number.")) {
                            if (ext_findSer($sernos[$keys]) != false) {
                                $v->isOk("#", "string", 1, 20, "Error : Serial number already exists.");
                            }
                        }
                    }
                }
            }
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : Items Not Selected.");
    }
    # 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 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> - Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $td = $pur['pdate'];
    # check if purchase has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : Order number <b>{$purid}</b> has already been received.</li>";
        $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);
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    $VATP = $vd['vat_amount'];
    if ($vd['zero'] != "Yes") {
        # If vat is not included (shipchrg)
        if ($pur['vatinc'] == "no") {
            $scvat = sprint($VATP / 100 * $shipchrg);
            $shipexvat = $shipchrg;
        } elseif ($pur['vatinc'] == "yes") {
            $scvat = sprint($shipchrg / ($VATP + 100) * $VATP);
            $shipexvat = $shipchrg - $scvat;
        } else {
            $scvat = 0;
            $shipexvat = $shipchrg;
        }
    } else {
        $scvat = 0;
        $shipexvat = $shipchrg;
    }
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # Begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_conn(PRD_DB);
    # get last ref number
    $refnum = getrefnum();
    db_connect();
    # amount of stock in
    $totstkamt = array();
    $resub = 0;
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    $flag = TRUE;
    $checkid = 0;
    $nonstot = 0;
    foreach ($recvd as $sk => $keys) {
        if ($checkid == $ids[$keys]) {
            $flag = FALSE;
        } else {
            $flag = TRUE;
        }
        $checkid = $ids[$keys];
        # Skip zeros
        if ($qtys[$keys] <= 0) {
            continue;
        }
        db_connect();
        # 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);
        if ($stk['units'] < 0) {
            $min_stock = abs($stk['units']);
            if ($qtys[$keys] < $min_stock) {
                $min_stock = $qtys[$keys];
            }
        } else {
            $min_stock = 0;
        }
        # Get selected stock line
        $sql = "SELECT * FROM pur_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        if ($pur['vatinc'] == "yes") {
            $unitcost[$keys] = sprint(($stkd['amt'] - $stkd['svat']) / $stkd['qty']);
        } else {
            $unitcost[$keys] = sprint($stkd['amt'] / $stkd['qty']);
        }
        //$perc[$keys] = sprint((($unitcost[$keys]*$qtys[$keys])/$pur['subtot']) * 100);
        $perc[$keys] = sprint($unitcost[$keys] / $pur['subtot'] * 100);
        $ffs = $perc[$keys] * $qtys[$keys];
        # Get percentage from shipping charges excluding vat
        $shipc[$keys] = sprint($perc[$keys] / 100 * $shipexvat);
        //print "cost: percent:$ffs ship: part1".($unitcost[$keys]*$qtys[$keys])."part2".($shipc[$keys]*$qtys[$keys])."<br>";
        # add delivery charges = amt + del chrg excluding vat
        $unitcost[$keys] += $shipc[$keys];
        if ($stkd['udiscount'] > 0) {
            $discps = round($stkd['udiscount'] / 100 * $unitcost[$keys], 2);
        } else {
            $discps = 0;
        }
        $amt[$keys] = sprint($qtys[$keys] * $unitcost[$keys]);
        #serialized items are broken into multiples .... we only want to process the first ... so FLAG is used
        if (isset($invoice)) {
            $iq = $qtys[$keys];
            $iq += 0;
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            if ($pur['vatinc'] == "yes") {
                $iamount = $stkd['amt'];
            } else {
                $iamount = sprint($stkd['amt'] + $stkd['svat']);
            }
            if ($flag) {
                vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "VAT for Purchase No. {$pur['purnum']}", -$iamount, -$stkd['svat']);
            }
            $Sl = "UPDATE pur_items SET iqty=iqty-'{$iq}' WHERE id='{$stkd['id']}'";
            $Ri = db_exec($Sl) or errDie("Unable to update invoice qty.");
        }
        $resub += $amt[$keys];
        # Update purchase items
        $sql = "\n\t\t\tUPDATE pur_items \n\t\t\tSET rqty = (rqty + '{$qtys[$keys]}'), ddate = '{$ddate[$keys]}' \n\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);
        $cc = "";
        if ($stkd['account'] > 0) {
            if ($pur['vatinc'] == "yes") {
                #calculate the vat of this amount as we dont store it !!
                $vatcod = $stkd['vatcode'] + 0;
                $get_v = "SELECT vat_amount FROM vatcodes WHERE id = '{$vatcod}' LIMIT 1";
                $run_v = db_exec($get_v) or errDie("Unable to get vatcode information.");
                $varr = pg_fetch_array($run_v);
                $clearvat = $varr['vat_amount'] + 0;
                $remvat = sprint($stkd['amt'] / ($clearvat + 100) * $clearvat);
                $nonstot = $nonstot + $stkd['amt'] - $remvat;
            } else {
                $nonstot = $nonstot + $stkd['amt'];
            }
            $stk['whid'] = $stkd['account'];
            $sql = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '" . USER_DIV . "' LIMIT 1";
            $banks = db_exec($sql);
            if (pg_numrows($banks) < 1) {
                return "<li class='err'> There are no accounts held at the selected Bank.\n\t\t\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
            }
            $barr = pg_fetch_array($banks);
            $bankid = $barr['bankid'];
            core_connect();
            $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
            # Check if link exists
            if (pg_numrows($rslt) < 1) {
                return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.";
            }
            $banklnk = pg_fetch_array($rslt);
            $cc_trantype = cc_TranTypeAcc($stkd['account'], $banklnk['accnum']);
        } else {
            # Update stock(ordered + qty, units + qty, csamt + (csamt + amt))
            $sql = "\n\t\t\t\tUPDATE stock \n\t\t\t\tSET ordered = (ordered - '{$qtys[$keys]}'), units = (units + '{$qtys[$keys]}' +'{$min_stock}'), csamt = (csamt + '{$amt[$keys]}') \n\t\t\t\tWHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            if (isset($sers[$stkids[$keys]][$keys])) {
                ext_InSer($sers[$stkids[$keys]][$keys], $stkids[$keys], $pur['supname'], $pur['purnum'], "pur", $td);
                $serial = $sers[$stkids[$keys]][$keys];
                db_connect();
                $sql = "\n\t\t\t\t\tINSERT INTO pserec (\n\t\t\t\t\t\tpurid, purnum, stkid, serno, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$pur['purnum']}', '{$stkids[$keys]}', '{$serial}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to update stock serials in Cubit.", SELF);
            }
            # Get selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            //$sdate = date("Y-m-d");
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $td, $qtys[$keys], $amt[$keys], "Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}");
            db_connect();
            $cspric = sprint($amt[$keys] / $qtys[$keys]);
            $sql = "\n\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, \n\t\t\t\t\tcsamt, details, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$td}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'purchase', '{$qtys[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t'{$cspric}', 'Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t\t)";
            $recRslt = db_exec($sql);
            # Just wanted to fix the xxx.xxxxxxe-x value
            if ($stk['units'] > 0) {
                $csprice = round($stk['csamt'] / $stk['units'], 2);
            } else {
                $csprice = round($stk['csprice'], 2);
            }
            # update stock(csprice = (csamt/units))
            $sql = "\n\t\t\t\tUPDATE stock \n\t\t\t\tSET csprice = '{$csprice}', lcsprice = '{$cspric}' \n\t\t\t\tWHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        }
        # Keep records for transactions
        if (isset($totstkamt[$stk['whid']])) {
            $totstkamt[$stk['whid']] += $amt[$keys];
        } else {
            $totstkamt[$stk['whid']] = $amt[$keys];
        }
        db_connect();
        # check if there are any outstanding items
        $sql = "SELECT * FROM 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 purchases SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update Orders in Cubit.", SELF);
        }
        if ($min_stock > 0) {
            $cost = sprint($unitcost[$keys] * $min_stock);
            db_conn("exten");
            $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $stockacc = $wh['stkacc'];
            $cosacc = $wh['cosacc'];
            db_connect();
            $Sl = "UPDATE stock SET csamt = (csamt - '{$cost}'),units=(units-'{$min_stock}') WHERE stkid='{$stkids[$keys]}'";
            $Ri = db_exec($Sl);
            writetrans($cosacc, $stockacc, $td, $refnum, $cost, "Cost Of Sales for stock sold before purchase {$pur['purnum']}");
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, 0, $cost, "Cost Of Sales for stock sold before purchase {$pur['purnum']}");
            db_connect();
            $Sl = "\n\t\t\t\tINSERT INTO pcost (\n\t\t\t\t\tpurnum, cost, qty, rqty, stkid\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$pur['purnum']}', '{$unitcost[$keys]}', '{$min_stock}', '0', '{$stk['stkid']}'\n\t\t\t\t)";
            $Ri = db_exec($Sl);
        }
    }
    //	$darr = explode ("-",$date);
    //	$cdate = "$darr[2]-$darr[1]-$darr[0]";
    #if non stock total is set, process the cost center
    if ($nonstot != "0") {
        $nonstot = sprint($nonstot);
        if ($cc_trantype != false) {
            $date = date("Y-m-d");
            $cc .= "\n\t\t\t\t<script>\n\t\t\t\t\tCostCenter('{$cc_trantype}', 'Non Stock Purchase', '{$date}', '{$stkd['description']}', {$nonstot}, '');\n\t\t\t\t</script>";
        } else {
            $cc .= "";
        }
    }
    if (isset($invoice)) {
        ###################VAT CALCS#######################
        $pur['delvat'] += 0;
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['delvat']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            $Sl = "SELECT * FROM vatcodes";
            $Ri = db_exec($Sl);
        }
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        $vr = vatcalc($shipchrg, $pur['vatinc'], $excluding, 0, $vd['vat_amount']);
        $vrs = explode("|", $vr);
        $ivat_tmp = $vrs[0];
        $iamount_tmp = $vrs[1];
        vatr($vd['id'], $td, "INPUT", $vd['code'], $refnum, "VAT Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.", sprint(-$iamount_tmp), -$scvat);
        ####################################################
        db_conn("exten");
        $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$itotal}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "\n\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\tsupid, edate, cacc, amount, descript, ref, ex, div\n\t\t\t) VALUES (\n\t\t\t\t'{$pur['supid']}', '{$pur['pdate']}', '{$wh['conacc']}', '{$itotal}', \n\t\t\t\t'Stock Received - Purchase {$pur['purnum']} Inv:{$pur['supinv']}', '{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t)";
        $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, $isubtot, "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
        # Transfer vat
        writetrans($vatacc, $dept['credacc'], $td, $refnum, $ivat, "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.", $itotal, '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 + '{$itotal}') 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 = "\n\t\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$itotal}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
        }
        /* Make transaction record  for age analysis */
        # commit updating
        $sql = "UPDATE purchases SET iamount = iamount+'{$itotal}',ivat=ivat+'{$ivat}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
        $sql = "SELECT SUM(iqty) FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktRslt = db_exec($sql);
        $data = pg_fetch_array($stktRslt);
        $left = $data['sum'];
        if ($left == 0) {
            /* Start moving if purchase */
            if ($pur['received'] == "y") {
                if (strlen($pur['appdate']) < 8) {
                    $pur['appdate'] = date("Y-m-d");
                }
                # copy purchase
                db_conn($pur['prd']);
                $sql = "\n\t\t\t\t\tINSERT INTO purchases (\n\t\t\t\t\t\tpurid, deptid, supid, supname, supaddr, supno, \n\t\t\t\t\t\tterms, pdate, ddate, shipchrg, subtot, total, \n\t\t\t\t\t\tbalance, vatinc, vat, shipping, remarks, refno, received, done, \n\t\t\t\t\t\tdiv, purnum, supinv, ordernum, appname, appdate\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', \n\t\t\t\t\t\t'{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', \n\t\t\t\t\t\t'0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$remarks}', '{$pur['refno']}', 'y', 'y', \n\t\t\t\t\t\t'" . USER_DIV . "', '{$pur['purnum']}', '{$supinv}', '{$pur['ordernum']}', '{$pur['appname']}', '{$pur['appdate']}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
                /*-- Cost varience -- */
                //$nsubtot = sprint($pur['total'] - $pur['vat']);
                $nsubtot = sprint($p['iamount'] - $p['ivat']);
                if ($p['rsubtot'] > $nsubtot) {
                    $diff = sprint($p['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 > $p['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($pur['prd']);
                    $sql = "\n\t\t\t\t\t\tINSERT INTO pur_items (\n\t\t\t\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, \n\t\t\t\t\t\t\tamt, svat, ddate, div\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', \n\t\t\t\t\t\t\t'{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "'\n\t\t\t\t\t\t)";
                    $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
                }
                # begin updating
                //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
                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
                //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
            } else {
                # insert Order to DB
                $sql = "UPDATE purchases SET invcd = 'y',supinv='{$pur['supinv']}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
            }
        }
    }
    if (strlen($refno) > 0) {
        if (strlen($pur['refno']) > 0) {
            $refno = "{$pur['refno']}-{$refno}";
        } else {
            $refno = $refno;
        }
    } else {
        $refno = $pur['refno'];
    }
    db_connect();
    # Update purchase on the DB
    if ($pur['part'] == 'y') {
        $sql = "\n\t\t\tUPDATE purchases \n\t\t\tSET rsubtot = (rsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', edit = 1 \n\t\t\tWHERE purid = '{$purid}'";
    } else {
        $sql = "\n\t\t\tUPDATE purchases \n\t\t\tSET part = 'y', rsubtot = (rsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', edit = 1 \n\t\t\tWHERE purid = '{$purid}'";
    }
    $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    /* Transactions */
    db_conn(PRD_DB);
    # get last ref number
    //$refnum = getrefnum();
    /* - Start Hooks - */
    /* - End Hooks - */
    # Record transaction  from data
    foreach ($totstkamt as $whid => $wamt) {
        # get whouse info
        db_conn("exten");
        $sql = "SELECT stkacc,conacc FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        if (pg_num_rows($whRslt) < 1) {
            $sql = "SELECT stkacc,conacc FROM warehouses";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $wh['stkacc'] = $whid;
        } else {
            $wh = pg_fetch_array($whRslt);
        }
        # Debit Stock and Credit Stock control
        writetrans($wh['stkacc'], $wh['conacc'], $td, $refnum, $wamt, "Stock Received for Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    }
    # commit updating
    /*** pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    
    	/* Start moving if Order received and invoiced */
    # 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 Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li> - Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y" && $pur['invcd'] == 'y') {
        if (strlen($pur['appdate']) < 8) {
            $pur['appdate'] = date("Y-m-d");
        }
        # copy purchase
        db_conn(PRD_DB);
        $sql = "\n\t\t\t\tINSERT INTO purchases (\n\t\t\t\t\tpurid, deptid, supid, supname, supaddr, supno, \n\t\t\t\t\tterms, pdate, ddate, shipchrg, subtot, total, balance, \n\t\t\t\t\tvatinc, vat, shipping, remarks, refno, received, done, div, \n\t\t\t\t\tpurnum, supinv, ordernum, appname, appdate, delvat\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', \n\t\t\t\t\t'{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', \n\t\t\t\t\t'{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', \n\t\t\t\t\t'{$pur['purnum']}', '{$pur['supinv']}', '{$pur['ordernum']}', '{$pur['appname']}', '{$pur['appdate']}', '{$pur['delvat']}'\n\t\t\t\t)";
        $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 = "\n\t\t\t\t\tINSERT INTO pur_items (\n\t\t\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, \n\t\t\t\t\t\tamt, svat, ddate, div, vatcode, \n\t\t\t\t\t\taccount, description, udiscount\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', \n\t\t\t\t\t\t'{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "','{$stktc['vatcode']}', \n\t\t\t\t\t\t'{$stktc['account']}', '{$stktc['description']}', '{$stktc['udiscount']}'\n\t\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        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 Orders 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 Orders 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 Orders information in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving purchase received */
    if (isset($gds_note) and strlen($gds_note) > 0) {
        $cc .= "\n\t\t\t<script>\n\t\t\t\tprinter(\"" . SELF . "?key=recv_print&purid={$purid}\");\n\t\t\t</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>Order received</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Order receipt from Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='purchase-new.php'>New Purchase</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='purchase-view.php'>View 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 details($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>{$e['msg']}</li>";
        }
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $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 "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $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 <b>{$invid}</b> has no items.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # 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>";
        return $error;
    }
    # check if invoice has been serialised
    if ($inv['serd'] == "n") {
        $error = "<li class='err'> Error : You must select serial numbers for some Items on Invoice No. <b>T {$invid}</b> before you can print it.</li>";
        return $error;
    }
    #check if this transaction date is allowed
    // 	$curyr = getActiveFinYear();
    // 	if ($yr > $curyr || ($yr == $curyr && $mon > $PRDMON[12])) {
    // 		$v->addError("", "Cannot do transaction in future financial year. ".(DEBUG>0?"\"$details\"":""));
    // 	}
    db_conn('cubit');
    $showvat = TRUE;
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($inv['odate']) >= strtotime($blocked_date_from) and strtotime($inv['odate']) <= 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>";
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $invnum = divlastid('inv', USER_DIV);
    $Sl = "INSERT INTO ncsrec (oldnum, newnum, div) VALUES ('{$invid}', '{$invnum}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert into db");
    # 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);
    }
    /* --- Start Products Display --- */
    # Products layout
    $commision = 0;
    $products = array();
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM inv_items WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $taxex = 0;
    $i = 0;
    $page = 0;
    $salesp = qrySalesPersonN($inv["salespn"]);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                $showvat = FALSE;
            }
            $sp = "";
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "";
            }
            # all must be excempted
            if ($inv['chrgvat'] == 'nov') {
                $ex = "#";
            }
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            # Insert stock record
            $sdate = date("Y-m-d");
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            # Sales rep commission
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = $stk["com"];
            }
            #if this item is not exvat (ie. $ex != #) then reduce by the vat amount
            if ((strlen($ex) != "#" or $vd['vat_amount'] > 0) and $inv['chrgvat'] == "inc") {
                $vat = sprint($stkd['amt'] * $vd['vat_amount'] / (100 + $vd['vat_amount']));
                $exvatamt = sprint($stkd['amt'] - $vat);
            } else {
                $exvatamt = sprint($stkd['amt']);
            }
            $commision = $commision + coms($inv['salespn'], sprint($exvatamt), $itemcommission);
            if (strlen($stkd['serno']) > 0) {
                $showser = "<br>" . trim($stkd['serno']);
            } else {
                $showser = "";
            }
            # Put in product
            $products[$page][] = "\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$stk['stkcod']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$sp} {$stk['stkdes']}&nbsp; {$showser}</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$stkd['qty']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['unitcost']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['disc']}&nbsp;</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$stkd['amt']}&nbsp;</td>\n\t\t\t\t</tr>";
            $i++;
        } else {
            db_conn('core');
            $Sl = "SELECT * FROM accounts WHERE accid='{$stkd['account']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get account data.");
            $ad = pg_fetch_array($Ri);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                $showvat = FALSE;
            }
            $sp = "";
            # Check Tax Excempt
            if ($vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "";
            }
            # all must be excempted
            if ($inv['chrgvat'] == 'nov') {
                $ex = "#";
            }
            #if this item is not exvat (ie. $ex != #) then reduce by the vat amount
            if ((strlen($ex) != "#" or $vd['vat_amount'] > 0) and $inv['chrgvat'] == "inc") {
                $vat = sprint($stkd['amt'] * $vd['vat_amount'] / (100 + $vd['vat_amount']));
                $exvatamt = sprint($stkd['amt'] - $vat);
            } else {
                $exvatamt = sprint($stkd['amt']);
            }
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = 0;
            }
            $commision = $commision + coms($inv['salespn'], sprint($exvatamt), $itemcommission);
            # Put in product
            $products[$page][] = "\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$sp} {$stkd['description']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$stkd['qty']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['unitcost']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['disc']}&nbsp;</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$stkd['amt']}&nbsp;</td>\n\t\t\t\t</tr>";
            $i++;
        }
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\n\t \t\t\t<tr>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td>&nbsp;</td>\n\t \t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    if (strlen($inv['traddisc']) > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * $SUBTOT);
    } else {
        $traddiscm = "0.00";
    }
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOTAL = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    com_invoice($inv['salespn'], $TOTAL - $VAT, sprint($commision), $invnum, $inv["odate"], true);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    /* - End Hooks - */
    # Todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*refnum*/
    if ($inv['branch'] != 0) {
        db_conn("cubit");
        $get_addr = "SELECT * FROM customer_branches WHERE id = '{$inv['branch']}' LIMIT 1";
        $run_addr = db_exec($get_addr);
        if (pg_numrows($run_addr) < 1) {
            $address = "";
        } else {
            $barr = pg_fetch_array($run_addr);
            $address = " - {$barr['branch_name']}";
        }
    } else {
        $address = "";
    }
    /* --- Updates ---- */
    db_connect();
    $Sql = "UPDATE invoices SET printed = 'y', done = 'y', invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
    //dont make consignment order from invoice if customer number is entered ...
    //		if (isset($inv['cordno']) AND strlen($inv['cordno']) > 0){
    //			$inv_type = "Consignment Order";
    //		}else {
    $inv_type = "Invoice";
    //		}
    # Record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt (\n\t\t\t\tcusnum, invid, docref, amount, date, \n\t\t\t\ttype, branch, div, allocation_date, \n\t\t\t\tallocation_balance\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}', '{$inv['odate']}', \n\t\t\t\t'{$inv_type}', '{$address}', '" . USER_DIV . "', '{$inv['odate']}', \n\t\t\t\t'" . abs($inv['total']) . "'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO open_stmnt (\n\t\t\t\tcusnum, invid, docref, amount, balance, \n\t\t\t\tdate, type, div\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}','{$inv['total']}', \n\t\t\t\t'{$inv['odate']}', '{$inv_type}', '" . USER_DIV . "'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Save invoice discount
    $sql = "\n\t\t\tINSERT INTO inv_discs (\n\t\t\t\tcusnum, invid, traddisc, itemdisc, inv_date, delchrg, \n\t\t\t\tdiv, total\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$traddiscm}', '{$disc}', '{$inv['odate']}', '{$inv['delchrg']}', \n\t\t\t\t'" . USER_DIV . "', ({$SUBTOT}+{$inv['delchrg']})\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$inv['total']}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Make ledge record
    custledger($inv['cusnum'], $dept['incacc'], $inv['odate'], $invnum, "Invoice No. {$invnum}", $inv['total'], "d");
    db_connect();
    # get selected stock in this invoice
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    $sdate = date("Y-m-d");
    $nsp = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            db_connect();
            # get selamt from selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            if ($stk['units'] - $stkd['qty'] < 0) {
                if ($stk['units'] <= 0) {
                    $cosamt = 0;
                    $cosamt2 = 0;
                } else {
                    $cosamt = round($stk['units'] * $stk['csprice'], 2);
                    $cosamt2 = round($stk['units'] * $stk['csprice'], 4);
                }
            } else {
                $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
                $cosamt2 = round($stkd['qty'] * $stk['csprice'], 4);
            }
            # update stock(alloc - qty)
            $sql = "\n\t\t\t\t\tUPDATE stock \n\t\t\t\t\tSET csamt = (csamt - '{$cosamt}'),units = (units - '{$stkd['qty']}'), alloc=(alloc - '{$stkd['qty']}') \n\t\t\t\t\tWHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            if ($inv["pslip_sordid"] > 0) {
                $sql = "UPDATE stock SET alloc = (alloc - '{$stkd['qty']}') WHERE stkid='{$stkd['stkid']}'";
                //					db_exec($sql) or errDie("Unable to update allocation.");
            }
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            ####################################################
            $amtexvat = sprint($stkd['amt']);
            //	$uc=sprint($cosamt2/$stkd['qty']);
            $uc = round($cosamt2 / $stkd['qty'], 4);
            // '$cosamt',
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            db_connect();
            $sql = "\n\t\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, \n\t\t\t\t\t\tcsprice, csamt, details, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$inv['odate']}', '{$stkd['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'invoice', '{$stkd['qty']}', \n\t\t\t\t\t\t'{$amtexvat}', '{$csprice}', 'Stock sold - Invoice No. {$invnum}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
            if ($stk['csprice'] > 0) {
                $Sl = "INSERT INTO scr (inv, stkid, amount, invid) VALUES ('{$invnum}', '{$stkd['stkid']}', '{$uc}', '{$stkd['id']}')";
                $Rg = db_exec($Sl);
            }
            if ($stk['serd'] == 'yes') {
                ext_invSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $invnum, $inv['odate']);
            }
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            $sdate = date("Y-m-d");
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $inv['odate'], $stkd['qty'], $cosamt, "Sold to Customer : {$inv['surname']} - Invoice No. {$invnum}");
            # get accounts
            db_conn("exten");
            $sql = "SELECT stkacc, cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $stockacc = $wh['stkacc'];
            $cosacc = $wh['cosacc'];
            if ($cosamt < 0) {
                $cosamt = 0;
            }
            # dt(cos) ct(stock)
            writetrans($cosacc, $stockacc, $inv['odate'], $refnum, $cosamt, "Cost Of Sales for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
            $tcosamt += $cosamt;
            #record the entry for the stock report
            db_connect();
            $sql = "\n\t\t\t\t\tINSERT INTO salesrec (\n\t\t\t\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'stk', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
        } else {
            db_connect();
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            ####################################################
            $amtexvat = sprint($stkd['amt']);
            db_connect();
            $sdate = date("Y-m-d");
            $nsp += sprint($iamount - $ivat);
            writetrans($dept['debtacc'], $stkd['account'], $inv['odate'], $refnum, $iamount - $ivat, "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
            db_connect();
            $sql = "\n\t\t\t\t\tINSERT INTO salesrec (\n\t\t\t\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'non', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
        }
    }
    ###################VAT CALCS#######################
    $inv['delvat'] += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    $vr = vatcalc($inv['delchrg'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", sprint($iamount + $ivat), $ivat);
    ####################################################
    /* - Start Transactoins - */
    # dt(debtors) ct(income/sales)
    writetrans($dept['debtacc'], $dept['incacc'], $inv['odate'], $refnum, sprint($TOTAL - $VAT - $nsp), "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    # dt(debtors) ct(vat account)
    writetrans($dept['debtacc'], $vatacc, $inv['odate'], $refnum, $VAT, "VAT Received on Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    db_conn('cubit');
    $Sl = "\n\t\t\tINSERT INTO sj (\n\t\t\t\tcid, name, des, date, exl, \n\t\t\t\tvat, inc, div\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$inv['surname']}', 'Invoice {$invnum}', '{$inv['odate']}', '" . sprint($TOTAL - $VAT) . "', \n\t\t\t\t'{$VAT}', '" . sprint($TOTAL) . "', '" . USER_DIV . "'\n\t\t\t)";
    $Ri = db_exec($Sl);
    //		db_connect();
    //		$sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)
    //		VALUES('$inv[odate]', '$invid', '$invnum', '$dept[debtacc]', '$VAT', '$TOTAL', 'stk', '".USER_DIV."')";
    //		$recRslt = db_exec($sql);
    //exit;
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* - End Transactoins - */
    # vat explanation
    if ($inv['chrgvat'] == 'nov') {
        $expl = "VAT Exempt indicator";
    } else {
        $expl = "VAT Exempt indicator";
    }
    if (strlen($inv['comm']) > 0) {
        $inv['comm'] = "\n\t\t\t<table border='1' cellspacing='0' bordercolor='#000000'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Remarks:</td>\n\t\t\t\t\t<td>" . nl2br($inv['comm']) . "</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    $cc = "<script> sCostCenter('dt', 'Sales', '{$inv['odate']}', 'Invoice No.{$invnum} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', ''); </script>";
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='SALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sp = "\n\t\t\t<tr>\n\t\t\t\t<td><b>Sales Person:</b> {$inv['salespn']}</td>\n\t\t\t</tr>";
    } else {
        $sp = "";
    }
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if ($inv['branch'] == 0) {
        $branchname = "Head Office";
    } else {
        $get_bname = "SELECT * FROM customer_branches WHERE id = '{$inv['branch']}' LIMIT 1";
        $run_bname = db_exec($get_bname);
        if (pg_numrows($run_bname) < 1) {
            $branchname = "";
        } else {
            $arr = pg_fetch_array($run_bname);
            $branchname = $arr['branch_name'];
        }
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    if (strlen(COMP_TEL) > 0) {
        $showtel = "Tel: ";
    } else {
        $showtel = "";
    }
    if (strlen(COMP_FAX) > 0) {
        $showfax = "Fax: ";
    } else {
        $showfax = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company information from Cubit.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    $bank_data = qryBankAcct(getdSetting("BANK_DET"));
    // Retrieve customer information
    db_conn("cubit");
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusnum']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
    $cust_data = pg_fetch_array($cust_rslt);
    $table_borders = "\n\t\tborder-top: 2px solid #000000;\n\t\tborder-left: 2px solid #000000;\n\t\tborder-right: 2px solid #000000;\n\t\tborder-bottom: none;";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $barcode = "<img src='manufact/" . pick_slip_barcode($inv["invid"], 1) . "' />";
        $details .= "\n\t\t<center>\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='left'><img src='compinfo/getimg.php' width='230' height='47'>{$barcode}</td>\n\t\t\t\t\t<td align='left'><font size='5'><b>" . COMP_NAME . "</b></font></td>\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Invoice</b></font></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td valign='top'>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td><td valign='top'>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\n\t\t\t\t\t<td><b>Page Number</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\n\t\t\t\t</tr>\n\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr><td>&nbsp</td></tr>\n\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$invnum}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Sales Order No:</b> {$inv['ordno']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Account No:</b> {$cust_data['accno']}</td>\n\t\t\t\t</tr>\n\t\t\t\t{$sp}\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='center'><font size='4'><b>Tax Invoice To:</b></font></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$inv['surname']}</b></td>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\n\t\t\t\t\t<td>Branch: {$branchname}<br />" . nl2br($inv["del_addr"]) . "</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer Order No:</b> {$inv['cordno']}</td>\n\t\t\t\t\t<td width='33%'><b>Delivery Date:</b> {$inv['deldate']}</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;'><b>Code</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;'><b>Description</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;'><b>Qty</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;' align='right'><b>Unit Price</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;' align='right'><b>Unit Discount</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000' align='right'><b>Amount</b></td>\n\t\t\t\t</tr>\n\t\t\t\t{$products_out}\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$inv['comm']}</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms: {$inv['terms']} days</b></td>\n\t\t\t\t\t<td><b>Subtotal:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['subtot']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t\t\t\t\t<td><b>Trade Discount:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['discount']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\n\t\t\t\t\t<td><b>Delivery Charge</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['delivery']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['vat']}</b></td>\n\t\t\t\t<tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['total']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t</table>";
    }
    // Retrieve template settings from Cubit
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve the template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    $OUTPUT = "\n\t\t<script>\n\t\t\tsCostCenter('dt', 'Sales', '{$inv['odate']}', 'Invoice No.{$invnum} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', '');\n\t\t</script>";
    if (isset($email)) {
        $OUTPUT .= "\n\t\t\t<script>\n\t\t\t\tmove(\"invoices-email.php?evs={$inv['invid']}\");\n\t\t\t</script>";
        require "template.php";
    }
    if ($template == "invoice-print.php") {
        $OUTPUT .= $details;
        require "tmpl-print.php";
    } else {
        $OUTPUT .= "\n\t\t\t<script>\n\t\t\t\tmove(\"{$template}?invid={$inv['invid']}&type=inv\");\n\t\t\t</script>";
        require "template.php";
    }
}
function write($_POST)
{
    #get vars
    extract($_POST);
    #only process details if we are not changing the customer
    if (isset($customer_select) and isset($old_customer_select) and $customer_select != $old_customer_select) {
        return details($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $sdate = mkdate($nquo_year, $nquo_month, $nquo_day);
    $v->isOk($sdate, "date", 1, 1, "Invalid Date.");
    # used to generate errors
    $error = "asa@";
    // check the quote details
    $v->isOK($cusname, "string", 1, 100, "Invalid customer name");
    $v->isOK($cusaddr, "string", 0, 100, "Invalid customer address");
    $v->isOK($cusvatno, "string", 0, 50, "Invalid customer vat number");
    if ($chrgvat != "yes" && $chrgvat != "no" && $chrgvat != "none") {
        $v->addError($chrgvat, "Invalid vat option");
    }
    if (!isset($bodydata)) {
        $bodydata = "";
    }
    $bodydata = str_replace("'", "", $bodydata);
    //$bodydata = str_replace("<br>","",$bodydata);
    $bodydata = str_replace("  ", " ", $bodydata);
    $bodydata = str_replace("&nbsp;&nbsp;", " ", $bodydata);
    $bodydata = str_replace(" &nbsp;", " ", $bodydata);
    $bodydata = str_replace("&nbsp; ", " ", $bodydata);
    //[key] was $counter ... but it wasnt set ??
    $des[] = $bodydata;
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            //			$v->isOk ($des[$keys], "url", 1, 255, "Invalid Description.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- invoices Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['chrgvat'] = $chrgvat;
    # check if purchase has been printed
    if ($inv['done'] == "y") {
        $error = "<li class='err'> Error : quote number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $vatamount = 0;
    $showvat = TRUE;
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_connect();
    /* -- Start remove old items -- */
    # remove old items
    $sql = "DELETE FROM nons_inv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update quote items in Cubit.", SELF);
    $taxex = 0;
    /* -- End remove old items -- */
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod) && in_array($keys, $remprod)) {
            } else {
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                if (!isset($vatcodes[$keys])) {
                    $vatcodes[$keys] = 0;
                }
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                $Ri = db_exec($Sl);
                // 				if(pg_num_rows($Ri)<1) {
                // 					return "Please select the vatcode for all your stock.";
                // 				}
                $vd = pg_fetch_array($Ri);
                if ($vd['zero'] == "Yes") {
                    $excluding = "y";
                } else {
                    $excluding = "";
                }
                if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                    $showvat = FALSE;
                }
                $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, 0, $vd['vat_amount']);
                $vrs = explode("|", $vr);
                $ivat = $vrs[0];
                $iamount = $vrs[1];
                $vatamount += $ivat;
                $vate = 'n';
                if (isset($vatex) && in_array($keys, $vatex) || $vd['zero'] == "Yes") {
                    $taxex += $amt[$keys];
                    $vate = 'y';
                }
                $vate = $vatcodes[$keys];
                # insert purchase items
                $sql = "\n\t\t\t\t\tINSERT INTO nons_inv_items (\n\t\t\t\t\t\tinvid, qty, amt, unitcost, description, vatex, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$invid}', '{$qtys[$keys]}', '{$amt[$keys]}', '{$unitcost[$keys]}', '{$des[$keys]}','{$vate}',  '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert quote items to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Done'>";
        }
    } else {
        $_POST["done"] = "";
    }
    $_POST['showvat'] = $showvat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "no") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        //		$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = $vatamount;
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
    } elseif ($chrgvat == "yes") {
        $subtotal = sprint($sub);
        $subtotal = sprint($subtotal);
        //	$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = $vatamount;
        $SUBTOT = sprint($sub - $vatamount);
        $TOTAL = sprint($subtotal);
    } else {
        $subtotal = sprint($sub);
        $traddiscmt = sprint($subtotal);
        $subtotal = sprint($subtotal);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    /* --- Clac ---
    	# calculate subtot
    	if( isset($amt) ){
    		$SUBTOT = array_sum($amt);
    	}else{
    		$SUBTOT = 0.00;
    	}
    
    	$VATP = TAX_VAT;
    	if($chrgvat == "no"){
    		$SUBTOT = $SUBTOT;
    	}elseif($chrgvat == "yes"){
    		$SUBTOT = sprint(($SUBTOT * 100)/(100 + $VATP));
    	}else{
    		$SUBTOT = ($SUBTOT);
    	}
    
    	if($chrgvat != "none"){
    		$VAT = sprint($SUBTOT * ($VATP/100));
    	}else{
    		$VAT = 0;
    	}
    
    	$TOTAL = sprint($SUBTOT + $VAT);
    
    	/*# if vat is not included
    	$VATP = TAX_VAT;
    	if($chrgvat == "yes"){
    		$SUBTOT = sprintf("%0.2f", $TOTAL * 100 / (100 + $VATP) );
    	} elseif($chrgvat == "no") {
    		$SUBTOT = $TOTAL;
    		$TOTAL = sprintf("%0.2f", $TOTAL * (100 + $VATP) /100 );
    	}else{
    		$SUBTOT = $TOTAL;
    	}
    
    	// compute the sub total (total - vat), done this way because the specified price already includes vat
    	$VAT = $TOTAL - $SUBTOT;
    
    	/* --- End Clac --- */
    $ncdate = "{$ncdate_year}-{$ncdate_month}-{$ncdate_day}";
    if (!isset($lead)) {
        $lead = "";
    }
    # insert purchase to DB
    $sql = "\n\t\t\tUPDATE nons_invoices \n\t\t\tSET cusname = '{$cusname}', cusaddr = '{$cusaddr}', cusvatno = '{$cusvatno}', chrgvat = '{$chrgvat}', odate = '{$sdate}', \n\t\t\t\tsubtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}', remarks = '{$remarks}', lead = '{$lead}', ncdate = '{$ncdate}' \n\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update quote in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (!isset($doneBtn)) {
        return details($_POST);
    } else {
        $rslt = db_exec($sql) or errDie("Unable to update invoices status in Cubit.", SELF);
        #add lead
        if (isset($lead) and $lead == "yes") {
            db_conn("crm");
            $sql = "\n\t\t\t\tINSERT INTO leads (\n\t\t\t\t\tsurname, date, by, con, div, supp_id, cust_id, lead_source, birthdate, reports_to_id, assigned_to, \n\t\t\t\t\tassigned_to_id, account_id, gender, website, salespid, ncdate, team_id, dept_id, tell, hadd, ref\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cusname}', 'now', '" . USER_NAME . "', 'No', '" . USER_DIV . "', '0', '0', '0', 'now', '0', '" . USER_NAME . "', \n\t\t\t\t\t'0', '0', 'Male', 'http://', '0', '{$ncdate}', '0', '0', '', '{$cusaddr}', ''\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to add lead to database.");
            $lead_id = pglib_lastid("leads", "id");
        }
        // Final Laytout
        $write = "\n\t\t\t<script>\n\t\t\t\tprinter('nons-quote-print.php?invid={$invid}');\n\t\t\t</script>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>New Non-Stock Quotes</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Non-Stock Quotes for Customer <b>{$cusname}</b> has been recorded.</td>\n\t\t\t\t\t<td><input type='button' onClick=\"printer('nons-quote-print.php?invid={$invid}');\" value='Print Quote'></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='nons-quote-view.php'>View Non-Stock Quotes</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t</tr>\n\t\t\t</table>";
        return $write;
        // 		return "
        // 			<script>
        // 				printer('nons-quote-print.php?invid=$invid');
        // 				document.location='nons-multiline-quote-new.php';
        // 			</script>";
    }
}
function write($_POST)
{
    #get vars
    extract($_POST);
    if (isset($Cancel)) {
        db_connect();
        $Sl = "DELETE FROM corders WHERE sordid='{$sordid}' AND cusnum='0' AND div = '" . USER_DIV . "'";
        $Rs = db_exec($Sl) or errDie("Unable to delete Consignment Order information");
        $sordid--;
        $Sql = "SELECT setval('corders_sordid_seq', '{$sordid}')";
        $Rslt = db_exec($Sql) or errDie("Unable to set Consignment id.");
        header("Location: main.php");
    }
    if (!isset($cusnum)) {
        return details($_POST, "");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
    $v->isOk($sordid, "num", 1, 20, "Invalid Consignment Order 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($cord_day, "num", 1, 2, "Invalid Consignment Order Date day.");
    $v->isOk($cord_month, "num", 1, 2, "Invalid Consignment Order Date month.");
    $v->isOk($cord_year, "num", 1, 5, "Invalid Consignment Order Date year.");
    $odate = $cord_year . "-" . $cord_month . "-" . $cord_day;
    if (!checkdate($cord_month, $cord_day, $cord_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Consignment Order 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);
    }
    # Get Consignment Order info
    db_connect();
    $sql = "SELECT * FROM corders WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
    $sordRslt = db_exec($sql) or errDie("Unable to get Consignment Order information");
    if (pg_numrows($sordRslt) < 1) {
        return "<li>- Consignment Order Not Found</li>";
    }
    $sord = pg_fetch_array($sordRslt);
    $sord['chrgvat'] = $chrgvat;
    # check if Consignment Order has been printed
    if ($sord['accepted'] == "y") {
        $error = "<li class='err'> Error : Consignment Order number <b>{$sordid}</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 sord_data WHERE sordid = '{$sordid}' 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);
        $sord['deptid'] = $cust['deptid'];
        # If customer was just selected, get the following
        if ($sord['cusnum'] == 0) {
            $traddisc = $cust['traddisc'];
            $terms = $cust['credterm'];
        }
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$sord['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 Consignment Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # get selected stock in this Consignment Order
    db_connect();
    $sql = "SELECT * FROM corders_items  WHERE sordid = '{$sordid}' 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 corders_items WHERE sordid='{$sordid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Consignment Order 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], $sord['chrgvat'], $excluding, $sord['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\tINSERT INTO corders_items (\n\t\t\t\t\t\tsordid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\tamt, disc, discp, div, vatcode, \n\t\t\t\t\t\tdescription, account\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sordid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t'{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '" . USER_DIV . "', '{$vatcodes[$keys]}', \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 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], $sord['chrgvat'], $excluding, $sord['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 Consignment Order items
                $sql = "\n\t\t\t\t\tINSERT INTO corders_items (\n\t\t\t\t\t\tsordid, whid, stkid, qty, unitcost, \n\t\t\t\t\t\tamt, disc, discp, div, vatcode\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sordid}', '{$whids[$keys]}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', \n\t\t\t\t\t\t'{$amt[$keys]}', '{$disc[$keys]}', '{$discp[$keys]}', '" . USER_DIV . "','{$vatcodes[$keys]}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert Consignment Order 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"] = "&nbsp; | &nbsp;<input name='doneBtn' type='submit' value='Done'>\n\t\t\t\t&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);
    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, $sord['chrgvat'], $excluding, $sord['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);
    }
    # insert Consignment Order to DB
    $sql = "\n\t\tUPDATE corders \n\t\tSET delvat='{$delvat}', cusnum = '{$cusnum}', deptid = '{$dept['deptid']}', deptname = '{$dept['deptname']}', \n\t\t\tcusacc = '{$cust['accno']}', cusname = '{$cust['cusname']}', surname = '{$cust['surname']}', cusaddr = '{$cust['addr1']}', \n\t\t\tcusvatno = '{$cust['vatnum']}', cordno = '{$cordno}', ordno = '{$ordno}', chrgvat = '{$chrgvat}', terms = '{$terms}', \n\t\t\tsalespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', \n\t\t\tvat = '{$VAT}', total = '{$TOTAL}', balance = '{$TOTAL}', comm = '{$comm}', discount='{$traddiscmt}', \n\t\t\tdelivery='{$delexvat}' \n\t\tWHERE sordid = '{$sordid}'";
    $rslt = db_exec($sql) or errDie("Unable to update Consignment Order in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM cord_data WHERE sordid='{$sordid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Consignment Order data in Cubit.", SELF);
    # pu in new data
    $sql = "\n\t\tINSERT INTO cord_data (\n\t\t\tsordid, dept, customer, addr1, div\n\t\t) VALUES (\n\t\t\t'{$sordid}', '{$dept['deptname']}', '{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '" . USER_DIV . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert Consignment Order data to Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($donePrnt)) {
        $sql = "UPDATE corders SET done='y' WHERE sordid='{$sordid}' AND div='" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Consignment Order status in Cubit.");
        $OUTPUT = "\n\t\t\t<script>\n\t\t\t\tprinter('corder-print.php?sordid={$sordid}');\n\t\t\t\tmove('corder-new.php');\n\t\t\t</script>";
        return $OUTPUT;
    }
    if (isset($doneBtn)) {
        # insert Consignment Order to DB
        $sql = "UPDATE corders SET done = 'y' WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Consignment 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 Consignment Order</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Consignment Order for customer <b>{$cust['cusname']} {$cust['surname']}</b> has been recorded.</td>\n\t\t\t\t\t<td><a target='_blank' href='corder-print.php?sordid={$sordid}'>Print</a></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t</tr>\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 Consignment Order Saved</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Consignment Order 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='corder-view.php'>View Consignment Orders</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;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        return details($_POST);
    }
}
function write($_POST)
{
    #get vars
    extract($_POST);
    if (isset($cusnum) && customer_overdue($cusnum)) {
        return details($_POST, "<li class='err'>Customer is overdue, account blocked!</li>");
    }
    $pcredit += 0;
    $pcash += 0;
    $pcheque += 0;
    $pcc += 0;
    $deptid += 0;
    db_conn('cubit');
    if (isset($printsales)) {
        $Sl = "SELECT * FROM settings WHERE constant='PSALES'";
        $Ri = db_exec($Sl) or errDie("Unable to get settings.");
        if (pg_num_rows($Ri) < 1) {
            $Sl = "INSERT INTO settings (constant,value,div) VALUES ('PSALES','Yes','" . USER_DIV . "')";
            $Ri = db_exec($Sl);
        } else {
            $Sl = "UPDATE settings SET value='Yes' WHERE constant='PSALES' AND div='" . USER_DIV . "'";
            $Ri = db_exec($Sl);
        }
    } else {
        $Sl = "UPDATE settings SET value='No' WHERE constant='PSALES' AND div='" . USER_DIV . "'";
        $Ri = db_exec($Sl);
    }
    //$it+=0;
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($client)) {
        $v->isOk($client, "string", 0, 20, "Invalid Customer.");
    } else {
        $client = "";
    }
    if (isset($vatnum)) {
        $v->isOk($vatnum, "string", 0, 30, "Invalid VAT Number.");
    } else {
        $vatnum = "";
    }
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice Number.");
    $v->isOk($telno, "string", 0, 20, "Invalid Customer Telephone Number.");
    $v->isOk($cordno, "string", 0, 20, "Invalid Customer Order Number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($ordno, "string", 0, 20, "Invalid sales order number.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    $v->isOk($salespn, "string", 1, 255, "Invalid sales person.");
    $v->isOk($pinv_day, "num", 1, 2, "Invalid Invoice Date day.");
    $v->isOk($pinv_month, "num", 1, 2, "Invalid Invoice Date month.");
    $v->isOk($pinv_year, "num", 1, 5, "Invalid Invoice Date year.");
    $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day;
    if (!checkdate($pinv_month, $pinv_day, $pinv_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    if ($traddisc > 100) {
        $v->isOk($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
    }
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    $odate = $pinv_year . "-" . $pinv_month . "-" . $pinv_day;
    if (!checkdate($pinv_month, $pinv_day, $pinv_year)) {
        $v->isOk($odate, "num", 1, 1, "Invalid Invoice Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        if (!ext_isUnique(ext_remBlnk($sernos))) {
            //$v->isOk ($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # check is serial no was selected
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            if (is_numeric($stkid)) {
                $sql = "SELECT units, stkcod FROM cubit.stock WHERE stkid='{$stkid}'";
                $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
                list($stock_units, $stock_code) = pg_fetch_array($stock_rslt);
                if ($qtys[$keys] > $stock_units) {
                    $v->addError(0, "Not enough stock available for {$stock_code}");
                }
            }
            # check if serial is selected
            if (ext_isSerial("stock", "stkid", $stkid) && !isset($sernos[$keys])) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number (2): <b>" . ($keys + 1) . "</b>");
            } elseif (ext_isSerial("stock", "stkid", $stkid) && strlen($sernos[$keys]) <= 0 && strlen($sernos_ss[$keys]) <= 0) {
                $v->isOk($error, "num", 0, 0, "Error : Missing serial number for product number (1): <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $discp[$keys] += 0;
            $disc[$keys] += 0;
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>" . ($keys + 1) . "</b>.");
            if ($disc[$keys] > $unitcost[$keys]) {
                $v->isOk($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>" . ($keys + 1) . "</b> is more than the unitcost.");
            }
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check whids
    if (isset($whids)) {
        foreach ($whids as $keys => $whid) {
            $v->isOk($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
        }
    }
    $cusnum += 0;
    # check stkids
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    $des = remval($des);
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return details($_POST, $err);
    }
    if (strlen($client) < 1) {
        $client = "Cash Sale";
    }
    if (strlen($vatnum) < 1) {
        $vatnum = "";
    }
    $_POST['client'] = $client;
    $_POST['vatnum'] = $vatnum;
    $_POST['telno'] = $telno;
    $_POST['cordno'] = $cordno;
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li>- Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    $inv['traddisc'] = $traddisc;
    $inv['chrgvat'] = $chrgvat;
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # fix those nasty zeros
    $traddisc += 0;
    $delchrg += 0;
    $vatamount = 0;
    $showvat = TRUE;
    # insert invoice to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # get selected stock in this invoice
    $sql = "SELECT * FROM pinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stktRslt = db_exec($sql);
    while ($stkt = pg_fetch_array($stktRslt)) {
        # update stock(alloc + qty)
        $sql = "UPDATE stock SET alloc = (alloc - '{$stkt['qty']}')  WHERE stkid = '{$stkt['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if (strlen($stkt['serno']) > 0) {
            ext_unresvSer($stkt['serno'], $stkt['stkid']);
        }
    }
    # remove old items
    $sql = "DELETE FROM pinv_items WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice items in Cubit.", SELF);
    /* -- End remove old items -- */
    $taxex = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            /* set the serial ss field for serials selected from list */
            if ($sernos_ss[$keys] == "*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*") {
                $sernos_ss[$keys] = $sernos[$keys];
            }
            if (isset($remprod) && in_array($keys, $remprod)) {
                if ($sernos[$keys] == $sernos_ss[$keys] && $sernos_ss[$keys] != "") {
                    $chr = substr($sernos[$keys], strlen($sernos[$keys]) - 1, 1);
                    $tab = "ss{$chr}";
                    /* mark barcoded item as unavailable */
                    $sql = "UPDATE " . $tab . " SET active='yes' WHERE code = '{$sernos[$keys]}' AND div = '" . USER_DIV . "'";
                    db_exec($sql);
                }
            } else {
                if (isset($accounts[$keys]) && $accounts[$keys] != 0) {
                    $accounts[$keys] += 0;
                    # Get selamt from selected stock
                    db_conn('core');
                    $Sl = "SELECT * FROM accounts WHERE accid='{$accounts[$keys]}'";
                    $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                    $ad = pg_fetch_array($Ri);
                    $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                    $Ri = db_exec($Sl);
                    if (pg_num_rows($Ri) < 1) {
                        return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
                    }
                    $vd = pg_fetch_array($Ri);
                    if ($vd['zero'] == "Yes") {
                        $excluding = "y";
                    } else {
                        $excluding = "";
                    }
                    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                        $showvat = FALSE;
                    }
                    $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                    $vrs = explode("|", $vr);
                    $ivat = $vrs[0];
                    $iamount = $vrs[1];
                    $vatamount += $ivat;
                    # Check Tax Excempt
                    if ($vd['zero'] == "Yes") {
                        $taxex += $amt[$keys];
                        $exvat = "y";
                    } else {
                        $exvat = "n";
                    }
                    //$newvat+=vatcalc($amt[$keys],$chrgvat,$exvat,$traddisc);
                    $vatcodes[$keys] += 0;
                    $accounts[$keys] += 0;
                    $descriptions[$keys] = remval($descriptions[$keys]);
                    $wtd = $whids[$keys];
                    # insert invoice items
                    $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost,\n\t\t\t\t\t\t\t\tamt, disc, discp, ss, serno, div,vatcode,description,\n\t\t\t\t\t\t\t\taccount)\n\t\t\t\t\t\t\tVALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}',\n\t\t\t\t\t\t\t\t'{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}',\n\t\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '', '','" . USER_DIV . "',\n\t\t\t\t\t\t\t\t'{$vatcodes[$keys]}','{$descriptions[$keys]}',\n\t\t\t\t\t\t\t\t'{$accounts[$keys]}')";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                } else {
                    # get selamt from selected stock
                    $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                    $stkRslt = db_exec($sql);
                    $stk = pg_fetch_array($stkRslt);
                    # Calculate the Discount discount
                    if ($disc[$keys] < 1) {
                        if ($discp[$keys] > 0) {
                            $disc[$keys] = $discp[$keys] / 100 * $unitcost[$keys];
                        }
                    } else {
                        $discp[$keys] = $disc[$keys] * 100 / $unitcost[$keys];
                    }
                    # Calculate amount
                    $amt[$keys] = $qtys[$keys] * ($unitcost[$keys] - $disc[$keys]);
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$keys]}'";
                    $Ri = db_exec($Sl);
                    if (pg_num_rows($Ri) < 1) {
                        return details($_POST, "<li class=err>Please select the vatcode for all your items.</li>");
                    }
                    $vd = pg_fetch_array($Ri);
                    if ($vd['zero'] == "Yes") {
                        $excluding = "y";
                    } else {
                        $excluding = "";
                    }
                    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                        $showvat = FALSE;
                    }
                    $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
                    $vrs = explode("|", $vr);
                    $ivat = $vrs[0];
                    $iamount = $vrs[1];
                    $vatamount += $ivat;
                    # Check Tax Excempt
                    if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                        $taxex += $amt[$keys];
                        $exvat = "y";
                    } else {
                        $exvat = "n";
                    }
                    $wtd = $whids[$keys];
                    # insert invoice items
                    $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty,\n\t\t\t\t\t\t\t\tunitcost, amt, disc, discp, ss, serno, div,vatcode)\n\t\t\t\t\t\t\tVALUES('{$invid}', '{$whids[$keys]}', '{$stkids[$keys]}',\n\t\t\t\t\t\t\t\t'{$qtys[$keys]}', '{$unitcost[$keys]}', '{$amt[$keys]}',\n\t\t\t\t\t\t\t\t'{$disc[$keys]}', '{$discp[$keys]}', '{$sernos_ss[$keys]}', '{$sernos[$keys]}',\n\t\t\t\t\t\t\t\t'" . USER_DIV . "','{$vatcodes[$keys]}')";
                    // $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, div) VALUES('$invid', '$whids[$keys]', '$stkids[$keys]', '$qtys[$keys]', '$unitcost[$keys]','$amt[$keys]', '$disc[$keys]', '$discp[$keys]', '".USER_DIV."')";
                    $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
                    if (strlen($sernos[$keys]) > 0) {
                        ext_resvSer($sernos[$keys], $stk['stkid']);
                    }
                    # update stock(alloc + qty)
                    $sql = "UPDATE stock SET alloc = (alloc + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
                    $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
                }
            }
            # everything is set place done button
            $_POST["done"] = " | <input name='doneBtn' type='submit' value='Process'>";
        }
    } else {
        $_POST["done"] = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$delvat}'";
    $Ri = db_exec($Sl);
    // 		/*if(pg_num_rows($Ri)>0) {
    // 			*/$taxex += $delchrg;
    // 		}
    $vd = pg_fetch_array($Ri);
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    $_POST['showvat'] = $showvat;
    $vr = vatcalc($delchrg, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $vatamount += $ivat;
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        // 			$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = sprint($vatamount);
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        // 			$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = sprint($vatamount);
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    $Sl = "SELECT * FROM posround";
    $Ri = db_exec($Sl);
    $data = pg_fetch_array($Ri);
    if ($data['setting'] == "5cent") {
        if (sprint(floor(sprint($TOTAL / 0.05))) != sprint($TOTAL / 0.05)) {
            $otot = $TOTAL;
            $nTOTAL = sprint(sprint(floor($TOTAL / 0.05)) * 0.05);
            $rounding = $otot - $nTOTAL;
        } else {
            $rounding = 0;
        }
    } else {
        $rounding = 0;
    }
    //print sprint(floor($TOTAL/0.05));
    #get accno if invoice is on credit
    if ($cusnum != "0") {
        $get_acc = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
        $run_acc = db_exec($get_acc) or errDie("Unable to get customer information");
        if (pg_numrows($run_acc) < 1) {
            $accno = "";
        } else {
            $arr = pg_fetch_array($run_acc);
            $cusacc = $arr['accno'];
        }
    } else {
        $cusacc = "";
    }
    //	die($cusnum);
    # insert invoice to DB
    $sql = "UPDATE pinvoices SET pcredit='{$pcredit}',cusnum='{$cusnum}',delvat='{$delvat}',rounding='{$rounding}',pcash='{$pcash}',pcheque='{$pcheque}',\n\t\tpcc='{$pcc}',deptid='{$deptid}',deptname = '{$dept['deptname']}', cusname = '{$client}', cordno = '{$cordno}', ordno = '{$ordno}',chrgvat = '{$chrgvat}',\n\t\tsalespn = '{$salespn}', odate = '{$odate}', traddisc = '{$traddisc}', delchrg = '{$delchrg}', subtot = '{$SUBTOT}', vat = '{$VAT}', total = '{$TOTAL}',\n\t\tbalance = '{$pcredit}', comm = '{$comm}', discount='{$traddiscmt}', delivery='{$delexvat}', vatnum='{$vatnum}', cusacc = '{$cusacc}', telno='{$telno}'\n\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # remove old data
    $sql = "DELETE FROM pinv_data WHERE invid='{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice data in Cubit.", SELF);
    # put in new data
    $sql = "INSERT INTO pinv_data(invid, dept, customer, div) VALUES('{$invid}', '{$dept['deptname']}', '{$client}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice data to Cubit.", SELF);
    # commit updatin
    if (strlen($bar) > 0) {
        /* check if there a stock item with global barcode matching input barcode */
        $sql = "SELECT * FROM stock WHERE bar='{$bar}' AND div = '" . USER_DIV . "'";
        $barRslt = db_exec($sql);
        if (pg_num_rows($barRslt) <= 0) {
            /* fetch last character of barcode */
            $chr = substr($bar, strlen($bar) - 1, 1);
            /* invalid barcode */
            if (!is_numeric($chr)) {
                return details($_POST, "The code you selected is invalid");
            }
            /* which barcode table to scan for stock id */
            $tab = "ss{$chr}";
            $stid = barext_dbget($tab, 'code', $bar, 'stock');
            $stab = "serial{$chr}";
            $sstid = serext_dbget($stab, 'serno', $bar, 'stkid');
            /* non-existing barcode, check for serial number */
            if ($stid <= 0) {
                if ($sstid <= 0) {
                    return details($_POST, "<li class='err'>The serial number/bar code you selected is not in the system or is not available.</li>");
                }
                if (serext_dbnum($stab, 'serno', $bar, 'stkid') > 1) {
                    return details($_POST, "<li class='err'>Duplicate serial numbers found, please scan barcode or select stock item.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $stab . " SET rsvd='y' WHERE serno='{$bar}'";
                db_exec($sql);
                $serno_bar = "{$bar}";
                $stid = $sstid;
            } else {
                if ($sstid > 0) {
                    return details($_POST, "<li class='err'>A serial and barcode with same value, please scan other value or select product manually.</li>");
                }
                /* mark barcoded item as unavailable */
                $sql = "UPDATE " . $tab . " SET active='no' WHERE code='{$bar}' AND div='" . USER_DIV . "'";
                db_exec($sql);
                $serno_bar = "{$bar}";
            }
            /* fetch stock row for selected item */
            $sql = "SELECT * FROM stock WHERE stkid = '{$stid}' AND div = '" . USER_DIV . "'";
            $barRslt = db_exec($sql);
        } else {
            $serno_bar = "";
        }
        $s = pg_fetch_array($barRslt);
        /* allocate stock item */
        $sql = "UPDATE stock SET alloc = (alloc + '1') WHERE stkid = '{$s['stkid']}' AND div = '" . USER_DIV . "'";
        db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost, amt,\n\t\t\t\t\tdisc, discp, ss, serno, div)\n\t\t\t\tVALUES('{$invid}', '{$s['whid']}', '{$s['stkid']}', '1','{$s['selamt']}',\n\t\t\t\t\t'{$s['selamt']}', '0', '0','{$bar}', '{$serno_bar}', '" . USER_DIV . "')";
        db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* --- Start button Listeners --- */
    if (isset($doneBtn)) {
        # check if stock was selected(yes = put done button)
        db_connect();
        $sql = "SELECT stkid FROM pinv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
        $crslt = db_exec($sql);
        if (pg_numrows($crslt) < 1) {
            $error = "<li class='err'> Error : Invoice number has no items.";
            return details($_POST, $error);
        }
        $TOTAL = sprint($TOTAL - $rounding);
        #check for credit limit
        if ($cusnum != "0") {
            #customer is selected ... get info
            $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND location != 'int' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to view customer");
            if (pg_numrows($custRslt) < 1) {
                $cust['balance'] = "0";
                $cust['creditlimit'] = "0";
            } else {
                $cust = pg_fetch_array($custRslt);
            }
            #customer is set check for response
            if ($pcredit + $cust['balance'] > $cust['credlimit']) {
                #limit reached ... check for block
                db_conn("cubit");
                $get_check = "SELECT value FROM set WHERE label = 'CUST_INV_WARN' LIMIT 1";
                $run_check = db_exec($get_check) or errDie("Unable to get credit limit response setting");
                if (pg_numrows($run_check) < 1) {
                    #no setting ? do nothing ....
                } else {
                    $sarr = pg_fetch_array($run_check);
                    if ($sarr['value'] == "block") {
                        #block account ...
                        return details($_POST, "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " " . sprint($cust["credlimit"]) . "</b> has been exceeded.</li>");
                    }
                }
                # Check permissions
                if (!perm("invoice-limit-override.php")) {
                    return details($_POST, "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " " . sprint($cust["credlimit"]) . "</b> has been exceeded.</li>");
                }
            }
        }
        if ($pcash + $pcheque + $pcc + $pcredit < $TOTAL) {
            return details($_POST, "<li class='err'>The total of all the payments is less than the invoice total</li>");
        }
        $change = sprint(sprint($pcash + $pcheque + $pcc + $pcredit) - sprint($TOTAL));
        $pcash = sprint($pcash - $change);
        if ($pcash < 0) {
            $pcash = 0;
        }
        if (sprint($pcash + $pcheque + $pcc + $pcredit) != sprint($TOTAL)) {
            return details($_POST, "<li class='err'>The total of all the payments is not equal to the invoice total.<br>\n\t\t\t(You can only overpay with cash)</li>");
        }
        # insert quote to DB
        $sql = "UPDATE pinvoices SET done = 'y' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice status in Cubit.", SELF);
        # print the invoice
        $OUTPUT = "\n\t\t\t\t\t<script>printer2('pos-invoice-print.php?invid={$invid}');</script>\n\t\t\t\t\t<input type='button' value='Create New POS Invoice' onClick=\"move('pos-invoice-new-no-neg.php');\">";
        require "template.php";
    } elseif (isset($saveBtn)) {
        // Final Laytout
        $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>New Point of Sale Invoice Saved</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Invoice for <b>{$client}</b> has been saved.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-new-no-neg.php'>New Point of Sale Invoice</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-list.php'>View Point of Sale Invoices</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
        return $write;
    } elseif (isset($cancel)) {
        // Final Laytout
        $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>New Point of Sale Invoice Saved</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Invoice for <b>{$client}</b> has been saved.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-new-no-neg.php'>New Point of Sale Invoice</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pos-invoice-list.php'>View Point of Sale Invoices</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
        return $write;
    } else {
        if (isset($wtd)) {
            $_POST['wtd'] = $wtd;
        }
        return details($_POST);
    }
    /* --- End button Listeners --- */
}
function write($_POST)
{
    # get vars
    extract($_POST);
    $rounding += 0;
    $pcredit += 0;
    $vatamount = 0;
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $v->isOk($prd, "num", 1, 20, "Invalid period number.");
    $v->isOk($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($odate, "date", 1, 14, "Invalid Invoice note date.");
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    $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, "float", 1, 15, "Invalid Returned Quantity.");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount.");
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "Invalid Returned Quantity.");
    }
    # Check stkids[]
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.{$stkid}");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "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.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "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 error($_POST, $err);
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -------------------------------- */
    # Get invoice info
    db_conn($prd);
    $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    if ($rounding > 0) {
        db_conn('core');
        $Sl = "SELECT * FROM salesacc WHERE name='rounding'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set the rounding account, under sales settings.";
        }
        $ad = pg_fetch_array($Ri);
        $rac = $ad['accnum'];
    }
    $notenum = divlastid('note', USER_DIV);
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $taxex = 0;
    foreach ($qtys as $keys => $value) {
        db_connect();
        # 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);
        # get selected stock in this invoice
        db_conn($prd);
        $sql = "SELECT * FROM pinv_items  WHERE id = '{$sids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        #check serial number
        if (strlen($stkd['ss']) > 0) {
            $me = $stkd['ss'];
        } else {
            $me = $stkd['serno'];
        }
        #determine which table to connect to
        switch (substr($me, strlen($me) - 1, 1)) {
            case "0":
                $tab = "ss0";
                break;
            case "1":
                $tab = "ss1";
                break;
            case "2":
                $tab = "ss2";
                break;
            case "3":
                $tab = "ss3";
                break;
            case "4":
                $tab = "ss4";
                break;
            case "5":
                $tab = "ss5";
                break;
            case "6":
                $tab = "ss6";
                break;
            case "7":
                $tab = "ss7";
                break;
            case "8":
                $tab = "ss8";
                break;
            case "9":
                $tab = "ss9";
                break;
            default:
                $tab = "ss0";
        }
        db_connect();
        $upd = "UPDATE {$tab} SET active = 'yes' WHERE code = '{$stkd['ss']}' OR code = '{$stkd['serno']}'";
        $run_upd = db_exec($upd) or errDie("Unable to update stock serial numbers");
        # get warehouse name
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # Calculate the Discount discount
        if ($disc[$keys] < 1) {
            if ($discp[$keys] > 0) {
                $disc[$keys] = $discp[$keys] / 100 * $stkd['unitcost'];
            }
        } else {
            $discp[$keys] = $disc[$keys] * 100 / $stkd['unitcost'];
        }
        # Calculate amount
        $amt[$keys] = $qtys[$keys] * ($stkd['unitcost'] - $disc[$keys]);
        db_connect();
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        $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];
        }
        if ($stkd['account'] != 0) {
            # put in product
            $products .= "\n\t\t\t<input type='hidden' name='vatcode[]' value='{$stkd['vatcode']}' />\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><input type='hidden' name='stkids[]' value='{$stk['stkid']}'>{$stkd['description']}</td>\n\t\t\t\t<td><input type='hidden' size='5' name='qtys[]' value='{$qtys[$keys]}'>{$qtys[$keys]}</td>\n\t\t\t\t<td nowrap>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$amt[$keys]}'>" . CUR . " {$amt[$keys]}</td>\n\t\t\t</tr>";
        } else {
            # put in product
            $products .= "\n\t\t\t<input type='hidden' name='vatcode[]' value='{$stkd['vatcode']}' />\n\t\t\t<tr>\n\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stk['stkid']}'>{$stk['stkcod']}</td>\n\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t<td><input type='hidden' size='5' name='qtys[]' value='{$qtys[$keys]}'>{$qtys[$keys]}</td>\n\t\t\t\t<td nowrap>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$amt[$keys]}'>" . CUR . " {$amt[$keys]}</td>\n\t\t\t</tr>";
        }
    }
    # 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);
    }
    /* calculate delivery charge vat */
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
    $Ri = db_exec($Sl);
    $vd = pg_fetch_array($Ri);
    $vr = vatcalc($delchrg, $inv['chrgvat'], $vd['zero'] == "Yes" ? "y" : "", $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $vatamount += $ivat;
    /* --- ----------- Clac ---------------------
    
    	# calculate subtot
    	$SUBTOT = 0.00;
    	if(isset($amt))
    	$SUBTOT = array_sum($amt);
    
    	$SUBTOT -= $taxex;
    
    	# duplicate
    	$SUBTOTAL = $SUBTOT;
    
    	$VATP = TAX_VAT;
    	if($inv['chrgvat'] == "exc"){
    	$SUBTOTAL = $SUBTOTAL;
    	$delexvat= ($delchrg);
    	}elseif($inv['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);
    	$traddiscm = $traddiscmt;
    
    	if($inv['chrgvat'] != "nov"){
    	$VAT = sprint($EXVATTOT * ($VATP/100));
    	}else{
    	$VAT = 0;
    	}
    
    	$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
    	$SUBTOT += $taxex;
    
    	/* --- ----------- Clac --------------------- */
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $chrgvat = $inv['chrgvat'];
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($chrgvat == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //$VAT=sprint(($subtotal-$taxex)*$VATP/100);
        $VAT = sprint($vatamount);
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($chrgvat == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //$VAT=sprint(($subtotal-$taxex)*$VATP/(100+$VATP));
        $VAT = sprint($vatamount);
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    # Get invoice info
    db_conn($prd);
    $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li class='err'>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    if ($inv['balance'] >= $TOTAL) {
        $invpay = $TOTAL;
        $examt = 0;
    } else {
        $invpay = $inv['balance'];
        $examt = $TOTAL - $invpay;
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*refnum*/
    # insert invoice to period DB
    if ($inv['cusnum'] != "0") {
        #then get the actual customer
        db_connect();
        $get_cus = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' LIMIT 1";
        $run_cus = db_exec($get_cus) or errDie("Unable to get customer information");
        if (pg_numrows($run_cus) < 1) {
            #do nothing
        } else {
            $carr = pg_fetch_array($run_cus);
            $inv['cusname'] = "{$carr['cusname']}";
            $inv['surname'] = "{$carr['surname']}";
        }
    }
    db_conn($prd);
    # Format date
    $odate = explode("-", $odate);
    $rodate = $odate[2] . "-" . $odate[1] . "-" . $odate[0];
    $td = $rodate;
    # Insert invoice credit note to DB
    $sql = "INSERT INTO inv_notes(deptid, notenum, invnum, invid, cusnum, cordno, ordno,\n\t\t\t\tchrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, comm,\n\t\t\t\tusername, div, surname, cusaddr, cusvatno, telno, deptname, prd)";
    $sql .= " VALUES('{$inv['deptid']}', '{$notenum}', '{$inv['invnum']}', '{$inv['invid']}',\n\t\t\t\t'{$inv['cusnum']}', '{$inv['cordno']}', '{$inv['ordno']}', '{$inv['chrgvat']}',\n\t\t\t\t'{$terms}', '{$traddiscmt}', '{$inv['salespn']}', '{$rodate}', '{$delexvat}',\n\t\t\t\t'{$SUBTOT}', '{$VAT}' , '{$TOTAL}', '{$comm}', '" . USER_NAME . "', '" . USER_DIV . "',\n\t\t\t\t'{$inv['cusname']} {$inv['surname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['telno']}',\n\t\t\t\t'{$inv['deptname']}', {$inv['prd']})";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice to Cubit.", SELF);
    $invnum = $inv['invnum'];
    # Get next ordnum
    $noteid = pglib_lastid("inv_notes", "noteid");
    db_conn($prd);
    # Begin updating
    $nbal = $inv['nbal'] + $TOTAL;
    # Update the invoice (make balance less)
    $sql = "UPDATE pinvoices SET nbal = '{$nbal}', rdelchrg = (rdelchrg + '{$delchrg}'), balance = balance - '{$invpay}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $av = $VAT;
    $at = $TOTAL - $VAT;
    /*
    	$inv['pcash']=$pcash;
    	$inv['pcheque']=$pcheque;
    	$inv['pcc']=$pcc;
    	$inv['pcredit']=$pcredit;*/
    $sd = date("Y-m-d");
    db_conn('cubit');
    $Sl = "SELECT * FROM payrec WHERE inv='{$invnum}'";
    $Ri = db_exec($Sl);
    $data = pg_fetch_array($Ri);
    $user = $data['by'];
    $ro = $rounding;
    $ro += 0;
    $nsp = 0;
    # Commit updating
    $inv['pcash'] = $pcash;
    $inv['pcheque'] = $pcheque;
    $inv['pcc'] = $pcc;
    $inv['pcredit'] = $pcredit;
    $pcreditback = $pcredit;
    # Make ledge record
    //custledger($inv['cusnum'], $dept['incacc'], $td, $notenum, "Credit Note No. $notenum for invoice No. $inv[invnum]", $TOTAL, "c");
    $commision = 0;
    if ($examt > 0) {
        # Make record for age analisys
        //custCTP($examt, $inv['cusnum'],$td);
    }
    $discs = 0;
    $salesp = qrySalesPersonN($inv["salespn"]);
    foreach ($qtys as $keys => $value) {
        db_connect();
        # 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);
        # get selected stock in this invoice
        db_conn($prd);
        $sql = "SELECT * FROM pinv_items  WHERE id = '{$sids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
        //print $sql;
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            # Keep track of discounts
            $discs += $stkd['disc'] * $stkd['qty'];
            db_connect();
            $Sl = "SELECT * FROM scr WHERE inv='{$inv['invnum']}' AND stkid='{$stkd['stkid']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) > 0) {
                $cd = pg_fetch_array($Ri);
                $stk['csprice'] = $cd['amount'];
            } else {
                $stk["csprice"] = 0;
            }
            # cost amount
            if ($stk['csprice'] == "0.00") {
                $cosamt = round($qtys[$keys] * $stk['lcsprice'], 2);
            } else {
                $cosamt = round($qtys[$keys] * $stk['csprice'], 2);
            }
            db_connect();
            # Update stock(onhand + qty)
            $sql = "UPDATE stock SET csamt = (csamt + '{$cosamt}'), units = (units + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            # fix stock cost amount
            $Sl = "UPDATE stock set csprice=csamt/units WHERE stkid = '{$stkids[$keys]}' AND units>0";
            $Ri = db_exec($Sl) or errDie("Unable to update stock cost price in Cubit.", SELF);
            if ($stk['serd'] == 'yes') {
                ext_InSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $notenum, 'note', $td);
            }
            # negetive values to minus profit
            $nqty = $qtys[$keys] * 1;
            $namt = $amt[$keys] * -1;
            $ncsprice = $cosamt * -1;
            $noted = $stkd['noted'] + $qtys[$keys];
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            stockrec($stkd['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $td, $nqty, $cosamt, "Credit note for Customer : {$inv['surname']} - Credit note No. {$notenum}");
            db_connect();
            # Get amount exluding vat if including and not exempted
            $VATP = TAX_VAT;
            $amtexvat = $amt[$keys];
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM cubit.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 ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd["vat_amount"]);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "VAT for Credit note: {$notenum} Customer : {$inv['surname']}", -$iamount, -$ivat);
            ####################################################
            $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\tVALUES('{$td}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'note', '{$qtys[$keys]}', '{$amtexvat}', '{$cosamt}', 'Credit note for Customer : {$inv['surname']} - Credit note No. {$notenum}', '" . USER_DIV . "')";
            $recRslt = db_exec($sql);
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = $stk["com"];
            }
            $commision = $commision + coms($inv['salespn'], $amt[$keys], $itemcommission);
            # Get selected stock in this invoice
            db_conn($prd);
            $sql = "UPDATE pinv_items SET noted = '{$noted}' WHERE id = '{$sids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
            $stkdsRslt = db_exec($sql);
            # get accounts
            db_conn("exten");
            $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $stockacc = $wh['stkacc'];
            $cosacc = $wh['cosacc'];
            # dt(stock) ct(cos)
            writetrans($stockacc, $cosacc, $td, $refnum, $cosamt, "Cost Of Sales for Credit note No. {$notenum}.");
            db_conn($prd);
            # insert invoice items
            $sql = "INSERT INTO inv_note_items(noteid, whid, stkid, qty, amt, div, vatcode) \n\t\t\t\t\tVALUES('{$noteid}', '{$stkd['whid']}', '{$stkids[$keys]}', '{$qtys[$keys]}', \n\t\t\t\t\t\t'{$amt[$keys]}', '" . USER_DIV . "', '{$vatcode[$keys]}')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            db_connect();
            $date = date("Y-m-d");
            $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\tVALUES('{$rodate}', '{$noteid}', '{$notenum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'nstk', '" . USER_DIV . "')";
            $recRslt = db_exec($sql);
        } else {
            db_connect();
            ###################VAT CALCS#######################
            $noted = $stkd['noted'] + $qtys[$keys];
            db_conn($prd);
            $sql = "UPDATE pinv_items SET noted = '{$noted}' WHERE id = '{$sids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
            $stkdsRslt = db_exec($sql);
            db_conn($prd);
            # insert invoice items
            $sql = "INSERT INTO inv_note_items(noteid, whid, stkid, qty, amt, div,description, vatcode) \n\t\t\t\t\tVALUES('{$noteid}', '{$stkd['vatcode']}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "', '{$stkd['description']}', '{$vatcode[$keys]}')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            db_connect();
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd["vat_amount"]);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            $av -= $ivat;
            $at -= $iamount;
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Credit note No. {$notenum} for Customer : {$inv['cusname']} {$inv['surname']}", -$iamount, -$ivat);
            ####################################################
            $amtexvat = sprint($stkd['amt']);
            db_connect();
            $sdate = date("Y-m-d");
            $nsp += sprint($iamount - $ivat);
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = 0;
            }
            $commision = $commision + coms($inv['salespn'], $amt[$keys], $itemcommission);
            // 				//writetrans($cosacc, $stockacc,$inv['odate'] , $refnum, $cosamt, "Cost Of Sales for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
            // 				writetrans($dept['debtacc'], $stkd['account'],$inv['odate'], $refnum, ($iamount-$ivat), "Debtors Control for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
            db_connect();
            $date = date("Y-m-d");
            $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\tVALUES('{$rodate}', '{$noteid}', '{$notenum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'nnon', '" . USER_DIV . "')";
            $recRslt = db_exec($sql);
            if ($inv['pcash'] > 0) {
                $min = $ro;
                $inv['pcash'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcash'] >= $ivat) {
                    writetrans($vatacc, $dept['pca'], $td, $refnum, $ivat, "VAT Returned for Credit note No. {$notenum}");
                    $inv['pcash'] = sprint($inv['pcash'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcash'] > 0) {
                        if ($inv['pcash'] >= $iamount) {
                            writetrans($stkd['account'], $dept['pca'], $td, $refnum, $iamount, "Sales for Credit note No. {$notenum}");
                            $inv['pcash'] = sprint($inv['pcash'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcash'] < $iamount) {
                            writetrans($stkd['account'], $dept['pca'], $td, $refnum, $inv['pcash'], "Sales for Credit note No. {$notenum}");
                            $iamount = sprint($iamount - $inv['pcash']);
                            $inv['pcash'] = 0;
                        }
                    }
                } else {
                    writetrans($vatacc, $dept['pca'], $td, $refnum, $inv['pcash'], "VAT Returned for Credit note No. {$notenum}");
                    $ivat = sprint($ivat - $inv['pcash']);
                    $inv['pcash'] = 0;
                }
                // 					db_conn('cubit');
                //
                // 					$inv['pcash']-=$min;
                //
                // 					$Sl="INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('$sd','".USER_NAME."','$invnum','$inv[pcash]','Cash','".PRD_DB."','0')";
                // 					$Ri=db_exec($Sl) or errDie("Unable to insert data.");
            }
            if ($inv['pcheque'] > 0) {
                $min = $ro;
                $inv['pcheque'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcheque'] >= $ivat) {
                    writetrans($vatacc, $dept['pca'], $td, $refnum, $ivat, "VAT Returned for Credit note No. {$notenum}");
                    $inv['pcheque'] = sprint($inv['pcheque'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcheque'] > 0) {
                        if ($inv['pcheque'] >= $iamount) {
                            writetrans($stkd['account'], $dept['pca'], $td, $refnum, $iamount, "Sales for Credit note No. {$notenum}");
                            $inv['pcheque'] = sprint($inv['pcheque'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcheque'] < $iamount) {
                            writetrans($stkd['account'], $dept['pca'], $td, $refnum, $inv['pcheque'], "Sales for Credit note No. {$notenum}");
                            $iamount = sprint($iamount - $inv['pcheque']);
                            $inv['pcheque'] = 0;
                        }
                    }
                } else {
                    writetrans($vatacc, $dept['pca'], $td, $refnum, $inv['pcheque'], "VAT Returned for Credit note No. {$notenum}");
                    $ivat = sprint($ivat - $inv['pcheque']);
                    $inv['pcheque'] = 0;
                }
                db_conn('cubit');
                $inv['pcash'] -= $min;
                $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$sd}','" . USER_NAME . "','{$invnum}','-{$inv['pcash']}','Cash','" . PRD_DB . "','{$noteid}')";
                $Ri = db_exec($Sl) or errDie("Unable to insert data.");
            }
            if ($inv['pcc'] > 0) {
                db_conn('core');
                $Sl = "SELECT * FROM salacc WHERE name='cc'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return "Please set a link for the POS credit card control account";
                }
                $cd = pg_fetch_array($Ri);
                $cc = $cd['accnum'];
                $min = $ro;
                $inv['pcc'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcc'] >= $ivat) {
                    writetrans($vatacc, $cc, $td, $refnum, $ivat, "VAT Returned for Credit note No. {$notenum}");
                    $inv['pcc'] = sprint($inv['pcc'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcc'] > 0) {
                        if ($inv['pcc'] >= $iamount) {
                            writetrans($stkd['account'], $cc, $td, $refnum, $iamount, "Sales for Credit note No. {$notenum}");
                            $inv['pcc'] = sprint($inv['pcc'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcc'] < $iamount) {
                            writetrans($stkd['account'], $cc, $td, $refnum, $inv['pcc'], "Sales for Credit note No. {$notenum}");
                            $iamount = sprint($iamount - $inv['pcc']);
                            $inv['pcc'] = 0;
                        }
                    }
                } else {
                    writetrans($vatacc, $cc, $td, $refnum, $inv['pcc'], "VAT Returned for Credit note No. {$notenum}");
                    $ivat = sprint($ivat - $inv['pcc']);
                    $inv['pcc'] = 0;
                }
                db_conn('cubit');
                $inv['pcash'] -= $min;
                $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$sd}','" . USER_NAME . "','{$invnum}','-{$inv['pcash']}','Cash','" . PRD_DB . "','{$noteid}')";
                $Ri = db_exec($Sl) or errDie("Unable to insert data.");
            }
            if ($inv['pcredit'] > 0) {
                db_conn('core');
                $min = $ro;
                $inv['pcredit'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcredit'] >= $ivat) {
                    writetrans($vatacc, $dept['debtacc'], $td, $refnum, $ivat, "VAT Returned for Credit note No. {$notenum}");
                    $inv['pcredit'] = sprint($inv['pcredit'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcredit'] > 0) {
                        if ($inv['pcredit'] >= $iamount) {
                            writetrans($stkd['account'], $dept['debtacc'], $td, $refnum, $iamount, "Sales for Credit note No. {$notenum}");
                            $inv['pcredit'] = sprint($inv['pcredit'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcredit'] < $iamount) {
                            writetrans($stkd['account'], $dept['debtacc'], $td, $refnum, $inv['pcredit'], "Sales for Credit note No. {$notenum}");
                            $iamount = sprint($iamount - $inv['pcredit']);
                            $inv['pcredit'] = 0;
                        }
                    }
                } else {
                    writetrans($vatacc, $dept['debtacc'], $td, $refnum, $inv['pcredit'], "VAT Returned for Credit note No. {$notenum}");
                    $ivat = sprint($ivat - $inv['pcredit']);
                    $inv['pcredit'] = 0;
                }
                db_conn('cubit');
                $inv['pcash'] -= $min;
                $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$sd}','" . USER_NAME . "','{$invnum}','-{$inv['pcash']}','Cash','" . PRD_DB . "','{$noteid}')";
                $Ri = db_exec($Sl) or errDie("Unable to insert data.");
            }
        }
    }
    db_connect();
    # save invoice discount
    $sql = "INSERT INTO inv_discs(cusnum, invid, traddisc, itemdisc, inv_date, delchrg, div) VALUES('{$inv['cusnum']}', '{$invid}', '0', '-{$discs}', '{$inv['odate']}', '0', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    /* - Start Transactoins - */
    ###################VAT CALCS#######################
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    $excluding = "";
    $vr = vatcalc($delexvat, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd["vat_amount"]);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "VAT for Credit note No. {$notenum}, Customer : {$inv['cusname']} {$inv['surname']}", -$iamount, -$ivat);
    ####################################################
    /*
    # dt(income) ct(debtors)
    writetrans($dept['pia'], $dept['pca'], $td, $refnum, ($TOTAL-$VAT), "Debtors Control for Credit note No. $notenum for Customer : $inv[cusname] $inv[surname]");
    
    # dt(vat) ct(debtors)
    writetrans($vatacc, $dept['pca'], $td, $refnum, $VAT, "VAT Return for Credit note No. $notenum for Customer : $inv[cusname] $inv[surname]");
    */
    //	db_connect();
    //	$date = date("Y-m-d");
    //	$sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)
    //	VALUES('$rodate', '$noteid', '$notenum', '$dept[debtacc]', '$VAT', '$TOTAL', 'nstk', '".USER_DIV."')";
    //	$recRslt = db_exec($sql);
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t('{$inv['cusnum']}','{$inv['surname']}','Credit Note:{$notenum}, POS Invoice {$inv['invnum']}','{$rodate}','" . -sprint($TOTAL - $VAT) . "','-{$VAT}','" . -sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    // 	$av=$VAT;
    // 	$at=$TOTAL-$VAT;
    //
    // 	$inv['pcash']=$pcash;
    // 	$inv['pcheque']=$pcheque;
    // 	$inv['pcc']=$pcc;
    // 	$inv['pcredit']=$pcredit;
    //
    // 	$sd=date("Y-m-d");
    //
    // 	db_conn('cubit');
    // 	$Sl="SELECT * FROM payrec WHERE inv='$invnum'";
    // 	$Ri=db_exec($Sl);
    //
    // 	$data=pg_fetch_array($Ri);
    //
    // 	$user=$data['by'];
    //
    // 	$ro=$rounding;
    // 	$ro+=0;
    if ($inv['pcash'] > 0) {
        $min = $ro;
        $inv['pcash'] += $ro;
        $ro = 0;
        $amount = $inv['pcash'];
        if ($amount >= $av) {
            writetrans($vatacc, $dept['pca'], $td, $refnum, $av, "VAT Returned for POS Credit note: {$notenum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['pia'], $dept['pca'], $td, $refnum, $amount, "Sales for POS Credit note: {$notenum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($vatacc, $dept['pca'], $td, $refnum, $amount, "VAT Returned for POS Credit note: {$notenum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcash'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','{$user}','{$invnum}','-{$inv['pcash']}','Cash','" . PRD_DB . "','{$noteid}')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['pcheque'] > 0) {
        $min = $ro;
        $inv['pcheque'] += $ro;
        $ro = 0;
        $amount = $inv['pcheque'];
        if ($amount >= $av) {
            writetrans($vatacc, $dept['pca'], $td, $refnum, $av, "VAT Returned for POS Credit note: {$notenum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['pia'], $dept['pca'], $td, $refnum, $amount, "Sales for POS Credit note: {$notenum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($vatacc, $dept['pca'], $td, $refnum, $amount, "VAT Returned for POS Credit note: {$notenum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcheque'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','{$user}','{$invnum}','-{$inv['pcheque']}','Cheque','" . PRD_DB . "','{$noteid}')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['pcc'] > 0) {
        db_conn('core');
        $Sl = "SELECT * FROM salacc WHERE name='cc'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set a link for the POS credit card control account";
        }
        $cd = pg_fetch_array($Ri);
        $cc = $cd['accnum'];
        $min = $ro;
        $inv['pcc'] += $ro;
        $ro = 0;
        $amount = $inv['pcc'];
        if ($amount >= $av) {
            writetrans($vatacc, $cc, $td, $refnum, $av, "VAT Returned for POS Credit note: {$notenum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['pia'], $cc, $td, $refnum, $amount, "Sales for POS Credit note: {$notenum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($vatacc, $cc, $td, $refnum, $amount, "VAT Returned for POS Credit note: {$notenum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcc'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','-{$inv['pcc']}','Credit Card','" . PRD_DB . "','{$noteid}')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['pcredit'] > 0) {
        db_conn('core');
        $cc = $dept['debtacc'];
        $min = $ro;
        $inv['pcredit'] += $ro;
        $ro = 0;
        $amount = $inv['pcredit'];
        if ($amount >= $av) {
            writetrans($vatacc, $cc, $td, $refnum, $av, "VAT Returned for POS Credit note: {$notenum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['pia'], $cc, $td, $refnum, $amount, "Sales for POS Credit note: {$notenum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($vatacc, $cc, $td, $refnum, $amount, "VAT Returned for POS Credit note: {$notenum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcc'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','-{$inv['pcredit']}','Credit','" . PRD_DB . "','{$noteid}')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['rounding'] > 0) {
        if ($inv['pcash'] > 0) {
            writetrans($dept['pca'], $rac, $td, $refnum, $inv['rounding'], "Rounding  on Credit note: {$notenum}.");
        } elseif ($inv['pcheque'] > 0) {
            writetrans($dept['pca'], $rac, $td, $refnum, $inv['rounding'], "Rounding on Credit note: {$notenum}.");
        } elseif ($inv['pcc'] > 0) {
            writetrans($cc, $rac, $td, $refnum, $inv['rounding'], "Rounding on Credit note: {$notenum}.");
        } elseif ($inv['pcredit'] > 0) {
            writetrans($dept['debtacc'], $rac, $td, $refnum, $inv['rounding'], "Rounding on Credit note: {$notenum}.");
        }
    }
    com_invoice($inv['salespn'], -($TOTAL - $VAT), -$commision, $invnum, $td);
    db_conn('cubit');
    $Sl = "INSERT INTO pr(userid,username,amount,pdate,inv,cust,t) VALUES ('" . USER_ID . "','" . USER_NAME . "','-{$TOTAL}','{$td}','{$invnum}','{$inv['cusname']}','{$inv['terms']}')";
    $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    if ($rounding > 0) {
        $Sl = "INSERT INTO pcnc (note,amount) VALUES ('{$notenum}','{$rounding}')";
        $Ri = db_exec($Sl);
    }
    $inv['pcredit'] = $pcreditback;
    if ($inv['cusnum'] > 0 && $inv['pcredit'] > 0) {
        $nt = $inv['pcredit'];
        # Record the payment on the statement
        $sql = "\n\t\t\tINSERT INTO stmnt \n\t\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\t\tVALUES \n\t\t\t\t('{$inv['cusnum']}', '{$invnum}', '0', '-{$nt}', '{$inv['odate']}', 'Credit Note {$notenum}', '" . USER_DIV . "', '{$inv['odate']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance more)
        $sql = "UPDATE customers SET balance = (balance - '{$nt}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Update the invoice (make balance less)
        $sql = "UPDATE open_stmnt SET balance = balance-'{$pcreditback}' WHERE invid = '{$inv['invnum']}'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        custledger($inv['cusnum'], $dept['incacc'], $inv['odate'], $invnum, "Credit note {$notenum}", $nt, "c");
        //print $nt;exit;
        recordCT($nt, $inv['cusnum'], $inv['odate']);
    }
    pglib_transaction("COMMIT");
    //die("<br /><br />NOTE: TRANSACTION ROLLBACK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    /* - End Transactoins - */
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h2>Credit Note</h2>\n\t\t\t\t\t<table cellpadding='0' cellspacing='4' border=0 width='750'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>{$inv['surname']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='top' width='25%'>\n\t\t\t\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td width='20%'>\n\t\t\t\t\t\t\t\t<img src='compinfo/getimg.php' width='230' height='47'>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='bottom' align='right' width='25%'>\n\t\t\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Credit Note No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$notenum}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Order No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['ordno']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Terms</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$terms} Days</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Credit note Date</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$rodate}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='4'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='100%' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t\t\t\t\t\t\t<th width='45%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t\t\t\t<th>QTY RETURNED</th>\n\t\t\t\t\t\t\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t\t\t\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t{$products}\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</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<td>\n\t\t\t\t\t\t\t\t<table border='1' cellspacing='0' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>" . nl2br($comm) . "</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td align='right' colspan='3'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='50%' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$SUBTOT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Trade Discount</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$traddiscmt}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Delivery Charge</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$delexvat}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>VAT @ {$VATP}%</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$VAT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th><b>GRAND TOTAL<b></th>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " border='1'>\n\t\t\t\t\t\t        \t<tr>\n\t\t\t\t\t\t        \t\t<th>VAT No.</th>\n\t\t\t\t\t\t        \t\t<td align='center'>" . COMP_VATNO . "</td>\n\t\t\t\t\t\t        \t</tr>\n\t\t\t\t\t\t        </table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td><br></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</center>";
    $OUTPUT = "<script>printer2('pos-note-slip.php?noteid={$noteid}&prd={$prd}&cccc=true');move('main.php');</script>";
    require "template.php";
}
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)
{
    $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($comm, "string", 0, 255, "Invalid Comments.");
    $v->isOk($terms, "num", 1, 20, "Invalid terms.");
    $v->isOk($odate, "date", 1, 14, "Invalid Invoice note date.");
    $v->isOk($traddisc, "float", 0, 20, "Invalid Trade Discount.");
    $v->isOk($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");
    $v->isOk($prd, "num", 1, 2, "Invalid prd.");
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "float", 1, 15, "Invalid Returned Quantity.");
            $v->isOk($disc[$keys], "float", 0, 20, "Invalid Discount.");
            $v->isOk($discp[$keys], "float", 0, 20, "Invalid Discount Percentage.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "Invalid Returned Quantity.");
    }
    # check stkids[]
    if (isset($stkids)) {
        foreach ($stkids as $keys => $stkid) {
            $v->isOk($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "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.");
        }
    } else {
        $v->isOk($error, "num", 0, 1, "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 error($_POST, $err);
    }
    /* -------------------------------- */
    # Get invoice info
    db_conn($prd);
    $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 "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($inv['odate']) >= strtotime($blocked_date_from) and strtotime($inv['odate']) <= 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>";
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $notenum = divlastid('note', USER_DIV);
    $vatamount = 0;
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $taxex = 0;
    foreach ($qtys as $keys => $value) {
        db_connect();
        # 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);
        db_conn($prd);
        # get selected stock in this invoice
        $sql = "SELECT * FROM inv_items  WHERE id = '{$ids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        if ($stkd['account'] == 0) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # Calculate the Discount discount
            if ($disc[$keys] < 1) {
                if ($discp[$keys] > 0) {
                    $disc[$keys] = $discp[$keys] / 100 * $stkd['unitcost'];
                }
            } else {
                $discp[$keys] = $disc[$keys] * 100 / $stkd['unitcost'];
            }
            # Calculate amount
            $amt[$keys] = $qtys[$keys] * ($stkd['unitcost'] - $disc[$keys]);
            db_connect();
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($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];
            }
            # put in product
            $products .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stk['stkid']}'>{$stk['stkcod']}</td>\n\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t<td><input type='hidden' size='5' name='qtys[]' value='{$qtys[$keys]}'>{$qtys[$keys]}</td>\n\t\t\t\t\t<td>{$stkd['unitcost']}</td>\n\t\t\t\t\t<td><input type='hidden' name='amt[]' value='{$amt[$keys]}'>" . CUR . " {$amt[$keys]}</td>\n\t\t\t\t</tr>";
        } else {
            # get warehouse name
            db_conn("core");
            $sql = "SELECT accname FROM accounts WHERE accid = '{$stkd['account']}'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $discp[$keys] = 0;
            # Calculate amount
            $amt[$keys] = $qtys[$keys] * ($stkd['unitcost'] - $disc[$keys]);
            db_connect();
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($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];
            }
            $wh['whname'] = "";
            $stk['stkid'] = 0;
            $stk['stkcod'] = $wh['accname'];
            $stk['stkdes'] = $stkd['description'];
            # put in product
            $products .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stk['stkid']}'>{$stk['stkcod']}</td>\n\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t<td><input type='hidden' size='5' name='qtys[]' value='{$qtys[$keys]}'>{$qtys[$keys]}</td>\n\t\t\t\t\t<td>{$stkd['unitcost']}</td>\n\t\t\t\t\t<td><input type='hidden' name='amt[]' value='{$amt[$keys]}'>" . CUR . " {$amt[$keys]}</td>\n\t\t\t\t</tr>";
        }
    }
    # 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);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------NEW----------------------
    $sub = 0.0;
    if (isset($amt)) {
        $sub = sprint(array_sum($amt));
    }
    $VATP = TAX_VAT;
    if ($inv['chrgvat'] == "exc") {
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //		$VAT = sprint(($subtotal - $taxex) * $VATP / 100);
        $VAT = sprint($vatamount);
        $SUBTOT = $sub;
        $TOTAL = sprint($subtotal + $VAT);
        $delexvat = sprint($delchrg);
    } elseif ($inv['chrgvat'] == "inc") {
        $ot = $taxex;
        $taxex = sprint($taxex - $taxex * $traddisc / 100);
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        //		$VAT = sprint(($subtotal - $taxex) * $VATP / (100 + $VATP));
        $VAT = sprint($vatamount);
        $SUBTOT = sprint($sub);
        $TOTAL = sprint($subtotal);
        $delexvat = sprint($delchrg);
        $traddiscmt = sprint($traddiscmt);
    } else {
        $subtotal = sprint($sub + $delchrg);
        $traddiscmt = sprint($subtotal * $traddisc / 100);
        $subtotal = sprint($subtotal - $traddiscmt);
        $VAT = sprint(0);
        $SUBTOT = $sub;
        $TOTAL = $subtotal;
        $delexvat = sprint($delchrg);
    }
    /* --- ----------- Clac --------------------- */
    ##----------------------END----------------------
    # Get invoice info
    db_conn($prd);
    $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 class='err'>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    /* A quick fix by jupiter
    	$allnoted = true;
    	foreach($qtys as $keys => $value){
    		# get selected stock in this invoice
    		$sql = "SELECT * FROM inv_items  WHERE id = '$ids[$keys]' AND invid ='$invid' AND div = '".USER_DIV."'";
    		$stkdRslt = db_exec($sql);
    		$stkd = pg_fetch_array($stkdRslt);
    		if($stkd['qty'] != $qtys[$keys]){
    			$allnoted = false;
    		}
    	}
    
    	if($allnoted){
    		$SUBTOT = sprint($inv['subtot']);
    		$VAT = sprint($inv['vat']);
    		$TOTAL = sprint($inv['total']);
    		$delchrg = sprint($inv['delivery']);
    		$traddiscmt = sprint($inv['discount']);
    		$SUBTOTAL = sprint($TOTAL - $VAT);
    	}
    /* End A quick fix by jupiter */
    if ($inv['balance'] >= $TOTAL) {
        $invpay = $TOTAL;
        $examt = 0;
    } else {
        $invpay = $inv['balance'];
        $examt = $TOTAL - $invpay;
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "no");
    /* - End Hooks - */
    # Todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*refnum*/
    # Insert invoice to period DB
    db_conn($inv['prd']);
    # Format date
    $odate = explode("-", $odate);
    $rodate = $odate[2] . "-" . $odate[1] . "-" . $odate[0];
    $td = $rodate;
    # Insert invoice credit note to DB
    $sql = "\n\t\tINSERT INTO inv_notes (\n\t\t\tdeptid, notenum, invnum, invid, cusnum, cordno, ordno, \n\t\t\tchrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, \n\t\t\ttotal, comm, username, div, surname, cusaddr, cusvatno, \n\t\t\tdeptname, prd\n\t\t) VALUES (\n\t\t\t'{$inv['deptid']}', '{$notenum}', '{$inv['invnum']}', '{$inv['invid']}', '{$inv['cusnum']}', '{$inv['cordno']}', '{$inv['ordno']}', \n\t\t\t'{$inv['chrgvat']}', '{$terms}', '{$traddiscmt}', '{$inv['salespn']}', '{$rodate}', '{$delexvat}', '{$SUBTOT}', '{$VAT}', \n\t\t\t'{$TOTAL}', '{$comm}', '" . USER_NAME . "', '" . USER_DIV . "', '{$inv['surname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', \n\t\t\t'{$inv['deptname']}', {$inv['prd']}\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice to Cubit.", SELF);
    # Get next ordnum
    $noteid = pglib_lastid("inv_notes", "noteid");
    # Begin updating
    #pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
    $nbal = $inv['nbal'] + $TOTAL;
    db_conn($prd);
    # Update the invoice (make balance less)
    $sql = "\n\t\tUPDATE invoices \n\t\tSET nbal = '{$nbal}', rdelchrg = (rdelchrg + '{$delchrg}'), balance = balance - '{$invpay}' \n\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    db_connect();
    # Update the invoice (make balance less)
    $sql = "UPDATE open_stmnt SET balance = balance-'{$TOTAL}' WHERE invid = '{$inv['invnum']}'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Update the customer (make balance less)
    $sql = "UPDATE customers SET balance = (balance - '{$TOTAL}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Update invoice's discounts
    # $sql = "UPDATE inv_discs SET traddisc = (traddisc - '$traddiscm'), itemdisc = (itemdisc - '$discs') WHERE cusnum = '$inv[cusnum]' AND invid = '$invid'";
    # $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.",SELF);
    # record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt (\n\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\ttype, div, allocation_date\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$notenum}', '" . ($TOTAL - $TOTAL * 2) . "', '{$rodate}', \n\t\t\t\t'Credit Note for invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$rodate}'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    $disc = 0;
    # Commit updating
    #pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    $nsp = 0;
    # Make ledge record
    custledger($inv['cusnum'], $dept['incacc'], $sdate, $notenum, "Credit Note No. {$notenum} for invoice No. {$inv['invnum']}", $TOTAL, "c");
    if ($examt > 0) {
        # Make record for age analisys
        custCTP($examt, $inv['cusnum']);
    }
    foreach ($qtys as $keys => $value) {
        db_connect();
        # 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);
        db_conn($prd);
        # get selected stock in this invoice
        $sql = "SELECT * FROM inv_items  WHERE id='{$ids[$keys]}' AND invid='{$invid}' AND div='" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        if ($stkd['account'] == 0) {
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            db_connect();
            $Sl = "SELECT * FROM scr WHERE inv='{$inv['invnum']}' AND stkid='{$stkd['stkid']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) > 0) {
                $cd = pg_fetch_array($Ri);
                $stk['csprice'] = $cd['amount'];
            } else {
                $stk['csprice'] = 0;
            }
            # cost amount
            $cosamt = round($qtys[$keys] * $stk['csprice'], 2);
            db_connect();
            # Update stock(onhand + qty)
            $sql = "UPDATE stock SET csamt = (csamt + '{$cosamt}'), units = (units + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            db_connect();
            # fix stock cost amount
            $Sl = "UPDATE stock set csprice=csamt/units WHERE stkid = '{$stkids[$keys]}' AND units>0";
            $Ri = db_exec($Sl) or errDie("Unable to update stock cost price in Cubit.", SELF);
            if ($stk['serd'] == 'yes') {
                ext_InSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $notenum, 'note', $rodate);
            }
            # negetive values to minus profit
            $nqty = $qtys[$keys] * 1;
            $namt = $amt[$keys] * -1;
            $ncsprice = $cosamt * -1;
            $noted = $stkd['noted'] + $qtys[$keys];
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            stockrec($stkd['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $td, $nqty, $cosamt, "Credit note for Customer : {$inv['surname']} - Credit note No. {$notenum}");
            # Get amount exluding vat if including and not exempted
            $VATP = TAX_VAT;
            $amtexvat = $amt[$keys];
            ###################VAT CALCS#######################
            db_connect();
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "VAT for Credit note: {$notenum} Customer : {$inv['cusname']} {$inv['surname']}", -$iamount, -$ivat);
            ####################################################
            db_connect();
            $sql = "\n\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, \n\t\t\t\t\tcsamt, details, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$td}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'note', '{$qtys[$keys]}', '{$amtexvat}', \n\t\t\t\t\t'{$cosamt}', 'Credit note for Customer : {$inv['surname']} - Credit note No. {$notenum}', '" . USER_DIV . "'\n\t\t\t\t)";
            $recRslt = db_exec($sql);
            db_conn($inv['prd']);
            # Get selected stock in this invoice
            $sql = "UPDATE inv_items SET noted = '{$noted}' WHERE id = '{$ids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
            $stkdsRslt = db_exec($sql);
            $stkds = pg_fetch_array($stkdsRslt);
            # get accounts
            db_conn("exten");
            $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $stockacc = $wh['stkacc'];
            $cosacc = $wh['cosacc'];
            # sales rep commission
            # coms($inv['salespn'], $amt[$keys], $stk['com'], 'anything');
            //$commision=$commision+coms($inv['salespn'], $stkd['amt'], $stk['com']);
            # dt(stock) ct(cos)
            writetrans($stockacc, $cosacc, $td, $refnum, $cosamt, "Cost Of Sales for Credit note No. {$notenum} for Customer : {$inv['cusname']} {$inv['surname']}");
            db_conn($inv['prd']);
            # insert invoice items
            $sql = "\n\t\t\t\tINSERT INTO inv_note_items (\n\t\t\t\t\tnoteid, whid, stkid, qty, amt, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$noteid}', '{$stkd['whid']}', '{$stkids[$keys]}', '{$qtys[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            db_connect();
            $sql = "\n\t\t\t\tINSERT INTO salesrec (\n\t\t\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$rodate}', '{$noteid}', '{$notenum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'nstk', '" . USER_DIV . "'\n\t\t\t\t)";
            $recRslt = db_exec($sql);
        } else {
            # Keep track of discounts
            //$disc += ($stkd['disc'] * $stkd['qty']);
            # negetive values to minus profit
            $nqty = $qtys[$keys] * 1;
            $namt = $amt[$keys] * -1;
            //$ncsprice = ($cosamt * (-1));
            $noted = $stkd['noted'] + $qtys[$keys];
            # Get amount exluding vat if including and not exempted
            $VATP = TAX_VAT;
            $amtexvat = $amt[$keys];
            ###################VAT CALCS#######################
            db_connect();
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['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 ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($amt[$keys], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "VAT for Credit note: {$notenum} Customer : {$inv['cusname']} {$inv['surname']}", -$iamount, -$ivat);
            ####################################################
            db_conn($inv['prd']);
            # Get selected stock in this invoice
            $sql = "UPDATE inv_items SET noted = '{$noted}' WHERE id = '{$ids[$keys]}' AND invid ='{$invid}' AND div = '" . USER_DIV . "'";
            $stkdsRslt = db_exec($sql);
            $stkds = pg_fetch_array($stkdsRslt);
            $nsp += sprint($iamount - $ivat);
            //writetrans($cosacc, $stockacc,$inv['odate'] , $refnum, $cosamt, "Cost Of Sales for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
            writetrans($stkd['account'], $dept['debtacc'], $td, $refnum, $iamount - $ivat, "Debtors control for Credit note: {$notenum}");
            //# dt(stock) ct(cos)
            //	writetrans($stockacc, $cosacc, $td, $refnum, $cosamt, "Cost Of Sales for Credit note No. $notenum for Customer : $inv[cusname] $inv[surname]");
            db_conn($inv['prd']);
            # insert invoice items
            $sql = "\n\t\t\t\tINSERT INTO inv_note_items (\n\t\t\t\t\tnoteid, whid, stkid, qty, amt, div, description\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$noteid}', '{$stkd['account']}', '0', '{$qtys[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "', '{$stkd['description']}'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
            db_connect();
            $sql = "\n\t\t\t\tINSERT INTO salesrec (\n\t\t\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$rodate}', '{$noteid}', '{$notenum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'nnon', '" . USER_DIV . "'\n\t\t\t\t)";
            $recRslt = db_exec($sql);
        }
    }
    db_connect();
    # save invoice discount
    $sql = "\n\t\tINSERT INTO inv_discs (\n\t\t\tcusnum, invid, traddisc, itemdisc, inv_date, delchrg, div\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$invid}', '0', '-{$disc}', '{$inv['odate']}', '0', '" . USER_DIV . "'\n\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    ###################VAT CALCS#######################
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    $excluding = "";
    $vr = vatcalc($delexvat, $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    vatr($vd['id'], $sdate, "OUTPUT", $vd['code'], $refnum, "Vat for Credit note No. {$notenum}, Customer : {$inv['cusname']} {$inv['surname']}", -$iamount, -$ivat);
    ####################################################
    /* - Start Transactoins - */
    if ($TOTAL - $VAT - $nsp > 0) {
        # dt(income) ct(debtors)
        writetrans($dept['incacc'], $dept['debtacc'], $date, $refnum, $TOTAL - $VAT - $nsp, "Debtors Control for Credit note No. {$notenum} for Customer : {$inv['cusname']} {$inv['surname']}");
    }
    # dt(vat) ct(debtors)
    writetrans($vatacc, $dept['debtacc'], $date, $refnum, $VAT, "Vat Return for Credit note No. {$notenum} for Customer : {$inv['cusname']} {$inv['surname']}");
    db_connect();
    //	$sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)
    //	VALUES('$rodate', '$noteid', '$notenum', '$dept[debtacc]', '$VAT', '$TOTAL', 'nstk', '".USER_DIV."')";
    //	$recRslt = db_exec($sql);
    $Sl = "\n\t\tINSERT INTO sj (\n\t\t\tcid, name, des, date, \n\t\t\texl, vat, inc, div\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$inv['surname']}', 'Credit Note:{$notenum}, Invoice {$inv['invnum']}', '{$rodate}', \n\t\t\t'" . -sprint($TOTAL - $VAT) . "', '-{$VAT}', '" . sprint(-$TOTAL) . "', '" . USER_DIV . "'\n\t\t)";
    $Ri = db_exec($Sl);
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* - End Transactoins - */
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    /* -- Final Layout -- */
    $details = "\n\t\t<center>\n\t\t<h2>Credit Note</h2>\n\t\t<table cellpadding='0' cellspacing='4' border='0' width='750'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top' width='30%'>\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>{$inv['surname']}</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<td>" . nl2br($inv['cusaddr']) . "</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<td>(Vat No. {$inv['cusvatno']})</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' width='25%'>\n\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t</td>\n\t\t\t\t<td width='20%'><img src='compinfo/getimg.php' width='230' height='47'></td>\n\t\t\t\t<td valign='bottom' align='right' width='25%'>\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Credit Note No.</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$notenum}</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<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['invnum']}</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<td><b>Order No.</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['ordno']}</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<td><b>Terms</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$terms} Days</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<td><b>Credit note Date</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$rodate}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='4'>\n\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='100%' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t\t\t\t<th width='45%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t<th>QTY RETURNED</th>\n\t\t\t\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t{$products}\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<table border='1' cellspacing='0' bordercolor='#000000'>\n\t\t\t\t\t\t<tr><td>" . nl2br($comm) . "</td></tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td align='right' colspan='3'>\n\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width=50% bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$SUBTOT}</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<td><b>Trade Discount</b></td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$traddiscmt}</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<td><b>Delivery Charge</b></td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$delexvat}</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<td><b>VAT {$vat14}</b></td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$VAT}</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><b>GRAND TOTAL<b></th>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<table " . TMPL_tblDflts . " border='1'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>VAT No.</th>\n\t\t\t\t\t\t\t<td align='center'>" . COMP_VATNO . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td><br></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</center>";
    //$OUTPUT = "<script>printer('invoice-note-reprint.php?noteid=$noteid&prd=$inv[prd]&cccc=yes');move('index-sales.php');</script>";
    header("Location: invoice-note-reprint.php?noteid={$noteid}&prd={$inv['prd']}&cccc=yes");
    exit;
    require "tmpl-print.php";
}