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);
    # 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 number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $ddate = $d_year . "-" . $d_month . "-" . $d_day;
    if (!checkdate($d_month, $d_day, $d_year)) {
        $v->isOk($ddate, "num", 1, 1, "Invalid Date.");
    }
    # 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", 0, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($cunitcost[$keys], "float", 0, 20, "Invalid Foreign currency Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($duty[$keys], "float", 0, 20, "Invalid Duty Charges for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($dutyp[$keys], "float", 0, 20, "Invalid Duty Charges Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qtys[$keys] < 1) {
                $v->isOk($qtys[$keys], "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
            if ($qtys[$keys] > $qts[$keys]) {
                $v->isOk($qtys[$keys], "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.");
            # Nasty Zeros
            $unitcost[$keys] += 0;
            $cunitcost[$keys] += 0;
            $duty[$keys] += 0;
            $dutyp[$keys] += 0;
        }
        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>";
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    //print $td; exit;
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $TD = $pur["pdate"];
    # 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>";
    }
    # check if Order 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");
    $sup = pg_fetch_array($supRslt);
    # get department
    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);
    }
    # Insert Order to DB
    db_connect();
    # 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;
    foreach ($recvd as $sk => $keys) {
        if ($qtys[$keys] < 1) {
            continue;
        }
        /* -- Calculations -- */
        # Calculate cost amount bought
        $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        $amt[$keys] += $duty[$keys] * $pur['xrate'];
        # Calculate percentage from subtotal
        $perc[$keys] = $amt[$keys] / ($pur['subtot'] * $pur['xrate']) * 100;
        # Get percentage from shipping charges
        $shipchrg[$keys] = $perc[$keys] / 100 * ($pur['shipchrg'] * $pur['xrate']);
        # add shipping charges to amt
        $amt[$keys] = round($amt[$keys] + $shipchrg[$keys], 2);
        $resub += $amt[$keys];
        /* -- End Calculations --*/
        # 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;
        }
        # Update Order items
        $sql = "UPDATE purint_items SET rqty = (rqty + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        # update stock(ordered + qty, units + qty, csamt + (csamt + amt))
        $sql = "UPDATE stock SET ordered = (ordered - '{$qtys[$keys]}'), units = (units + '{$qtys[$keys]}' +'{$min_stock}'), csamt = (csamt + '{$amt[$keys]}') WHERE 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], $sup['supname'], $pur['purnum'], "pur", $TD);
            $serial = $sers[$stkids[$keys]][$keys];
            db_connect();
            $sql = "INSERT INTO pserec(purid, purnum, stkid, serno, div)\n\t\t\t\tVALUES('{$purid}', '{$pur['purnum']}', '{$stkids[$keys]}', '{$serial}', '" . USER_DIV . "')";
            $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 = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\tVALUES('{$TD}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'purchase', '{$qtys[$keys]}', '{$amt[$keys]}', '{$cspric}', 'Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}', '" . USER_DIV . "')";
        $recRslt = db_exec($sql);
        # keep records for transactions
        if (isset($totstkamt[$stk['whid']])) {
            $totstkamt[$stk['whid']] += $amt[$keys];
        } else {
            $totstkamt[$stk['whid']] = $amt[$keys];
        }
        # Just wanted to fix the xxx.xxxxxxe-x value
        # $csprice = round(($stk['csamt']/$stk['units']), 2);
        if ($stk['units'] > 0) {
            $csprice = round($stk['csamt'] / $stk['units'], 2);
        } else {
            $csprice = round($stk['csprice'], 2);
        }
        # update stock(csprice = (csamt/units))
        $sql = "UPDATE stock SET csprice = '{$csprice}', lcsprice = '{$cspric}' WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        # check if there are any outstanding items
        $sql = "SELECT * FROM purint_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        # if none the set to received
        if (pg_numrows($stkdRslt) < 1) {
            # update surch_int(received = 'y')
            $sql = "UPDATE purch_int SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF);
        }
    }
    if ($min_stock > 0) {
        $cost = sprint($unitcost[$keys] * $min_stock);
        $td = "{$d_year}-{$d_month}-{$d_day}";
        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 international purchase {$pur['purnum']}");
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, 0, $cost, "Cost Of Sales for stock sold before international purchase {$pur['purnum']}");
        db_connect();
        $Sl = "INSERT INTO pcost(purnum,cost,qty,rqty,stkid) VALUES ('{$pur['purnum']}','{$unitcost[$keys]}','{$min_stock}','0','{$stk['stkid']}')";
        $Ri = db_exec($Sl);
    }
    if (strlen($refno) > 0) {
        if (strlen($pur['refno']) > 0) {
            $refno = "{$pur['refno']}-{$refno}";
        } else {
            $refno = $refno;
        }
    } else {
        $refno = $pur['refno'];
    }
    # Update Order on the DB
    $fresub = sprint($resub / $pur['xrate']);
    $sql = "UPDATE purch_int SET rsubtot = (rsubtot + '{$fresub}'), rlsubtot = (rlsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', ddate = '{$ddate}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    /* --- Transactions --- */
    db_conn(PRD_DB);
    $refnum = getrefnum();
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - 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);
        $wh = pg_fetch_array($whRslt);
        # Debit Stock and Credit Suppliers control
        writetrans($wh['stkacc'], $wh['conacc'], $TD, $refnum, $wamt, "International Stock Order No. {$pur['purnum']} Received 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 Order info
    db_connect();
    $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y" && $pur['invcd'] == 'y') {
        # Copy Order
        db_conn($pur['prd']);
        $sql = "INSERT INTO purch_int(purid, deptid, supid, supaddr, terms, pdate, ddate, xrate, fcid, curr, tax, shipchrg, fshipchrg, duty, subtot, total, balance, fbalance, remarks, refno, received, done, div, purnum)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['xrate']}', '{$pur['fcid']}', '{$pur['curr']}', '{$pur['tax']}', '{$pur['shipchrg']}', '{$pur['fshipchrg']}', '{$pur['duty']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['fbalance']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
        /*-- Cost varience -- */
        $nsubtot = sprint($pur['total'] - $pur['tax']);
        $nsubtot = sprint($nsubtot * $pur['xrate']);
        if ($pur['rlsubtot'] > $nsubtot) {
            $diff = sprint($pur['rlsubtot'] - $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['rlsubtot']) {
            $diff = sprint($nsubtot - $pur['rlsubtot']);
            # 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 purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert Order items
            db_conn($pur['prd']);
            $sql = "INSERT INTO purint_items(purid, whid, stkid, qty, unitcost, cunitcost, duty, dutyp, amt, ddate, recved, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['cunitcost']}', '{$stktc['duty']}', '{$stktc['dutyp']}', '{$stktc['amt']}', '{$stktc['ddate']}', 'y', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        db_connect();
        # Remove the Order from running DB
        $sql = "DELETE FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Record where Order is
        $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('int', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
        $movRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Remove those Order items from running DB
        $sql = "DELETE FROM purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    }
    /* End moving Order received */
    // Final Layout
    $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>International Order received</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Order receipt from Supplier <b>{$sup['supname']}</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='purch-int-view.php'>View International 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);
    # 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], "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qtys[$keys] < 1) {
                $v->isOk("#", "num", 0, 0, "Error : Item Quantity must be at least one. 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.");
    }
    /* check quantities
    	if(isset($qtys)){
    		foreach($qtys as $keys => $qty){
    			$v->isOk ($qty, "num", 1, 10, "Invalid Quantity for product number : <b>".($keys+1)."</b>");
    			$v->isOk ($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>".($keys+1)."</b>.");
    			if($qty > $qts[$keys]){
    				$v->isOk ($qty, "num", 0, 0, "Error : Item Quantity returned is more than the bought quantity : <b>".($keys+1)."</b>");
    			}
    		}
    	}
    
    	# check stkids
    	if(isset($stkids)){
    		foreach($stkids as $keys => $stkid){
    			$v->isOk ($stkid, "num", 1, 10, "Invalid Stock number, 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 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);
    # 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 department info
    db_conn("exten");
    $sql = "SELECT deptname 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);
    }
    core_connect();
    # Get Petty cash account
    $cashacc = gethook("accnum", "bankacc", "name", "Petty Cash");
    # Insert purchase to DB
    db_connect();
    # Begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # amount of stock in
    $totstkamt = array();
    $resub = 0;
    $taxex = 0;
    $revat = 0;
    # Get subtotal
    foreach ($recvd as $sk => $keys) {
        # Skip zeros
        if ($qtys[$keys] < 1) {
            continue;
        }
        $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
    }
    $SUBTOTAL = array_sum($amt);
    foreach ($recvd as $sk => $keys) {
        # Skip zeros
        if ($qtys[$keys] < 1) {
            continue;
        }
        # 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 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);
        # Calculate cost amount bought
        $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        /* delivery charge */
        # Calculate percentage from subtotal
        $perc[$keys] = $amt[$keys] / $SUBTOTAL * 100;
        # Get percentage from shipping charges
        $shipc[$keys] = $perc[$keys] / 100 * $shipchrg;
        # Add delivery charges
        $amt[$keys] += $shipc[$keys];
        /* end delivery charge */
        # the subtotal + delivery charges
        $resub += $amt[$keys];
        # Check Tax Excempt
        if ($stk['exvat'] == 'yes') {
            # how much is not vatable?
            $taxex += $amt[$keys];
        } else {
            # Line vat
            $svat[$keys] = svat($amt[$keys], $stkd['amt'], $stkd['svat']);
            # received vat
            $revat += $svat[$keys];
            # make amount vat free
            if ($pur['vatinc'] == "yes") {
                $amt[$keys] = $amt[$keys] - $svat[$keys];
            }
        }
        # Update purchase items
        $sql = "UPDATE pur_items SET rqty = (rqty + '{$qtys[$keys]}'), ddate = '{$ddate[$keys]}' WHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        # Update stock(ordered + qty, units + qty, csamt + (csamt + amt))
        $sql = "UPDATE stock SET ordered = (ordered - '{$qtys[$keys]}'), units = (units + '{$qtys[$keys]}'), csamt = (csamt + '{$amt[$keys]}') WHERE 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", $pur['pdate']);
            $serial = $sers[$stkids[$keys]][$keys];
            db_connect();
            $sql = "INSERT INTO pserec(purid, purnum, stkid, serno, div)\n\t\t\t\tVALUES('{$purid}', '{$pur['purnum']}', '{$stkids[$keys]}', '{$serial}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to update stock serials in Cubit.", SELF);
        }
        # Keep records for transactions
        if (isset($totstkamt[$stk['whid']])) {
            $totstkamt[$stk['whid']] += $amt[$keys];
        } else {
            $totstkamt[$stk['whid']] = $amt[$keys];
        }
        # 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', $sdate, $qtys[$keys], $amt[$keys], "Stock Received from Supplier : {$pur['supname']} - Order No. {$pur['purnum']}");
        db_connect();
        $cspric = sprint($amt[$keys] / $qtys[$keys]);
        $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\tVALUES('{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'purchase', '{$qtys[$keys]}', '{$amt[$keys]}', '{$cspric}', 'Stock Received from Supplier : {$pur['supname']} - Order No. {$pur['purnum']}', '" . USER_DIV . "')";
        $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 = "UPDATE stock SET csprice = '{$csprice}', lcsprice = '{$cspric}' WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        # 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 (strlen($refno) > 0) {
        if (strlen($pur['refno']) > 0) {
            $refno = "{$pur['refno']}-{$refno}";
        } else {
            $refno = $refno;
        }
    } else {
        $refno = $pur['refno'];
    }
    # Update purchase on the DB
    if ($pur['part'] == 'y') {
        $sql = "UPDATE purchases SET shipchrg = (shipchrg + '{$shipchrg}'), refno = '{$refno}', remarks = '{$remarks}', edit = 1 WHERE purid = '{$purid}'";
    } else {
        $sql = "UPDATE purchases SET shipchrg = '{$shipchrg}', part = 'y', refno = '{$refno}', remarks = '{$remarks}', edit = 1 WHERE purid = '{$purid}'";
    }
    $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    /* Transactions */
    $refnum = getrefnum(date("d-m-Y"));
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    $tpp = 0;
    # Record transaction  from data
    foreach ($totstkamt as $whid => $wamt) {
        # Get whouse info
        db_conn("exten");
        $sql = "SELECT stkacc FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # Debit Stock and Petty Cash acc
        writetrans($wh['stkacc'], $cashacc, date("d-m-Y"), $refnum, $wamt, "Stock Received for Purchase No. {$pur['purid']} from Supplier : {$pur['supname']}.");
    }
    # Calc Vat amount on (subtot + delchrg)
    # $vatamt = vat(($resub - $taxex), $pur['vatinc']);
    $vatamt = $revat;
    # Add vat if not included
    if ($pur['vatinc'] == 'no') {
        $retot = $resub + $vatamt;
    } else {
        $retot = $resub;
    }
    # Transfer vat
    writetrans($vatacc, $cashacc, date("d-m-Y"), $refnum, $vatamt, "Vat Paid for Purchase No. {$pur['purid']} from Supplier : {$pur['supname']}.");
    db_connect();
    # Record tranfer for patty cash report
    $sdate = date("Y-m-d");
    $sql = "INSERT INTO pettyrec(date, type, det, amount, name, div) VALUES ('{$sdate}', 'Req', 'Cash Payment for Stock Received on Purchase No. {$pur['purid']} from Supplier : {$pur['supname']}.', '-{$retot}', 'Petty Cash Purchase', '" . USER_DIV . "')";
    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    /* Start moving if purchase received */
    # 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") {
        # copy purchase
        db_conn($pur['prd']);
        $sql = "INSERT INTO purchases(purid, deptid, supid, supname, supaddr, supno, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, remarks, refno, received, done, div, purnum)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
        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 = "INSERT INTO pur_items(purid, whid, stkid, qty, rqty, unitcost, amt, ddate, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['ddate']}', '" . USER_DIV . "')";
            $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 Order 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 Order 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 Order information in Cubit.", SELF);
    }
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving purchase received */
    // Final Layout
    $write = "\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Order received</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Order receipt from Supplier <b>{$pur['supname']}</b> has been recorded.</td>\n\t\t</tr>\n\t</table>\n\t<p>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='purchase-view.php'>View Orders</a></td>\n\t\t</tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    if (isset($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()
{
    # 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);
    # 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 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";
}