function write($_POST)
{
    # Set max execution time to 12 hours
    ini_set("max_execution_time", 43200);
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($invids as $key => $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid recuring invoice number.");
    }
    $VATP = TAX_VAT;
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return $err;
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $i = 0;
    foreach ($invids as $key => $invid) {
        db_connect();
        $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "' and done='n'";
        $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);
        $ctyp = $inv['ctyp'];
        //$td=$inv['sdate'];
        $td = $inv['odate'];
        //$cus['surname']=$inv['cusname'];
        if ($ctyp == 's') {
            $cusnum = $inv['tval'];
            $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to view customer");
            $cus = pg_fetch_array($custRslt);
            $na = $cus['surname'];
        } elseif ($ctyp == 'c') {
            $deptid = $inv['tval'];
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
            $deptRslt = db_exec($sql) or errDie("Unable to view customers");
            $dept = pg_fetch_array($deptRslt);
            $na = $inv['cusname'];
        }
        db_connect();
        $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql) or errDie("Unable to get data.");
        unset($totstkamt);
        $refnum = getrefnum();
        /*refnum*/
        /* - Start Hooks - */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "NO VAT");
        $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
        /* - End Hooks - */
        db_conn("cubit");
        $real_invid = divlastid('inv', USER_DIV);
        db_conn("cubit");
        # Put in product
        $totstkamt = array();
        while ($stk = pg_fetch_array($stkdRslt)) {
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatex']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            if ($vd['zero'] == "Yes") {
                $stk['vatex'] = "y";
            }
            $t = $inv['chrgvat'];
            $stkacc = $stk['accid'];
            if (isset($totstkamt[$stkacc])) {
                if ($stk['vatex'] == "y") {
                    $totstkamt[$stkacc] += vats($stk['amt'], 'novat', $vd['vat_amount']);
                    $va = 0;
                    $inv['chrgvat'] = "";
                } else {
                    $totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                    $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                    if ($inv['chrgvat'] == "no") {
                        $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                    }
                }
            } else {
                if ($stk['vatex'] == "y") {
                    $totstkamt[$stkacc] = vats($stk['amt'], 'novat', $vd['vat_amount']);
                    $inv['chrgvat'] = "";
                    $va = 0;
                } else {
                    $totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                    $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                    if ($inv['chrgvat'] == "no") {
                        $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                    }
                }
            }
            vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock Sales, invoice No.{$real_invid}", vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']) + $va, $va);
            //print vats($stk['amt'],$inv['chrgvat'], $vd['vat_amount']);
            $inv['chrgvat'] = $t;
            //$sql = "UPDATE nons_inv_items SET accid = '$stk[account]' WHERE id = '$stk[id]'";
            //$sRslt = db_exec($sql);
        }
        /* --- Start Some calculations --- */
        # Subtotal
        $SUBTOT = sprint($inv['subtot']);
        $VAT = sprint($inv['vat']);
        $TOTAL = sprint($inv['total']);
        /* --- End Some calculations --- */
        /* - Start Hooks - */
        //$vatacc = gethook("accnum", "salesacc", "name", "VAT");
        /* - End Hooks - */
        # todays date
        $date = date("d-m-Y");
        $sdate = date("Y-m-d");
        db_conn("cubit");
        if (isset($bankid)) {
            $bankid += 0;
            db_conn("cubit");
            $sql = "SELECT * FROM bankacct WHERE bankid = '{$inv['accid']}'";
            $deptRslt = db_exec($sql) or errDie("Unable to view customers");
            if (pg_numrows($deptRslt) < 1) {
                $error = "<li class=err> Bank not Found.";
                $confirm .= "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
                return $confirm;
            } else {
                $deptd = pg_fetch_array($deptRslt);
            }
            db_conn('core');
            $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
            $rd = db_exec($Sl) or errDie("Unable to get data.");
            $data = pg_fetch_array($rd);
            $BA = $data['accnum'];
        }
        $tot_post = 0;
        # bank  % cust
        if ($ctyp == 's') {
            # Get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                $dept['deptname'] = "<li class=err>Department not Found.";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $tpp = 0;
            //$sql = "SELECT * FROM nons_inv_items  WHERE invid = '$invid' AND div = '".USER_DIV."'";
            //$stkdRslt = db_exec($sql);
            // 			# Put in product
            // 			while($stk = pg_fetch_array($stkdRslt)){
            // 				$wamt=$stk['amt'];
            //
            // 				$tot_post+=$wamt;
            // 				writetrans($dept['debtacc'], $stk['account'], $td, $refnum, $wamt, "Non-Stock Sales on invoice No.$real_invid customer $cus[surname].");
            // 			}
            # record transaction  from data
            foreach ($totstkamt as $stkacc => $wamt) {
                # Debit Customer and Credit stock
                $tot_post += $wamt;
                writetrans($dept['debtacc'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            # Debit bank and credit the account involved
            if ($VAT != 0) {
                $tot_post += $VAT;
                writetrans($dept['debtacc'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            $sdate = date("Y-m-d");
        } else {
            if (!isset($accountc)) {
                $accountc = 0;
            }
            if (!isset($dept['pca'])) {
                $accountc += 0;
                $dept['pca'] = $accountc;
                $dept['debtacc'] = $accountc;
            }
            if (isset($bankid)) {
                $dept['pca'] = $BA;
            }
            if ($ctyp == "ac") {
                $dept['pca'] = $inv['tval'];
            }
            $tpp = 0;
            # record transaction  from data
            foreach ($totstkamt as $stkacc => $wamt) {
                if (!isset($cust['surname'])) {
                    $cust['surname'] = $inv['cusname'];
                    $cust['addr1'] = $inv['cusaddr'];
                }
                # Debit Customer and Credit stock
                $tot_post += $wamt;
                writetrans($dept['pca'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            if (isset($bankid)) {
                db_connect();
                $bankid += 0;
                $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div) VALUES ('{$bankid}', 'deposit', '{$td}', '{$inv['cusname']}', 'Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}', '0', '{$TOTAL}', '{$VAT}', '{$inv['chrgvat']}', 'no', '{$stkacc}', '" . USER_DIV . "')";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                $sql = "UPDATE nons_invoices SET jobid='{$bankid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            }
            # Debit bank and credit the account involved
            if ($VAT != 0) {
                $tot_post += $VAT;
                writetrans($dept['pca'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            $sdate = date("Y-m-d");
        }
        $tot_post = sprint($tot_post);
        db_connect();
        if ($ctyp == 's') {
            $sql = "UPDATE nons_invoices SET balance = total, cusid = '{$cusnum}', ctyp = '{$ctyp}', cusaddr = '{$cus['addr1']}', cusvatno = '{$cus['vatnum']}', done = 'y', invnum = '{$real_invid}' 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('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}','{$inv['odate']}', 'Non-Stock 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('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}', '{$TOTAL}','{$inv['sdate']}', 'Non-Stock 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 + '{$TOTAL}'::numeric(13,2)) WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            # Make ledge record
            custledger($cusnum, $stkacc, $td, $real_invid, "Non Stock Invoice No. {$real_invid}", $TOTAL, "d");
            custDT($TOTAL, $cusnum, $td, $invid, "nons");
            //print $tot_post;exit;
            $tot_dif = sprint($tot_post - $TOTAL);
            if ($tot_dif > 0) {
                writetrans($varacc, $dept['debtacc'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            } elseif ($tot_dif < 0) {
                $tot_dif = $tot_dif * -1;
                writetrans($dept['debtacc'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            }
        } else {
            $date = date("Y-m-d");
            $sql = "UPDATE nons_invoices SET balance=total, accid = '{$dept['pca']}', ctyp = '{$ctyp}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
            $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            $tot_dif = sprint($tot_post - $TOTAL);
            if ($tot_dif > 0) {
                writetrans($varacc, $dept['pca'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            } elseif ($tot_dif < 0) {
                $tot_dif = $tot_dif * -1;
                writetrans($dept['pca'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            }
            if ($ctyp == "c") {
                $cusnum = "0";
            } elseif ($ctyp == "ac") {
                $cusnum = "0";
                $na = "";
            }
        }
        db_connect();
        $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\tVALUES('{$inv['sdate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$VAT}', '{$TOTAL}', 'non', '" . USER_DIV . "')";
        $recRslt = db_exec($sql);
        db_conn('cubit');
        $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t\t('{$cusnum}','{$na}','Non-stock Invoice {$real_invid}','{$inv['sdate']}','" . 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 ninvc 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\tVALUES('{$cc['ccid']}', 'dt', 'Invoice', '{$inv['sdate']}', 'Invoice No.{$real_invid}', '{$amount}', '" . USER_NAME . "', '" . USER_DIV . "')";
                    $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
                }
            }
        }
        $i++;
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Retrieve template settings
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices' AND div='" . USER_DIV . "'";
    $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 border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>{$i} Invoices Proccesed</th></tr>\n\t\t<tr class='bg-even'><td>Invoices have been successfully printed.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t<tr><th>Quick Links</th></tr>\n\t<tr class='bg-odd'><td><a href='invoice-view.php'>View Invoices</a></td></tr>\n\t<script>document.write(getQuicklinkSpecial());</script>\n\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;
}