/**
 * destroys r2s by name
 *
 * the list of r2s's allow you to associate a name to an r2sid, for ex.
 * every time you list invoices a new r2s is made, if an error say occurs
 * when processing the selected invoices you can just click the link to
 * go back to the exact same listing.
 */
function r2sListDestroy($name)
{
    if (($r2sid = r2sListCheck($name)) !== false) {
        r2s_destroy($r2sid);
        unset($_SESSION["R2S_NAMED"][$name]);
    }
}
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;
}