function details($_GET)
{
    $showvat = TRUE;
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $td = $inv['odate'];
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($td) >= strtotime($blocked_date_from) and strtotime($td) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    $sql = "SELECT stkid FROM inv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
    $crslt = db_exec($sql);
    if (pg_numrows($crslt) < 1) {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has no items.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # check if invoice has been serialised
    if ($inv['serd'] == "n") {
        $error = "<li class='err'> Error : You must select serial numbers for some Items on Invoice No. <b>T {$invid}</b> before you can print it.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    cus_xrate_update($inv['fcid'], $inv['xrate']);
    # Begin Updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $invnum = divlastid('inv', USER_DIV);
    $Sl = "INSERT INTO ncsrec (oldnum, newnum, div) VALUES ('{$invid}', '{$invnum}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert into db");
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    /* --- Start Products Display --- */
    # Products layout
    $commision = 0;
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $taxex = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # get warehouse name
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # get selected stock in this warehouse
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        $sp = "";
        # Check Tax Excempt
        if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
            $taxex += $stkd['amt'];
            $ex = "#";
        } else {
            $ex = "";
        }
        # all must be excempted
        if ($inv['chrgvat'] == 'nov') {
            $ex = "#";
        }
        # Keep track of discounts
        $disc += $stkd['disc'] * $stkd['qty'];
        # Insert stock record
        $sdate = date("Y-m-d");
        $csprice = sprint($stk['csprice'] * $stkd['qty']);
        # Get amount exluding vat if including and not exempted
        $VATP = TAX_VAT;
        $amtexvat = sprint($stkd['famt']);
        if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes') {
            $amtexvat = sprint($stkd['famt'] * 100 / (100 + $VATP));
        }
        db_connect();
        $sql = "\n\t\t\tINSERT INTO stockrec (\n\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, \n\t\t\t\tdetails, div\n\t\t\t) VALUES (\n\t\t\t\t'{$td}', '{$stkd['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'invoice', '{$stkd['qty']}', '{$amtexvat}', '{$csprice}', \n\t\t\t\t'Stock sold - Invoice No. {$invnum}', '" . USER_DIV . "'\n\t\t\t)";
        $recRslt = db_exec($sql);
        # Sales rep commission
        $commision = $commision + coms($inv['salespn'], $stkd['amt'], $stk['com']);
        # Put in product
        $products .= "\n\t\t\t<tr valign='top'>\n\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t<td>{$ex} {$sp} {$stk['stkdes']}</td>\n\t\t\t\t<td>" . sprint3($stkd['qty']) . "</td>\n\t\t\t\t<td>{$inv['currency']} " . sprint($stkd['unitcost']) . "</td>\n\t\t\t\t<td>{$inv['currency']} {$stkd['disc']}</td>\n\t\t\t\t<td>{$inv['currency']} {$stkd['amt']}</td>\n\t\t\t</tr>";
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOTAL = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    $FSUBTOT = sprint($inv['subtot'] * $inv['xrate']);
    $FVAT = sprint($inv['vat'] * $inv['xrate']);
    $FTOTAL = sprint($inv['total'] * $inv['xrate']);
    $fdelchrg = sprint($inv['delchrg'] * $inv['xrate']);
    $ftraddiscm = sprint($inv['discount'] * $inv['xrate']);
    com_invoice($inv['salespn'], $FTOTAL, $commision * $inv['xrate'], $invnum, $td);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "int");
    /* - End Hooks - */
    # Todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*$refnum*/
    /* --- Updates ---- */
    db_connect();
    $Sql = "UPDATE invoices SET printed ='y', done ='y', invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
    # Record the payment on the statement
    $sql = "\n\t\tINSERT INTO stmnt (\n\t\t\tcusnum, invid, amount, date, type, div, allocation_date\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}','{$invnum}', '{$TOTAL}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Record the payment on the statement
    $sql = "\n\t\tINSERT INTO open_stmnt (\n\t\t\tcusnum, invid, amount, balance, date, type, div\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$TOTAL}', '{$TOTAL}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "'\n\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Save invoice discount
    $sql = "\n\t\tINSERT INTO inv_discs (\n\t\t\tcusnum, invid, traddisc, itemdisc, inv_date, delchrg, div, \n\t\t\ttotal\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$ftraddiscm}', '{$disc}', '{$inv['odate']}', '{$fdelchrg}', '" . USER_DIV . "', \n\t\t\t({$FSUBTOT}+{$fdelchrg})\n\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$FTOTAL}'), fbalance = (fbalance + '{$TOTAL}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Make ledge record
    custledger($inv['cusnum'], $dept['incacc'], $td, $invnum, "Invoice No. {$invnum}", $FTOTAL, "d");
    db_connect();
    # get selected stock in this invoice
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        db_connect();
        # get selamt from selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        # cost amount
        $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
        # update stock(alloc - qty)
        $sql = "UPDATE stock SET csamt = (csamt - '{$cosamt}'),units = (units - '{$stkd['qty']}'),alloc = (alloc - '{$stkd['qty']}')  WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        ###################VAT CALCS#######################
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        $iamount = $iamount * $inv['xrate'];
        $ivat = $ivat * $inv['xrate'];
        vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
        ####################################################
        if ($stk['serd'] == 'yes') {
            ext_invSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $invnum);
        }
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        $sdate = date("Y-m-d");
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, $stkd['qty'], $cosamt, "Sold to Customer : {$inv['surname']} - Invoice No. {$invnum}");
        # get accounts
        db_conn("exten");
        $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        $stockacc = $wh['stkacc'];
        $cosacc = $wh['cosacc'];
        # dt(cos) ct(stock)
        writetrans($cosacc, $stockacc, $td, $refnum, $cosamt, "Cost Of Sales for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
        $tcosamt += $cosamt;
    }
    ###################VAT CALCS#######################
    $inv['delvat'] += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    $vr = vatcalc($inv['delchrg'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    $iamount = $iamount * $inv['xrate'];
    $ivat = $ivat * $inv['xrate'];
    vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
    ####################################################
    /* - Start Transactoins - */
    # dt(debtors) ct(income/sales)
    writetrans($dept['debtacc'], $dept['incacc'], $td, $refnum, $FTOTAL - $FVAT, "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    # dt(debtors) ct(vat account)
    writetrans($dept['debtacc'], $vatacc, $td, $refnum, $FVAT, "VAT Received on Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    db_connect();
    $sql = "\n\t\tINSERT INTO salesrec (\n\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t) VALUES (\n\t\t\t'{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$FVAT}', '{$FTOTAL}', 'stk', '" . USER_DIV . "'\n\t\t)";
    $recRslt = db_exec($sql);
    db_conn('cubit');
    $Sl = "\n\t\tINSERT INTO sj (\n\t\t\tcid, name, des, date, exl, vat, inc, div\n\t\t) VALUES (\n\t\t\t'{$inv['cusnum']}', '{$inv['surname']}', 'International Invoice {$invnum}', '{$inv['odate']}', '" . sprint($FTOTAL - $FVAT) . "', \n\t\t\t'{$FVAT}', '" . sprint($FTOTAL) . "', '" . USER_DIV . "'\n\t\t)";
    $Ri = db_exec($Sl);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* - End Transactoins - */
    # vat explanation
    if ($inv['chrgvat'] == 'nov') {
        $expl = "VAT Exempt indicator";
    } else {
        $expl = "0% VAT indicator";
        $expl = "VAT Exempt indicator";
    }
    # Avoid little box, <table border=1> <-- ehhhemm !!
    if (strlen($inv['comm']) > 0) {
        $inv['comm'] = "\n\t\t\t<table border='1' cellspacing='0' bordercolor='#000000'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>" . nl2br($inv['comm']) . "</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    $cc = "<script> sCostCenter('dt', 'Sales', '{$inv['odate']}', 'Invoice No.{$invnum} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($FTOTAL - $FVAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', ''); </script>";
    /* -- Final Layout -- */
    $details = "\n\t\t<center>\n\t\t{$cc}\n\t\t<h2>Tax Invoice</h2>\n\t\t<table cellpadding='0' cellspacing='4' border='0' width='750'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>{$inv['surname']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>" . nl2br($inv['cusaddr']) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>(VAT No. {$inv['cusvatno']})</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t" . COMP_PADDR . "<br>\n\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\tReg No. " . COMP_REGNO . "<br>\n\t\t\t\t\tVAT No. " . COMP_VATNO . "<br>\n\t\t\t\t</td>\n\t\t\t\t<td width='20%'>\n\t\t\t\t\t<img src='compinfo/getimg.php' width='230' height='47'>\n\t\t\t\t</td>\n\t\t\t\t<td valign='bottom' align='right' width='20%'>\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$invnum}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Proforma Inv No.</b></td>\n\t\t\t\t\t\t\t<td>{$inv['docref']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Order No.</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['ordno']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Terms</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['terms']} Days</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Invoice Date</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['odate']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>VAT</b></td>\n\t\t\t\t\t\t\t<td valign='center'>{$inv['chrgvat']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='4'>\n\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='100%' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>ITEM NUMBER</b></td>\n\t\t\t\t\t\t\t<td width='45%'><b>DESCRIPTION</b></td>\n\t\t\t\t\t\t\t<td><b>QTY</b></td>\n\t\t\t\t\t\t\t<td><b>UNIT PRICE</b></td>\n\t\t\t\t\t\t\t<td><b>DISCOUNT</b></td>\n\t\t\t\t\t\t\t<td><b>AMOUNT</b></td>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t{$products}\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>{$inv['comm']}</td>\n\t\t\t\t<td>" . BNK_BANKDET . "</td>\n\t\t\t\t<td align='right' colspan='2'>\n\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='50%' bordercolor='#000000'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$SUBTOT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Trade Discount</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$inv['discount']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Delivery Charge</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$inv['delivery']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>VAT {$vat14}</b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$VAT}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>GRAND TOTAL<b></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'>{$expl} = #</td>\n\t\t\t\t\t\t</tr>\n\t\t\t        </table>\n\t\t\t\t</td>\n\t\t\t\t<td><br></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</center>";
    $OUTPUT = $details;
    require "tmpl-print.php";
}
function write($_POST)
{
    # Get stock vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($stkid, "num", 1, 50, "Invalid stock number.");
    $v->isOk($sdiv, "num", 1, 50, "Invalid branch number.");
    $v->isOk($whid, "num", 1, 50, "Invalid warehouse number.");
    $v->isOk($tunits, "num", 1, 50, "Invalid number of units.");
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        if (!ext_isUnique(ext_remBlnk($sernos))) {
            $v->isOk("##", "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li>";
        }
        return $confirm;
    }
    # Select Stock
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.</li>";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    db_conn("exten");
    # get warehouse
    $sql = "SELECT * FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # get warehouse
    $sql = "SELECT * FROM warehouses WHERE whid = '{$whid}' AND div = '{$sdiv}'";
    $swhRslt = db_exec($sql);
    $swh = pg_fetch_array($swhRslt);
    /* Start Stock transfering */
    db_connect();
    $csamt = $tunits * $stk['csprice'];
    # Reduce on the other hand
    $sql = "UPDATE stock SET units = (units - '{$tunits}'), csamt = (csamt - '{$csamt}') WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update stock in Cubit.", SELF);
    # Insert ithe stock into transit
    $sql = "INSERT INTO transit (trandate, stkid, sdiv, swhid, tunits, cstamt, div) VALUES (now(), '{$stkid}', '{$sdiv}', '{$whid}', '{$tunits}', '{$csamt}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to insert stock into transit.", SELF);
    $tid = pglib_lastid("transit", "id");
    if (isset($sernos)) {
        foreach ($sernos as $skey => $serno) {
            # Insert the stock serial into transit serials
            $sql = "INSERT INTO transerial (tid, stkid, serno) VALUES ('{$tid}', '{$stkid}', '{$serno}')";
            $rslt = db_exec($sql) or errDie("Unable to insert stock into transit.", SELF);
            ext_invSer($serno, $stkid);
        }
    }
    # todays date
    $date = date("d-m-Y");
    $refnum = getrefnum($date);
    # dt(conacc) ct(stkacc)
    # writetrans($wh['conacc'], $wh['stkacc'], $date, $refnum, $csamt, "Stock Transfer", USER_DIV);
    /* End Stock transfering */
    db_connect();
    # Original Branch
    $sql = "SELECT * FROM branches WHERE div = '{$stk['div']}'";
    $branRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($branRslt) < 1) {
        return "<li> Invalid Branch ID.</li>";
    } else {
        $bran = pg_fetch_array($branRslt);
    }
    # Selected Branch
    $sql = "SELECT * FROM branches WHERE div = '{$sdiv}'";
    $sbranRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($sbranRslt) < 1) {
        return "<li> Invalid Branch ID.</li>";
    } else {
        $sbran = pg_fetch_array($sbranRslt);
    }
    # Select Stock
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    # Available stock units
    $avstk = $stk['units'] - $stk['alloc'];
    # Return
    $write = "\n\t\t<h3>Stock has been taken to transit</h3>\n\t\t<table " . TMPL_tblDflts . " width='350'>\n\t\t\t<tr>\n\t\t\t\t<th width='40%'>Field</th>\n\t\t\t\t<th width='60%'>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Branch</td>\n\t\t\t\t<td>{$bran['branname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Warehouse</td>\n\t\t\t\t<td>{$wh['whname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Category</td>\n\t\t\t\t<td>{$stk['catname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock code</td>\n\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock description</td>\n\t\t\t\t<td>" . nl2br($stk['stkdes']) . "</pre></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>On Hand</td>\n\t\t\t\t<td>{$stk['units']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Allocated</td>\n\t\t\t\t<td>{$stk['alloc']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Available</td>\n\t\t\t\t<td>{$avstk}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>On Order</td>\n\t\t\t\t<td>{$stk['ordered']}</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<th colspan='2'>Transfered to</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>To Branch</td>\n\t\t\t\t<td>{$sbran['branname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>To Store </td>\n\t\t\t\t<td>{$swh['whname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Number of units transfered</td>\n\t\t\t\t<td>{$tunits}</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . " width='15%'>\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='stock-transit-view.php'>View Stock in transit</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
function details($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>{$e['msg']}</li>";
        }
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $sql = "SELECT stkid FROM inv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
    $crslt = db_exec($sql);
    if (pg_numrows($crslt) < 1) {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has no items.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        return $error;
    }
    # check if invoice has been serialised
    if ($inv['serd'] == "n") {
        $error = "<li class='err'> Error : You must select serial numbers for some Items on Invoice No. <b>T {$invid}</b> before you can print it.</li>";
        return $error;
    }
    #check if this transaction date is allowed
    // 	$curyr = getActiveFinYear();
    // 	if ($yr > $curyr || ($yr == $curyr && $mon > $PRDMON[12])) {
    // 		$v->addError("", "Cannot do transaction in future financial year. ".(DEBUG>0?"\"$details\"":""));
    // 	}
    db_conn('cubit');
    $showvat = TRUE;
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($inv['odate']) >= strtotime($blocked_date_from) and strtotime($inv['odate']) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $invnum = divlastid('inv', USER_DIV);
    $Sl = "INSERT INTO ncsrec (oldnum, newnum, div) VALUES ('{$invid}', '{$invnum}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert into db");
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    /* --- Start Products Display --- */
    # Products layout
    $commision = 0;
    $products = array();
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM inv_items WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $taxex = 0;
    $i = 0;
    $page = 0;
    $salesp = qrySalesPersonN($inv["salespn"]);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                $showvat = FALSE;
            }
            $sp = "";
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "";
            }
            # all must be excempted
            if ($inv['chrgvat'] == 'nov') {
                $ex = "#";
            }
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            # Insert stock record
            $sdate = date("Y-m-d");
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            # Sales rep commission
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = $stk["com"];
            }
            #if this item is not exvat (ie. $ex != #) then reduce by the vat amount
            if ((strlen($ex) != "#" or $vd['vat_amount'] > 0) and $inv['chrgvat'] == "inc") {
                $vat = sprint($stkd['amt'] * $vd['vat_amount'] / (100 + $vd['vat_amount']));
                $exvatamt = sprint($stkd['amt'] - $vat);
            } else {
                $exvatamt = sprint($stkd['amt']);
            }
            $commision = $commision + coms($inv['salespn'], sprint($exvatamt), $itemcommission);
            if (strlen($stkd['serno']) > 0) {
                $showser = "<br>" . trim($stkd['serno']);
            } else {
                $showser = "";
            }
            # Put in product
            $products[$page][] = "\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$stk['stkcod']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$sp} {$stk['stkdes']}&nbsp; {$showser}</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$stkd['qty']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['unitcost']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['disc']}&nbsp;</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$stkd['amt']}&nbsp;</td>\n\t\t\t\t</tr>";
            $i++;
        } else {
            db_conn('core');
            $Sl = "SELECT * FROM accounts WHERE accid='{$stkd['account']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get account data.");
            $ad = pg_fetch_array($Ri);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                $showvat = FALSE;
            }
            $sp = "";
            # Check Tax Excempt
            if ($vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "";
            }
            # all must be excempted
            if ($inv['chrgvat'] == 'nov') {
                $ex = "#";
            }
            #if this item is not exvat (ie. $ex != #) then reduce by the vat amount
            if ((strlen($ex) != "#" or $vd['vat_amount'] > 0) and $inv['chrgvat'] == "inc") {
                $vat = sprint($stkd['amt'] * $vd['vat_amount'] / (100 + $vd['vat_amount']));
                $exvatamt = sprint($stkd['amt'] - $vat);
            } else {
                $exvatamt = sprint($stkd['amt']);
            }
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = 0;
            }
            $commision = $commision + coms($inv['salespn'], sprint($exvatamt), $itemcommission);
            # Put in product
            $products[$page][] = "\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$sp} {$stkd['description']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$stkd['qty']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['unitcost']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['disc']}&nbsp;</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$stkd['amt']}&nbsp;</td>\n\t\t\t\t</tr>";
            $i++;
        }
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\n\t \t\t\t<tr>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td>&nbsp;</td>\n\t \t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    if (strlen($inv['traddisc']) > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * $SUBTOT);
    } else {
        $traddiscm = "0.00";
    }
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOTAL = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    com_invoice($inv['salespn'], $TOTAL - $VAT, sprint($commision), $invnum, $inv["odate"], true);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    /* - End Hooks - */
    # Todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*refnum*/
    if ($inv['branch'] != 0) {
        db_conn("cubit");
        $get_addr = "SELECT * FROM customer_branches WHERE id = '{$inv['branch']}' LIMIT 1";
        $run_addr = db_exec($get_addr);
        if (pg_numrows($run_addr) < 1) {
            $address = "";
        } else {
            $barr = pg_fetch_array($run_addr);
            $address = " - {$barr['branch_name']}";
        }
    } else {
        $address = "";
    }
    /* --- Updates ---- */
    db_connect();
    $Sql = "UPDATE invoices SET printed = 'y', done = 'y', invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
    //dont make consignment order from invoice if customer number is entered ...
    //		if (isset($inv['cordno']) AND strlen($inv['cordno']) > 0){
    //			$inv_type = "Consignment Order";
    //		}else {
    $inv_type = "Invoice";
    //		}
    # Record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt (\n\t\t\t\tcusnum, invid, docref, amount, date, \n\t\t\t\ttype, branch, div, allocation_date, \n\t\t\t\tallocation_balance\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}', '{$inv['odate']}', \n\t\t\t\t'{$inv_type}', '{$address}', '" . USER_DIV . "', '{$inv['odate']}', \n\t\t\t\t'" . abs($inv['total']) . "'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO open_stmnt (\n\t\t\t\tcusnum, invid, docref, amount, balance, \n\t\t\t\tdate, type, div\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}','{$inv['total']}', \n\t\t\t\t'{$inv['odate']}', '{$inv_type}', '" . USER_DIV . "'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Save invoice discount
    $sql = "\n\t\t\tINSERT INTO inv_discs (\n\t\t\t\tcusnum, invid, traddisc, itemdisc, inv_date, delchrg, \n\t\t\t\tdiv, total\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$traddiscm}', '{$disc}', '{$inv['odate']}', '{$inv['delchrg']}', \n\t\t\t\t'" . USER_DIV . "', ({$SUBTOT}+{$inv['delchrg']})\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$inv['total']}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Make ledge record
    custledger($inv['cusnum'], $dept['incacc'], $inv['odate'], $invnum, "Invoice No. {$invnum}", $inv['total'], "d");
    db_connect();
    # get selected stock in this invoice
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    $sdate = date("Y-m-d");
    $nsp = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            db_connect();
            # get selamt from selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            if ($stk['units'] - $stkd['qty'] < 0) {
                if ($stk['units'] <= 0) {
                    $cosamt = 0;
                    $cosamt2 = 0;
                } else {
                    $cosamt = round($stk['units'] * $stk['csprice'], 2);
                    $cosamt2 = round($stk['units'] * $stk['csprice'], 4);
                }
            } else {
                $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
                $cosamt2 = round($stkd['qty'] * $stk['csprice'], 4);
            }
            # update stock(alloc - qty)
            $sql = "\n\t\t\t\t\tUPDATE stock \n\t\t\t\t\tSET csamt = (csamt - '{$cosamt}'),units = (units - '{$stkd['qty']}'), alloc=(alloc - '{$stkd['qty']}') \n\t\t\t\t\tWHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            if ($inv["pslip_sordid"] > 0) {
                $sql = "UPDATE stock SET alloc = (alloc - '{$stkd['qty']}') WHERE stkid='{$stkd['stkid']}'";
                //					db_exec($sql) or errDie("Unable to update allocation.");
            }
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            ####################################################
            $amtexvat = sprint($stkd['amt']);
            //	$uc=sprint($cosamt2/$stkd['qty']);
            $uc = round($cosamt2 / $stkd['qty'], 4);
            // '$cosamt',
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            db_connect();
            $sql = "\n\t\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, \n\t\t\t\t\t\tcsprice, csamt, details, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$inv['odate']}', '{$stkd['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'invoice', '{$stkd['qty']}', \n\t\t\t\t\t\t'{$amtexvat}', '{$csprice}', 'Stock sold - Invoice No. {$invnum}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
            if ($stk['csprice'] > 0) {
                $Sl = "INSERT INTO scr (inv, stkid, amount, invid) VALUES ('{$invnum}', '{$stkd['stkid']}', '{$uc}', '{$stkd['id']}')";
                $Rg = db_exec($Sl);
            }
            if ($stk['serd'] == 'yes') {
                ext_invSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $invnum, $inv['odate']);
            }
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            $sdate = date("Y-m-d");
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $inv['odate'], $stkd['qty'], $cosamt, "Sold to Customer : {$inv['surname']} - Invoice No. {$invnum}");
            # get accounts
            db_conn("exten");
            $sql = "SELECT stkacc, cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $stockacc = $wh['stkacc'];
            $cosacc = $wh['cosacc'];
            if ($cosamt < 0) {
                $cosamt = 0;
            }
            # dt(cos) ct(stock)
            writetrans($cosacc, $stockacc, $inv['odate'], $refnum, $cosamt, "Cost Of Sales for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
            $tcosamt += $cosamt;
            #record the entry for the stock report
            db_connect();
            $sql = "\n\t\t\t\t\tINSERT INTO salesrec (\n\t\t\t\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'stk', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
        } else {
            db_connect();
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if ($vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            ####################################################
            $amtexvat = sprint($stkd['amt']);
            db_connect();
            $sdate = date("Y-m-d");
            $nsp += sprint($iamount - $ivat);
            writetrans($dept['debtacc'], $stkd['account'], $inv['odate'], $refnum, $iamount - $ivat, "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
            db_connect();
            $sql = "\n\t\t\t\t\tINSERT INTO salesrec (\n\t\t\t\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'non', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
        }
    }
    ###################VAT CALCS#######################
    $inv['delvat'] += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    $vr = vatcalc($inv['delchrg'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", sprint($iamount + $ivat), $ivat);
    ####################################################
    /* - Start Transactoins - */
    # dt(debtors) ct(income/sales)
    writetrans($dept['debtacc'], $dept['incacc'], $inv['odate'], $refnum, sprint($TOTAL - $VAT - $nsp), "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    # dt(debtors) ct(vat account)
    writetrans($dept['debtacc'], $vatacc, $inv['odate'], $refnum, $VAT, "VAT Received on Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    db_conn('cubit');
    $Sl = "\n\t\t\tINSERT INTO sj (\n\t\t\t\tcid, name, des, date, exl, \n\t\t\t\tvat, inc, div\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$inv['surname']}', 'Invoice {$invnum}', '{$inv['odate']}', '" . sprint($TOTAL - $VAT) . "', \n\t\t\t\t'{$VAT}', '" . sprint($TOTAL) . "', '" . USER_DIV . "'\n\t\t\t)";
    $Ri = db_exec($Sl);
    //		db_connect();
    //		$sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)
    //		VALUES('$inv[odate]', '$invid', '$invnum', '$dept[debtacc]', '$VAT', '$TOTAL', 'stk', '".USER_DIV."')";
    //		$recRslt = db_exec($sql);
    //exit;
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* - End Transactoins - */
    # vat explanation
    if ($inv['chrgvat'] == 'nov') {
        $expl = "VAT Exempt indicator";
    } else {
        $expl = "VAT Exempt indicator";
    }
    if (strlen($inv['comm']) > 0) {
        $inv['comm'] = "\n\t\t\t<table border='1' cellspacing='0' bordercolor='#000000'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Remarks:</td>\n\t\t\t\t\t<td>" . nl2br($inv['comm']) . "</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    $cc = "<script> sCostCenter('dt', 'Sales', '{$inv['odate']}', 'Invoice No.{$invnum} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', ''); </script>";
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='SALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sp = "\n\t\t\t<tr>\n\t\t\t\t<td><b>Sales Person:</b> {$inv['salespn']}</td>\n\t\t\t</tr>";
    } else {
        $sp = "";
    }
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if ($inv['branch'] == 0) {
        $branchname = "Head Office";
    } else {
        $get_bname = "SELECT * FROM customer_branches WHERE id = '{$inv['branch']}' LIMIT 1";
        $run_bname = db_exec($get_bname);
        if (pg_numrows($run_bname) < 1) {
            $branchname = "";
        } else {
            $arr = pg_fetch_array($run_bname);
            $branchname = $arr['branch_name'];
        }
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    if (strlen(COMP_TEL) > 0) {
        $showtel = "Tel: ";
    } else {
        $showtel = "";
    }
    if (strlen(COMP_FAX) > 0) {
        $showfax = "Fax: ";
    } else {
        $showfax = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company information from Cubit.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    $bank_data = qryBankAcct(getdSetting("BANK_DET"));
    // Retrieve customer information
    db_conn("cubit");
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusnum']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
    $cust_data = pg_fetch_array($cust_rslt);
    $table_borders = "\n\t\tborder-top: 2px solid #000000;\n\t\tborder-left: 2px solid #000000;\n\t\tborder-right: 2px solid #000000;\n\t\tborder-bottom: none;";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $barcode = "<img src='manufact/" . pick_slip_barcode($inv["invid"], 1) . "' />";
        $details .= "\n\t\t<center>\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='left'><img src='compinfo/getimg.php' width='230' height='47'>{$barcode}</td>\n\t\t\t\t\t<td align='left'><font size='5'><b>" . COMP_NAME . "</b></font></td>\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Invoice</b></font></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td valign='top'>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td><td valign='top'>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\n\t\t\t\t\t<td><b>Page Number</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\n\t\t\t\t</tr>\n\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr><td>&nbsp</td></tr>\n\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$invnum}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Sales Order No:</b> {$inv['ordno']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Account No:</b> {$cust_data['accno']}</td>\n\t\t\t\t</tr>\n\t\t\t\t{$sp}\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='center'><font size='4'><b>Tax Invoice To:</b></font></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$inv['surname']}</b></td>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\n\t\t\t\t\t<td>Branch: {$branchname}<br />" . nl2br($inv["del_addr"]) . "</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer Order No:</b> {$inv['cordno']}</td>\n\t\t\t\t\t<td width='33%'><b>Delivery Date:</b> {$inv['deldate']}</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;'><b>Code</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;'><b>Description</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;'><b>Qty</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;' align='right'><b>Unit Price</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;' align='right'><b>Unit Discount</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000' align='right'><b>Amount</b></td>\n\t\t\t\t</tr>\n\t\t\t\t{$products_out}\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$inv['comm']}</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms: {$inv['terms']} days</b></td>\n\t\t\t\t\t<td><b>Subtotal:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['subtot']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t\t\t\t\t<td><b>Trade Discount:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['discount']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\n\t\t\t\t\t<td><b>Delivery Charge</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['delivery']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['vat']}</b></td>\n\t\t\t\t<tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['total']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t</table>";
    }
    // Retrieve template settings from Cubit
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve the template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    $OUTPUT = "\n\t\t<script>\n\t\t\tsCostCenter('dt', 'Sales', '{$inv['odate']}', 'Invoice No.{$invnum} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', '');\n\t\t</script>";
    if (isset($email)) {
        $OUTPUT .= "\n\t\t\t<script>\n\t\t\t\tmove(\"invoices-email.php?evs={$inv['invid']}\");\n\t\t\t</script>";
        require "template.php";
    }
    if ($template == "invoice-print.php") {
        $OUTPUT .= $details;
        require "tmpl-print.php";
    } else {
        $OUTPUT .= "\n\t\t\t<script>\n\t\t\t\tmove(\"{$template}?invid={$inv['invid']}&type=inv\");\n\t\t\t</script>";
        require "template.php";
    }
}
function write($_POST)
{
    # get stock vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($stkid, "num", 1, 50, "Invalid stock number.");
    $v->isOk($sstkid, "num", 1, 50, "Invalid stock number.");
    $v->isOk($whid, "num", 1, 50, "Invalid warehouse number.");
    $v->isOk($tunits, "float", 1, 15, "Invalid number of units.");
    $date = mkdate($d_year, $d_month, $d_day);
    $v->isOk($date, "date", 1, 1, "Invalid transfer date.");
    if ($stkid == $sstkid) {
        $v->isOk($shelf, "string", 0, 10, "Invalid Shelf number.");
        $v->isOk($row, "string", 0, 10, "Invalid Row number.");
        $v->isOk($minlvl, "num", 0, 10, "Invalid minimum stock level.");
        $v->isOk($maxlvl, "num", 0, 10, "Invalid maximum stock level.");
        $v->isOk($selamt, "float", 0, 10, "Invalid selling amount.");
    }
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        if (!ext_isUnique(ext_remBlnk($sernos))) {
            $v->isOk($error, "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li>";
        }
        return $confirm;
    }
    # Select Stock
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to get stock information.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.</li>";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    if ($stkid == $sstkid) {
        $sstk = $stk;
        $head = "New Stock";
        $data = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Location</td>\n\t\t\t\t<td>Shelf : <input type='hidden' name='shelf' value='{$shelf}'>{$shelf} - Row : <input type='hidden' name='row' value='{$row}'>{$row}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Level</td>\n\t\t\t\t<td>Minimum : <input type='hidden' name='minlvl' value='{$minlvl}'>{$minlvl} -  Maximum : <input type='hidden' name='maxlvl' value='{$maxlvl}'>{$maxlvl}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Selling price per unit</td>\n\t\t\t\t<td>" . CUR . " <input type='hidden' name='selamt' value='{$stk['selamt']}'>{$stk['selamt']}</td>\n\t\t\t</tr>";
    } else {
        $sql = "SELECT * FROM stock WHERE stkid = '{$sstkid}' AND div = '" . USER_DIV . "'";
        $sstkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
        if (pg_numrows($sstkRslt) < 1) {
            return "<li> Invalid Stock ID.</li>";
        } else {
            $sstk = pg_fetch_array($sstkRslt);
        }
        $head = "";
        $data = "";
    }
    db_conn("exten");
    # get warehouse
    $sql = "SELECT whid, whname, stkacc FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # get warehouse
    $sql = "SELECT whid, whname, stkacc FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
    $swhRslt = db_exec($sql);
    $swh = pg_fetch_array($swhRslt);
    /* Start Stock transfering */
    pglib_transaction("BEGIN") or errDie("Could Not Start Transaction.");
    db_connect();
    $csamt = $tunits * $stk['csprice'];
    $sdate = $date;
    if ($stkid == $sstkid) {
        # Create new stock item on the other hand
        $sql = "\n\t\t\tINSERT INTO stock (\n\t\t\t\tstkcod, serno, stkdes, prdcls, classname, csamt, \n\t\t\t\tunits, buom, suom, rate, shelf, row, minlvl, maxlvl, \n\t\t\t\tcsprice, selamt, catid, catname, whid, blocked, type, alloc, \n\t\t\t\tcom, serd, div, vatcode\n\t\t\t) VALUES (\n\t\t\t\t'{$sstk['stkcod']}', '{$sstk['serno']}', '{$sstk['stkdes']}', '{$sstk['prdcls']}', '{$sstk['classname']}', '{$csamt}',  \n\t\t\t\t'{$tunits}', '{$sstk['buom']}', '{$sstk['suom']}', '{$sstk['rate']}', '{$shelf}', '{$row}', '{$minlvl}', '{$maxlvl}', \n\t\t\t\t'{$sstk['csprice']}', '{$sstk['selamt']}', '{$sstk['catid']}', '{$sstk['catname']}', '{$whid}', 'n', '{$sstk['type']}', '0', \n\t\t\t\t'0', '{$sstk['serd']}', '" . USER_DIV . "', '{$sstk['vatcode']}'\n\t\t\t)";
        $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
        $sstkid = pglib_lastid("stock", "stkid");
        db_conn(date("n"));
        $sql = "\n\t\t\tINSERT INTO stkledger (\n\t\t\t\tstkid, stkcod, stkdes, trantype, edate, qty, csamt, \n\t\t\t\tbalance, bqty, details, div, yrdb\n\t\t\t) VALUES (\n\t\t\t\t'{$sstkid}', '{$sstk['stkcod']}', '{$sstk['stkdes']}', 'bal', '{$date}', '0', '0', \n\t\t\t\t'0', '0', 'Balance', '" . USER_DIV . "', '" . YR_DB . "'\n\t\t\t)";
        $Ro = db_exec($sql);
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        stockrec($sstkid, $sstk['stkcod'], $sstk['stkdes'], 'dt', $sdate, $tunits, $csamt, "Stock Transferred from Store : {$wh['whname']}", FALSE);
        db_connect();
        # Reduce on the other hand
        $sql = "UPDATE stock SET units = (units - '{$tunits}'), csamt = (csamt - '{$csamt}') WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock in Cubit.", SELF);
        //		db_conn('audit');
        //		for ($i = 1; $i <= 12; ++$i) {
        //			db_conn($i);
        //			$sql = "INSERT INTO stkledger(stkid,stkcod,stkdes,trantype,edate,qty,csamt,balance,
        //						bqty,details,div,yrdb)
        //					VALUES ('$data[stkid]','$data[stkcod]','$data[stkdes]','bal','$date',
        //						'$data[units]','$data[csamt]','$data[csamt]','$data[units]',
        //						'Balance','".USER_DIV."','".YR_DB."')";
        //			$Ro=db_exec($sql);
        // doesnt make sense ???
        // 			$sql = "
        // 				INSERT INTO stkledger (
        // 					stkid, stkcod, stkdes, trantype, edate, qty, csamt,
        // 					balance, bqty, details, div, yrdb
        // 				) VALUES (
        // 					'$sstk[stkid]', '$sstk[stkcod]', '$sstk[stkdes]', 'bal', '$date', '$sstk[units]', '$sstk[csamt]',
        // 					'$sstk[csamt]', '$sstk[units]', 'Balance', '".USER_DIV."', '".YR_DB."'
        // 				)";
        //		}
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $sdate, $tunits, $csamt, "Stock Transferred to Store : {$swh['whname']}");
        //		db_connect();
    } else {
        db_connect();
        # Move units and csamt
        $sql = "UPDATE stock SET units = (units + '{$tunits}'), csamt = (csamt + '{$csamt}') WHERE stkid = '{$sstkid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock in Cubit.", SELF);
        $sdate = date("Y-m-d");
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        stockrec($sstk['stkid'], $sstk['stkcod'], $sstk['stkdes'], 'dt', $sdate, $tunits, $csamt, "Stock Transferred from Store : {$wh['whname']}", FALSE);
        db_connect();
        # Reduce on the other hand
        $sql = "UPDATE stock SET units = (units - '{$tunits}'), csamt = (csamt - '{$csamt}') WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock in Cubit.", SELF);
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $sdate, $tunits, $csamt, "Stock Transferred to Store : {$swh['whname']}");
    }
    # todays date
    $refnum = getrefnum($date);
    db_connect();
    $ins_sql = "\n\t\tINSERT INTO stock_transfer (\n\t\t\tstkid, whid_from, whid_to, units, reference, remark, location_shelf, location_row, level_min, level_max, transfer_date\n\t\t) VALUES (\n\t\t\t'{$stkid}', '{$wh['whid']}', '{$swh['whid']}', '{$tunits}', '{$refnum}', '{$remark}', '{$shelf}', '{$row}', '{$minlvl}', '{$maxlvl}', '{$date}'\n\t\t)";
    $run_ins = db_exec($ins_sql) or errDie("Unable to record stock transfer information.");
    $serials = "";
    # Move serial number,using functions
    if (isset($sernos)) {
        $serials = "\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Units Serial Numbers</th>\n\t\t\t</tr>";
        foreach ($sernos as $skey => $serno) {
            ext_invSer($serno, $stkid);
            ext_unInvSer($serno, $sstkid);
            $serials .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2' align='center'>{$serno}</td>\n\t\t\t\t</tr>";
        }
    }
    # dt(cos) ct(stock)
    writetrans($swh['stkacc'], $wh['stkacc'], $date, $refnum, $csamt, "Stock Transfer");
    /* End Stock transfering */
    pglib_transaction("COMMIT") or errDie("Unable To Commit Transaction.");
    # Select Stock
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.</li>";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    # available stock units
    $avstk = $stk['units'] - $stk['alloc'];
    # return
    $write = "\n\t\t<h3> Stock has been Transfered </h3>\n\t\t<table " . TMPL_tblDflts . " width='350'>\n\t\t\t<tr>\n\t\t\t\t<th width='40%'>Field</th>\n\t\t\t\t<th width='60%'>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Warehouse</td>\n\t\t\t\t<td>{$wh['whname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Category</td>\n\t\t\t\t<td>{$stk['catname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock code</td>\n\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock description</td>\n\t\t\t\t<td>" . nl2br($stk['stkdes']) . "</pre></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>On Hand</td>\n\t\t\t\t<td>" . sprint3($stk['units']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Allocated</td>\n\t\t\t\t<td>" . sprint3($stk['alloc']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Available</td>\n\t\t\t\t<td>" . sprint3($avstk) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>On Order</td>\n\t\t\t\t<td>" . sprint3($stk['ordered']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t{$serials}\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Transfered to {$head}</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>To Store </td>\n\t\t\t\t<td>{$swh['whname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock code</td>\n\t\t\t\t<td>{$sstk['stkcod']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock description</td>\n\t\t\t\t<td>" . nl2br($sstk['stkdes']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Number of units transfered</td>\n\t\t\t\t<td>" . sprint3($tunits) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Remark</td>\n\t\t\t\t<td>{$remark}</td>\n\t\t\t</tr>\n\t\t\t{$data}\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . " width='15%'>\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='stock-transfer.php'>New Stock Transfer</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t</tr>\n\t\t</table>";
    return $write;
}
function write($_POST)
{
    # Set max execution time to 12 hours
    ini_set("max_execution_time", 43200);
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($invids as $key => $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid recuring invoice number.");
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $err;
    }
    $i = 0;
    foreach ($invids as $key => $invid) {
        # Get recuring invoice info
        db_connect();
        $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $invRslt = db_exec($sql) or errDie("Unable to get recuring invoice information");
        if (pg_numrows($invRslt) < 1) {
            return "<i class='err'>Not Found</i>";
        }
        $inv = pg_fetch_array($invRslt);
        # check if invoice has been printed
        if ($inv['printed'] == "y") {
            $error = "<li class='err'> Error : Invoice number <b>{$inv['invnum']}</b> has already been printed.";
            $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $error;
        }
        # check if invoice has been serialised
        if ($inv['serd'] == "n") {
            $error = "<li class='err'> Error : You must select serial numbers for some Items on Invoice No. <b>T {$invid}</b> before you can print it.";
            $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $error;
        }
        # Begin Updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        $invnum = divlastid('inv', USER_DIV);
        $Sl = "INSERT INTO ncsrec (oldnum, newnum, div) VALUES ('{$invid}', '{$invnum}', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert into db");
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<i class='err'>Not Found</i>";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        /* --- Start Products Display --- */
        # Products layout
        $commision = 0;
        $products = "";
        $disc = 0;
        # get selected stock in this invoice
        db_connect();
        $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        if (pg_numrows($stkdRslt) < 1) {
            $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has no items.</li>";
            if (($r2sid = r2sListCheck("invoice_stk_view")) !== false) {
                $error .= "<p><input type='button' onClick='document.location.href=\"r2srestore.php?r2sid={$r2sid}\";' value='List Invoices'>";
            } else {
                $error .= "<p><input type='button' onClick='document.location.href=\"invoice-view.php\";' value='List Invoices'>";
            }
            $OUTPUT = $error;
            pglib_transaction("ROLLBACK");
            require "template.php";
        }
        $taxex = 0;
        while ($stkd = pg_fetch_array($stkdRslt)) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            $sp = "&nbsp;&nbsp;&nbsp;&nbsp;";
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes') {
                $taxex += $stkd['amt'];
            }
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            # Insert stock record
            $sdate = date("Y-m-d");
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            # Get amount exluding vat if including and not exempted
            //			$VATP = TAX_VAT;
            #get the actual vat perc of this item
            $get_vat = "SELECT vat_amount FROM vatcodes WHERE id = '{$stkd['vatcode']}' LIMIT 1";
            $run_vat = db_exec($get_vat) or errDie("Unable to get vat percentage information");
            if (pg_numrows($run_vat) < 1) {
                $VATP = 0;
            } else {
                $varr = pg_fetch_array($run_vat);
                $VATP = $varr['vat_amount'];
            }
            $amtexvat = sprint($stkd['amt']);
            if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes') {
                $amtexvat = sprint($stkd['amt'] * 100 / (100 + $VATP));
            }
            if ($stkd['account'] == 0) {
                db_connect();
                $sql = "\n\t\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, \n\t\t\t\t\t\tcsprice, csamt, details, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sdate}', '{$stkd['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'invoice', '{$stkd['qty']}', \n\t\t\t\t\t\t'{$amtexvat}', '{$csprice}', 'Stock sold - Invoice No. {$invnum}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $recRslt = db_exec($sql);
                # Sales rep commission
                //				$commision = $commision + coms($inv['salespn'], $stkd['amt'], $stk['com']);
                $commision = $commision + coms($inv['salespn'], $amtexvat, $stk['com']);
            }
        }
        /* --- Start Some calculations --- */
        # Subtotal
        $SUBTOT = sprint($inv['subtot']);
        # Calculate tradediscm
        if (strlen($inv['traddisc']) > 0) {
            $traddiscm = sprint($inv['traddisc'] / 100 * $SUBTOT);
        } else {
            $traddiscm = "0.00";
        }
        # Calculate subtotal
        $VATP = TAX_VAT;
        $SUBTOTAL = sprint($inv['subtot']);
        $VAT = sprint($inv['vat']);
        $TOTAL = sprint($inv['total']);
        $inv['delchrg'] = sprint($inv['delchrg']);
        com_invoice($inv['salespn'], $TOTAL - $VAT, $commision, $invnum, $inv["odate"]);
        /* --- End Some calculations --- */
        /* - Start Hooks - */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "out");
        /* - End Hooks - */
        # Todays date
        $date = date("d-m-Y");
        $sdate = date("Y-m-d");
        $refnum = getrefnum();
        /* --- Updates ---- */
        db_connect();
        $Sql = "UPDATE invoices SET printed ='y', done ='y', invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
        # Record the payment on the statement
        $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "', '{$inv['odate']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Record the payment on the statement
        $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}','{$inv['total']}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Save invoice discount
        $sql = "INSERT INTO inv_discs(cusnum, invid, traddisc, itemdisc, inv_date, delchrg, div,total) VALUES('{$inv['cusnum']}', '{$invnum}', '{$traddiscm}', '{$disc}', '{$inv['odate']}', '{$inv['delchrg']}', '" . USER_DIV . "', ({$SUBTOT}+{$inv['delchrg']}))";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance more)
        $sql = "UPDATE customers SET balance = (balance + '{$inv['total']}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Make ledge record
        custledger($inv['cusnum'], $dept['incacc'], $inv["odate"], $invnum, "Invoice No. {$invnum}", $inv['total'], "d");
        $nsp = 0;
        db_connect();
        # get selected stock in this invoice
        $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $tcosamt = 0;
        while ($stkd = pg_fetch_array($stkdRslt)) {
            $stkd['account'] += 0;
            if ($stkd['account'] == 0) {
                db_connect();
                # get selamt from selected stock
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                if ($stk['units'] - $stkd['qty'] < 0) {
                    if ($stk['units'] <= 0) {
                        $cosamt = 0;
                    } else {
                        $cosamt = round($stk['units'] * $stk['csprice'], 2);
                    }
                } else {
                    $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
                }
                $uc = sprint($cosamt / $stkd['qty']);
                if ($stk['csprice'] > 0) {
                    $Sl = "INSERT INTO scr(inv,stkid,amount) VALUES ('{$invnum}','{$stkd['stkid']}','{$uc}')";
                    $Rg = db_exec($Sl);
                }
                # update stock(alloc - qty)
                $sql = "UPDATE stock SET csamt = (csamt - '{$cosamt}'),units = (units - '{$stkd['qty']}'),alloc = (alloc - '{$stkd['qty']}')  WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
                if ($stk['serd'] == 'yes') {
                    ext_invSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $invnum);
                }
                # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
                $sdate = date("Y-m-d");
                if ($stkd['account'] == 0) {
                    stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $sdate, $stkd['qty'], $cosamt, "Sold to Customer : {$inv['surname']} - Invoice No. {$invnum}");
                }
            }
            ###################VAT CALCS#######################
            db_connect();
            $stkd['vatcode'] += 0;
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            ####################################################
            if ($stkd['account'] == 0) {
                # get accounts
                db_conn("exten");
                $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                $stockacc = $wh['stkacc'];
                $cosacc = $wh['cosacc'];
                if ($cosamt > 0) {
                    # dt(cos) ct(stock)
                    //						writetrans($cosacc, $stockacc, $date, $refnum, $cosamt, "Cost Of Sales for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
                    writetrans($cosacc, $stockacc, $inv['odate'], $refnum, $cosamt, "Cost Of Sales for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
                }
                $tcosamt += $cosamt;
                db_connect();
                $date = date("Y-m-d");
                $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\t\t\tVALUES('{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'stk', '" . USER_DIV . "')";
                $recRslt = db_exec($sql);
            } else {
                $amtexvat = sprint($stkd['amt']);
                db_connect();
                $sdate = date("Y-m-d");
                $nsp += sprint($iamount - $ivat);
                //writetrans($cosacc, $stockacc,$inv['odate'] , $refnum, $cosamt, "Cost Of Sales for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
                writetrans($dept['debtacc'], $stkd['account'], $inv['odate'], $refnum, $iamount - $ivat, "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
                db_connect();
                $date = date("Y-m-d");
                $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\t\t\tVALUES('{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'non', '" . USER_DIV . "')";
                $recRslt = db_exec($sql);
            }
        }
        /* - Start Transactoins - */
        # dt(debtors) ct(income/sales)
        //			writetrans($dept['debtacc'], $dept['incacc'], $date, $refnum, sprint($TOTAL-$VAT-$nsp), "Debtors Control for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
        writetrans($dept['debtacc'], $dept['incacc'], $inv['odate'], $refnum, sprint($TOTAL - $VAT - $nsp), "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
        # dt(debtors) ct(vat account)
        writetrans($dept['debtacc'], $vatacc, $inv['odate'], $refnum, $VAT, "VAT Received on Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
        db_conn('cubit');
        $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t\t\t('{$inv['cusnum']}','{$inv['surname']}','Invoice {$invnum}','{$inv['odate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
        $Ri = db_exec($Sl);
        $ecost = sprint($TOTAL - $VAT);
        db_conn('cubit');
        $inv['jobid'] += 0;
        $Sl = "SELECT * FROM invc WHERE inv='{$inv['jobid']}'";
        $Ri = db_exec($Sl);
        if (CC_USE == "use") {
            if (pg_num_rows($Ri) > 0) {
                while ($data = pg_fetch_array($Ri)) {
                    db_conn('cubit');
                    $sql = "SELECT * FROM costcenters WHERE ccid = '{$data['cid']}'";
                    $ccRslt = db_exec($sql) or errDie("Unable to retrieve Cost centers from database.");
                    $cc = pg_fetch_array($ccRslt);
                    $amount = sprint($ecost * $data['amount'] / 100);
                    db_conn(PRD_DB);
                    $sql = "INSERT INTO cctran(ccid, trantype, typename, edate, description, amount, username, div)\n\t\t\t\t\t\tVALUES('{$cc['ccid']}', 'dt', 'Invoice', '{$inv['odate']}', 'Invoice No.{$invnum}', '{$amount}', '" . USER_NAME . "', '" . USER_DIV . "')";
                    $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
                }
            }
        }
        ####/*###*/############VAT CALCS#######################
        $inv['delvat'] += 0;
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            $Sl = "SELECT * FROM vatcodes";
            $Ri = db_exec($Sl);
        }
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        $vr = vatcalc($inv['delchrg'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
        ####################################################
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        $i++;
    }
    // Retrieve template settings
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        pdf($_POST);
    } else {
        templatePdf($_POST);
    }
    // Final Laytout
    $write = "\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>{$i} Invoices Proccesed</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Invoices has been successfully printed.</td>\n\t\t</tr>\n\t</table>\n\t<p>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='invoice-view.php'>View Invoices</a></td>\n\t\t</tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function details($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($inv['odate']) >= strtotime($blocked_date_from) and strtotime($inv['odate']) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    if ($inv['rounding'] > 0) {
        db_conn('core');
        $Sl = "SELECT * FROM salesacc WHERE name='rounding'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set the rounding account, under sales settings.";
        }
        $ad = pg_fetch_array($Ri);
        $rac = $ad['accnum'];
    }
    if ($inv['cusnum'] != "0") {
        #then get the actual customer
        db_connect();
        $get_cus = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' LIMIT 1";
        $run_cus = db_exec($get_cus) or errDie("Unable to get customer information");
        if (pg_numrows($run_cus) < 1) {
            #do nothing
        } else {
            $carr = pg_fetch_array($run_cus);
            $inv['cusname'] = "{$carr['cusname']}";
            $inv['surname'] = "{$carr['surname']}";
        }
    }
    $td = $inv['odate'];
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    db_conn('cubit');
    $sql = "SELECT stkid FROM pinv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
    $crslt = db_exec($sql);
    if (pg_numrows($crslt) < 1) {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has no items.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    if ($inv['terms'] == 1) {
        db_conn('core');
        $Sl = "SELECT * FROM salacc WHERE name='cc'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set a link for the POS credit card control account";
        }
        $cd = pg_fetch_array($Ri);
        $cc = $cd['accnum'];
    }
    $change = sprint(sprint($inv['pcash'] + $inv['pcheque'] + $inv['pcc'] + $inv['pcredit']) - sprint($inv['total'] - $inv['rounding']));
    $inv['pcash'] = sprint($inv['pcash'] - $change);
    if ($inv['pcash'] < 0) {
        $inv['pcash'] = 0;
    }
    if (sprint($inv['pcash'] + $inv['pcheque'] + $inv['pcc'] + $inv['pcredit']) != sprint($inv['total'] - $inv['rounding'])) {
        return "<li class='err'>The total of all the payments is not equal to the invoice total.<br>\n\t\tPlease edit the invoice and try again(You can only overpay with cash)</li>";
    }
    db_connect();
    # Begin updates
    #
    //lock(2);
    $invnum = divlastid('inv', USER_DIV);
    $Sl = "INSERT INTO ncsrec (oldnum,newnum, div) VALUES ('{$invid}','{$invnum}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert into db");
    //unlock(2);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class=err>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM pinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $taxex = 0;
    $commision = 0;
    $salesp = qrySalesPersonN($inv["salespn"]);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            db_connect();
            //this was set to the stock vatcode ??? must be the pur_item code ...
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "<li class='err'>Please select the vatcode for all your stock.</li>";
            }
            $vd = pg_fetch_array($Ri);
            $sp = "&nbsp;&nbsp;&nbsp;&nbsp;";
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "&nbsp;&nbsp;";
            }
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            # Insert stock record
            $sdate = date("Y-m-d");
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            # put in product
            $products .= "\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t\t<td>{$ex} {$sp} {$stk['stkdes']}</td>\n\t\t\t\t\t<td>{$stkd['qty']}</td>\n\t\t\t\t\t<td>" . sprint($stk["selamt"]) . "</td>\n\t\t\t\t\t<td>" . CUR . sprint($stkd["amt"]) . "</td>\n\t\t\t\t</tr>";
            # Get amount exluding vat if including and not exempted
            $VATP = TAX_VAT;
            $amtexvat = sprint($stkd['amt']);
            if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes') {
                $amtexvat = sprint($stkd['amt'] * 100 / (100 + $VATP));
            }
            $sql = "\n\t\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, \n\t\t\t\t\t\tcsamt, details, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$td}', '{$stkd['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'invoice', '{$stkd['qty']}', '{$stkd['amt']}', \n\t\t\t\t\t\t'{$csprice}', 'Stock sold - Invoice No. {$invnum}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = $stk["com"];
            }
            $commision = $commision + coms($inv['salespn'], $amtexvat, $itemcommission);
        } else {
            db_conn('core');
            $Sl = "SELECT * FROM accounts WHERE accid='{$stkd['account']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get account data.");
            $ad = pg_fetch_array($Ri);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            $sp = "";
            # Check Tax Excempt
            if ($vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "";
            }
            # all must be excempted
            if ($inv['chrgvat'] == 'nov') {
                $ex = "#";
            }
            $VATP = TAX_VAT;
            $amtexvat = sprint($stkd['amt']);
            if ($inv['chrgvat'] == "inc") {
                $amtexvat = sprint($stkd['amt'] * 100 / (100 + $VATP));
            }
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = 0;
            }
            $commision = $commision + coms($inv['salespn'], $amtexvat, $itemcommission);
            # Put in product
            $products .= "\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>{$ex} {$sp} {$stkd['description']}</td>\n\t\t\t\t\t<td>{$stkd['qty']}</td>\n\t\t\t\t\t<td>" . sprint($stkd["unitcost"]) . "</td>\n\t\t\t\t\t<td>{$stkd['disc']}</td>\n\t\t\t\t\t<td>" . CUR . sprint($stkd["amt"]) . "</td>\n\t\t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOTAL = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $av = $VAT;
    $at = $TOTAL - $VAT;
    $nt = sprint($inv['pcredit']);
    $sd = date("Y-m-d");
    $ro = $inv['rounding'];
    $ro += 0;
    com_invoice($inv['salespn'], $TOTAL - $VAT, $commision, $invnum, $td, true);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "novat");
    /* - End Hooks - */
    $nsp = 0;
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    db_conn('cubit');
    if ($inv['cusnum'] > 0 && $nt > 0) {
        # Record the payment on the statement
        $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$inv['cusnum']}', '{$invnum}', '0', '{$nt}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "', '{$inv['odate']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Record the payment on the statement
        $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('{$inv['cusnum']}', '{$invnum}', '0', '{$nt}', '{$nt}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance more)
        $sql = "UPDATE customers SET balance = (balance + '{$nt}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        custledger($inv['cusnum'], $dept['incacc'], $inv['odate'], $invnum, "Invoice No. {$invnum}", $nt, "d");
        recordDT($nt, $inv['cusnum'], $inv['odate']);
        db_conn('cubit');
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$nt}','Credit','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    db_conn('cubit');
    if ($inv['terms'] == 1) {
        $Sl = "INSERT INTO crec(userid,username,amount,pdate,inv) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}')";
        $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    } else {
        $Sl = "INSERT INTO posrec(userid,username,amount,pdate,inv) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}')";
        $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    }
    if (!isset($inv['cusname']) or strlen($inv['cusname']) < 1) {
        $custname = $inv['surname'];
    } else {
        $custname = $inv['cusname'];
    }
    $Sl = "INSERT INTO pr(userid,username,amount,pdate,inv,cust,t) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}','{$custname}','{$inv['terms']}')";
    $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    $refnum = getrefnum();
    /*refnum*/
    $fcash = $inv['pcash'];
    $fccp = $inv['pcc'];
    $fcheque = $inv['pcheque'];
    $fcredit = $inv['pcredit'];
    /* --- Updates ---- */
    db_connect();
    $Sql = "UPDATE pinvoices SET pchange='{$change}',printed ='y', done ='y',invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
    # save invoice discount
    $sql = "INSERT INTO inv_discs(cusnum, invid, traddisc, itemdisc, inv_date, delchrg, div,total) VALUES('0','{$invnum}','{$inv['delivery']}','{$disc}', '{$inv['odate']}', '{$inv['delivery']}', '" . USER_DIV . "',({$SUBTOT}+{$inv['delivery']}))";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # get selected stock in this invoice
    $sql = "SELECT * FROM pinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            db_connect();
            # get selamt from selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            if ($stk['units'] - $stkd['qty'] < 0) {
                if ($stk['units'] < 0) {
                    $stk['units'] = 0;
                }
                $cosamt = round($stk['units'] * $stk['csprice'], 2);
            } else {
                $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
            }
            # cost amount
            //$cosamt = round(($stkd['qty'] * $stk['csprice']), 2);
            if ($stk['csprice'] > 0) {
                $Sl = "INSERT INTO scr(inv,stkid,amount) VALUES ('{$invnum}','{$stkd['stkid']}',' {$stk['csprice']}')";
                $Rg = db_exec($Sl);
            }
            # update stock(alloc - qty)
            $sql = "UPDATE stock SET csamt = (csamt - '{$cosamt}'),units = (units - '{$stkd['qty']}'),alloc = (alloc - '{$stkd['qty']}')  WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vat code for all your stock.";
            }
            $VATP = TAX_VAT;
            $amtexvat = sprint($stkd['amt']);
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            ####################################################
            if ($stk['serd'] == 'yes') {
                ext_invSer($stkd['serno'], $stkd['stkid'], "POS Cash", $invnum);
            }
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            $sdate = date("Y-m-d");
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, $stkd['qty'], $cosamt, "POS Sales - Invoice No. {$invnum}");
            # get accounts
            db_conn("exten");
            $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $stockacc = $wh['stkacc'];
            $cosacc = $wh['cosacc'];
            # dt(cos) ct(stock)
            writetrans($cosacc, $stockacc, $td, $refnum, $cosamt, "Cost Of Sales POS Cash on POS Invoice No.{$invnum}.");
            $tcosamt += $cosamt;
            db_connect();
            $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\t\tVALUES('{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'stk', '" . USER_DIV . "')";
            $recRslt = db_exec($sql);
        } else {
            db_connect();
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if ($vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            $av -= $ivat;
            $at -= $iamount;
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            db_connect();
            $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\t\tVALUES('{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'non', '" . USER_DIV . "')";
            $recRslt = db_exec($sql);
            ####################################################
            $amtexvat = sprint($stkd['amt']);
            db_connect();
            $sdate = date("Y-m-d");
            $nsp += sprint($iamount - $ivat);
            // 				//writetrans($cosacc, $stockacc,$inv['odate'] , $refnum, $cosamt, "Cost Of Sales for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
            // 				writetrans($dept['debtacc'], $stkd['account'],$inv['odate'], $refnum, ($iamount-$ivat), "Debtors Control for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
            if ($inv['pcash'] > 0) {
                $min = $ro;
                $inv['pcash'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcash'] >= $ivat) {
                    writetrans($dept['pca'], $vatacc, $td, $refnum, $ivat, "VAT Received for POS Invoice No.{$invnum}.");
                    $inv['pcash'] = sprint($inv['pcash'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcash'] > 0) {
                        if ($inv['pcash'] >= $iamount) {
                            writetrans($dept['pca'], $stkd['account'], $td, $refnum, $iamount, "Sales for POS Invoice No.{$invnum}.");
                            $inv['pcash'] = sprint($inv['pcash'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcash'] < $iamount) {
                            writetrans($dept['pca'], $stkd['account'], $td, $refnum, $inv['pcash'], "Sales for POS Invoice No.{$invnum}.");
                            $iamount = sprint($iamount - $inv['pcash']);
                            $inv['pcash'] = 0;
                        }
                    }
                } else {
                    writetrans($dept['pca'], $vatacc, $td, $refnum, $inv['pcash'], "VAT Received for POS Invoice No.{$invnum}.");
                    $ivat = sprint($ivat - $inv['pcash']);
                    $inv['pcash'] = 0;
                }
                // 					db_conn('cubit');
                //
                // 					$inv['pcash']-=$min;
                //
                // 					$Sl="INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('$sd','".USER_NAME."','$invnum','$inv[pcash]','Cash','".PRD_DB."','0')";
                // 					$Ri=db_exec($Sl) or errDie("Unable to insert data.");
            }
            if ($inv['pcheque'] > 0) {
                $min = $ro;
                $inv['pcheque'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcheque'] >= $ivat) {
                    writetrans($dept['pca'], $vatacc, $td, $refnum, $ivat, "VAT Received for POS Invoice No.{$invnum}.");
                    $inv['pcheque'] = sprint($inv['pcheque'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcheque'] > 0) {
                        if ($inv['pcheque'] >= $iamount) {
                            writetrans($dept['pca'], $stkd['account'], $td, $refnum, $iamount, "Sales for POS Invoice No.{$invnum}.");
                            $inv['pcheque'] = sprint($inv['pcheque'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcheque'] < $iamount) {
                            writetrans($dept['pca'], $stkd['account'], $td, $refnum, $inv['pcheque'], "Sales for POS Invoice No.{$invnum}.");
                            $iamount = sprint($iamount - $inv['pcheque']);
                            $inv['pcheque'] = 0;
                        }
                    }
                } else {
                    writetrans($dept['pca'], $vatacc, $td, $refnum, $inv['pcheque'], "VAT Received for POS Invoice No.{$invnum}.");
                    $ivat = sprint($ivat - $inv['pcheque']);
                    $inv['pcheque'] = 0;
                }
                // 					db_conn('cubit');
                //
                // 					$inv['pcash']-=$min;
                //
                // 					$Sl="INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('$sd','".USER_NAME."','$invnum','$inv[pcash]','Cash','".PRD_DB."','0')";
                // 					$Ri=db_exec($Sl) or errDie("Unable to insert data.");
            }
            if ($inv['pcc'] > 0) {
                db_conn('core');
                $Sl = "SELECT * FROM salacc WHERE name='cc'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return "Please set a link for the POS credit card control account";
                }
                $cd = pg_fetch_array($Ri);
                $cc = $cd['accnum'];
                $min = $ro;
                $inv['pcc'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcc'] >= $ivat) {
                    writetrans($cc, $vatacc, $td, $refnum, $ivat, "VAT Received for POS Invoice No.{$invnum}.");
                    $inv['pcc'] = sprint($inv['pcc'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcc'] > 0) {
                        if ($inv['pcc'] >= $iamount) {
                            writetrans($cc, $stkd['account'], $td, $refnum, $iamount, "Sales for POS Invoice No.{$invnum}.");
                            $inv['pcc'] = sprint($inv['pcc'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcc'] < $iamount) {
                            writetrans($cc, $stkd['account'], $td, $refnum, $inv['pcc'], "Sales for POS Invoice No.{$invnum}.");
                            $iamount = sprint($iamount - $inv['pcc']);
                            $inv['pcc'] = 0;
                        }
                    }
                } else {
                    writetrans($cc, $vatacc, $td, $refnum, $inv['pcc'], "VAT Received for POS Invoice No.{$invnum}.");
                    $ivat = sprint($ivat - $inv['pcc']);
                    $inv['pcc'] = 0;
                }
                // 					db_conn('cubit');
                //
                // 					$inv['pcash']-=$min;
                //
                // 					$Sl="INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('$sd','".USER_NAME."','$invnum','$inv[pcash]','Cash','".PRD_DB."','0')";
                // 					$Ri=db_exec($Sl) or errDie("Unable to insert data.");
            }
            if ($inv['pcredit'] > 0) {
                db_conn('core');
                $min = $ro;
                $inv['pcredit'] += $ro;
                $ro = 0;
                //$amount=$inv['pcash'];
                if ($inv['pcredit'] >= $ivat) {
                    writetrans($dept['debtacc'], $vatacc, $td, $refnum, $ivat, "VAT Received for POS Invoice No.{$invnum}.");
                    $inv['pcredit'] = sprint($inv['pcredit'] - $ivat);
                    $ivat = 0;
                    if ($inv['pcredit'] > 0) {
                        if ($inv['pcredit'] >= $iamount) {
                            writetrans($dept['debtacc'], $stkd['account'], $td, $refnum, $iamount, "Sales for POS Invoice No.{$invnum}.");
                            $inv['pcredit'] = sprint($inv['pcredit'] - $iamount);
                            $iamount = 0;
                        } elseif ($inv['pcredit'] < $iamount) {
                            writetrans($dept['debtacc'], $stkd['account'], $td, $refnum, $inv['pcredit'], "Sales for POS Invoice No.{$invnum}.");
                            $iamount = sprint($iamount - $inv['pcredit']);
                            $inv['pcredit'] = 0;
                        }
                    }
                } else {
                    writetrans($dept['debtacc'], $vatacc, $td, $refnum, $inv['pcredit'], "VAT Received for POS Invoice No.{$invnum}.");
                    $ivat = sprint($ivat - $inv['pcredit']);
                    $inv['pcredit'] = 0;
                }
                // 					db_conn('cubit');
                //
                // 					$inv['pcash']-=$min;
                //
                // 					$Sl="INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('$sd','".USER_NAME."','$invnum','$inv[pcash]','Cash','".PRD_DB."','0')";
                // 					$Ri=db_exec($Sl) or errDie("Unable to insert data.");
            }
        }
    }
    /* - Start Transactoins - */
    ###################VAT CALCS#######################
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    $excluding = "";
    $vr = vatcalc($inv['delchrg'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
    ####################################################
    //print $inv['pcash'];exit;
    if ($inv['pcash'] > 0) {
        $min = $ro;
        $inv['pcash'] += $ro;
        $ro = 0;
        $amount = $inv['pcash'];
        if ($amount >= $av) {
            writetrans($dept['pca'], $vatacc, $td, $refnum, $av, "VAT Received for POS Invoice No.{$invnum}.");
            // PROBLEM HERE?
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['pca'], $dept['pia'], $td, $refnum, $amount, "Sales for POS Invoice No.{$invnum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($dept['pca'], $vatacc, $td, $refnum, $amount, "VAT Received for POS Invoice No.{$invnum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcash'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fcash}','Cash','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
        $fcash = 0;
    }
    db_conn('cubit');
    if ($fcash > 0) {
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fcash}','Cash','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['pcheque'] > 0) {
        $min = $ro;
        $inv['pcheque'] += $ro;
        $ro = 0;
        $amount = $inv['pcheque'];
        if ($amount >= $av) {
            writetrans($dept['pca'], $vatacc, $td, $refnum, $av, "VAT Received for POS Invoice No.{$invnum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['pca'], $dept['pia'], $td, $refnum, $amount, "Sales for POS Invoice No.{$invnum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($dept['pca'], $vatacc, $td, $refnum, $amount, "VAT Received for POS Invoice No.{$invnum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcheque'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fcheque}','Cheque','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
        $fcheque = 0;
    }
    db_conn('cubit');
    if ($fcheque > 0) {
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fcheque}','Cheque','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['pcc'] > 0) {
        db_conn('core');
        $Sl = "SELECT * FROM salacc WHERE name='cc'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set a link for the POS credit card control account";
        }
        $cd = pg_fetch_array($Ri);
        $cc = $cd['accnum'];
        $min = $ro;
        $inv['pcc'] += $ro;
        $ro = 0;
        $amount = $inv['pcc'];
        if ($amount >= $av) {
            writetrans($cc, $vatacc, $td, $refnum, $av, "VAT Received for POS Invoice No.{$invnum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($cc, $dept['pia'], $td, $refnum, $amount, "Sales for POS Invoice No.{$invnum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($cc, $vatacc, $td, $refnum, $amount, "VAT Received for POS Invoice No.{$invnum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcc'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fccp}','Credit Card','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
        $fccp = 0;
    }
    db_conn('cubit');
    if ($fccp > 0) {
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fccp}','Credit Card','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['pcredit'] > 0) {
        db_conn('core');
        $min = $ro;
        $inv['pcredit'] += $ro;
        $ro = 0;
        $amount = $inv['pcredit'];
        if ($amount >= $av) {
            writetrans($dept['debtacc'], $vatacc, $td, $refnum, $av, "VAT Received for POS Invoice No.{$invnum}.");
            $amount = sprint($amount - $av);
            $av = 0;
            if ($amount > 0) {
                writetrans($dept['debtacc'], $dept['pia'], $td, $refnum, $amount, "Sales for POS Invoice No.{$invnum}.");
                $at = $at - $amount;
            }
        } else {
            writetrans($dept['debtacc'], $vatacc, $td, $refnum, $amount, "VAT Received for POS Invoice No.{$invnum}.");
            $av = $av - $amount;
            $amount = 0;
        }
        db_conn('cubit');
        $inv['pcc'] -= $min;
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fcredit}','Credit','" . PRD_DB . "','0')";
        //$Ri=db_exec($Sl) or errDie("Unable to insert data.");
        $fcredit = 0;
    }
    db_conn('cubit');
    if ($fcredit > 0) {
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$td}','" . USER_NAME . "','{$invnum}','{$fcredit}','Credit','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    if ($inv['rounding'] > 0) {
        if ($inv['pcash'] > 0) {
            writetrans($rac, $dept['pca'], $td, $refnum, $inv['rounding'], "Rounding  on Invoice No.{$invnum}.");
        } elseif ($inv['pcheque'] > 0) {
            writetrans($rac, $dept['pca'], $td, $refnum, $inv['rounding'], "Rounding on Invoice No.{$invnum}.");
        } elseif ($inv['pcc'] > 0) {
            writetrans($rac, $cc, $td, $refnum, $inv['rounding'], "Rounding on Invoice No.{$invnum}.");
        } elseif ($inv['pcredit'] > 0) {
            writetrans($rac, $dept['debtacc'], $td, $refnum, $inv['rounding'], "Rounding on Invoice No.{$invnum}.");
        }
    }
    // 	if($inv['terms']==1) {
    // 		$dept['pca']=$cc;
    // 	}
    //
    // 	# dt(debtors) ct(income/sales)
    // 	writetrans($dept['pca'], $dept['pia'], $td, $refnum, ($TOTAL-$VAT), "Sales for POS Invoice No.$invnum.");
    //
    // 	# dt(debtors) ct(vat account)
    // 	writetrans($dept['pca'], $vatacc, $td, $refnum, $VAT, "VAT Received for POS Invoice No.$invnum.");
    //	db_connect();
    //	$sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)
    //	VALUES('$inv[odate]', '$invid', '$invnum', '$dept[debtacc]', '$VAT', '$TOTAL', 'stk', '".USER_DIV."')";
    //	$recRslt = db_exec($sql);
    db_conn('cubit');
    if ($inv['cusnum'] > 0) {
        db_conn('cubit');
        $Sl = "SELECT * FROM customers WHERE cusnum='{$inv['cusnum']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $cd = pg_fetch_array($Ri);
        $inv['cusname'] = $cd['surname'];
    }
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t('{$inv['cusnum']}','{$inv['cusname']}','POS Invoice {$invnum}','{$inv['odate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    if ($change > 0) {
        $Sl = "INSERT INTO pc(date,by,inv,amount) VALUES ('{$sd}','" . USER_NAME . "','{$invnum}','{$change}')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    db_conn('cubit');
    if ($inv['rounding'] > 0) {
        $Sl = "INSERT INTO varrec(inv,date,amount) VALUES('{$invnum}','" . date("Y-m-d") . "','{$inv['rounding']}')";
        $Ri = db_exec($Sl);
    }
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (strlen($inv['comm']) > 0) {
        $Com = "<table><tr><td>" . nl2br($inv['comm']) . "</td></tr></table>";
    } else {
        $Com = "";
    }
    $cc = "<script> sCostCenter('dt', 'Sales', '{$inv['odate']}', 'POS Invoice No.{$invnum}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', ''); </script>";
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    /* - End Transactoins - */
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t<center>\n\t\t\t\t\t{$cc}\n\t\t\t\t\t<h2>Tax Invoice</h2>\n\t\t\t\t\t<table cellpadding='0' cellspacing='1' border=0 width=750>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td valign='top' width='40%'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr><td>{$inv['surname']}</td></tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='top' width='35%'>\n\t\t\t\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\t\t\t\tReg No. " . COMP_REGNO . "<br>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='bottom' align='right' width='25%'>\n\t\t\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$invnum}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Order No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['ordno']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Terms</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>Cash</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Invoice Date</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['odate']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>VAT</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['chrgvat']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='3'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width=100% bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t\t\t\t\t\t\t<th width='45%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t\t\t\t<th>QTY</th>\n\t\t\t\t\t\t\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t\t\t\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t{$products}\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>{$Com}</td>\n\t\t\t\t\t\t\t<td align='right' colspan='2'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='50%' bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$SUBTOT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Trade Discount</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$inv['discount']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Delivery Charge</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$inv['delivery']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>VAT @ {$VATP}%</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$VAT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th><b>GRAND TOTAL<b></th>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " border='1'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td colspan='2'>VAT Exempt indicator = #</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th>VAT No.</th>\n\t\t\t\t\t\t\t\t\t\t<td align='center'>" . COMP_VATNO . "</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t        </table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td><br></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</center>";
    /* Start moving invoices */
    db_connect();
    # Move invoices that are fully paid
    $sql = "SELECT * FROM pinvoices WHERE printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    while ($invb = pg_fetch_array($invbRslt)) {
        db_conn($invb['prd']);
        $invb['invnum'] += 0;
        # Insert invoice to period DB
        $sql = "INSERT INTO pinvoices(invid,invnum, deptid, cusnum, deptname, cusacc, cusname, telno,\n\t\t\t\t\tsurname, cusaddr, cusvatno, cordno, ordno, chrgvat, terms, traddisc, salespn,\n\t\t\t\t\todate, delchrg, subtot, vat, total, balance, comm, printed, done, div, username,\n\t\t\t\t\trounding,delvat,vatnum,pcash,pcheque,pcc,pcredit, pslip_sordid)\n\t\t\t\tVALUES('{$invb['invid']}','{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}',\n\t\t\t\t\t'{$invb['deptname']}', '{$invb['cusacc']}', '{$invb['cusname']}', '{$invb['telno']}', '{$invb['surname']}',\n\t\t\t\t\t'{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}',\n\t\t\t\t\t'{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}',\n\t\t\t\t\t'{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' ,\n\t\t\t\t\t'{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', 'y', 'y', '" . USER_DIV . "',\n\t\t\t\t\t'" . USER_NAME . "','{$invb['rounding']}','{$invb['delvat']}','{$invb['vatnum']}',\n\t\t\t\t\t'{$invb['pcash']}','{$invb['pcheque']}','{$invb['pcc']}','{$invb['pcredit']}', '{$invb['pslip_sordid']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.", SELF);
        db_connect();
        $sql = "INSERT INTO movinv(invtype, invnum, prd, docref, div) VALUES('pos', '{$invb['invnum']}', '{$invb['prd']}', '', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.", SELF);
        # get selected stock in this invoice
        db_connect();
        $sql = "SELECT * FROM pinv_items WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        while ($stkd = pg_fetch_array($stkdRslt)) {
            db_conn($invb['prd']);
            # insert invoice items
            $stkd['vatcode'] += 0;
            $stkd['account'] += 0;
            $sql = "INSERT INTO pinv_items(invid, whid, stkid, qty, unitcost, amt, disc, discp, serno, div,vatcode,account,description) VALUES('{$invb['invid']}', '{$stkd['whid']}', '{$stkd['stkid']}', '{$stkd['qty']}', '{$stkd['unitcost']}', '{$stkd['amt']}', '{$stkd['disc']}', '{$stkd['discp']}', '{$stkd['serno']}', '" . USER_DIV . "','{$stkd['vatcode']}','{$stkd['account']}','{$stkd['description']}')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
        }
        db_connect();
        # Remove those invoices from running DB
        $sql = "DELETE FROM pinvoices WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        # Remove those invoice items from running DB
        $sql = "DELETE FROM pinv_items WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    }
    /* end moving invoices */
    /* OLD
    	$OUTPUT = $details;
    	require("tmpl-print.php");*/
    header("Location: pos-slip.php?invid={$inv['invid']}&prd={$inv['prd']}&cccc=yes");
    exit;
}