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";
}
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";
}