function write($_GET)
{
    $showvat = TRUE;
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice number.");
    $sndate = $ninv_year . "-" . $ninv_month . "-" . $ninv_day;
    if (!checkdate($ninv_month, $ninv_day, $ninv_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    $td = $sndate;
    foreach ($ids as $key => $id) {
        $v->isOk($id, "num", 1, 20, "Invalid Item number.");
        $v->isOk($qtys[$key], "float", 1, 20, "Invalid Item quantity.");
        $v->isOk($amts[$key], "float", 1, 20, "Invalid Item amount.");
    }
    $v->isOk($subtot, "float", 1, 20, "Invalid sub-total amount.");
    $v->isOk($vat, "float", 1, 20, "Invalid vat amount.");
    $v->isOk($total, "float", 1, 20, "Invalid total amount.");
    # 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 hire.hire_nons_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);
    db_conn("hire");
    $noteid = pglib_lastid("hire_nons_inv_notes", "noteid");
    $noteid++;
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* --- Start Products Display --- */
    $refnum = getrefnum();
    /*refnum*/
    $real_noteid = divlastid('note', USER_DIV);
    $vattot = 0;
    $amttot = 0;
    db_connect();
    # Products layout
    $products = array();
    $i = 0;
    $page = 0;
    foreach ($ids as $key => $id) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $sql = "SELECT * FROM hire.hire_nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $temp = $stkd['vatex'];
        if ($vd['zero'] == "Yes") {
            $stkd['vatex'] = "y";
        }
        $t = $inv['chrgvat'];
        //	$VATP = TAX_VAT;
        $VATP = $vd['vat_amount'];
        $stkacc = $stkd['accid'];
        # keep records for transactions
        if (isset($totstkamt[$stkacc])) {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] += $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] += vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($stkd['amt'] - vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        } else {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] = $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] = vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($amts[$key] - vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        }
        #add this entry's vat to a total
        $vattot = $vattot + $va;
        vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.", -vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']) - $va, -$va);
        $inv['chrgvat'] = $t;
        $sql = "UPDATE hire.hire_nons_inv_items SET rqty = (rqty + '{$qtys[$key]}') WHERE id = '{$stkd['id']}'";
        $sRslt = db_exec($sql);
        if ($stkd['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        $stkd['vatex'] = $temp;
        #add this entry's amt to a total
        $amttot = $amttot + $amts[$key];
        $sql = "INSERT INTO hire.hire_nons_note_items(noteid, qty, description, amt, unitcost, vatcode) VALUES('{$noteid}', '{$qtys[$key]}', '{$stkd['description']}', '{$amts[$key]}', '{$stkd['unitcost']}', '{$stkd['vatex']}')";
        $stkdRslt = db_exec($sql);
        #the credit note entry will get any remark entered here ? so we dont update the invoice entry ...
        //	db_conn("cubit");
        //	$sql = "UPDATE nons_invoices SET remarks='$remarks' WHERE invid='$invid'";
        //	$rslt = db_exec($sql) or errDie("Unable to save the comments to Cubit.");
        $products[$page][] = "\r\n\t\t\t\t\t\t<tr valign='top'>\r\n\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$stkd['description']}&nbsp;</td>\r\n\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$qtys[$key]}&nbsp;</td>\r\n\t\t\t\t\t\t\t<td style='border-right: 2px solid #000' align='right' nowrap>" . CUR . " {$stkd['unitcost']}&nbsp;</td>\r\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$amts[$key]}&nbsp;</td>\r\n\t\t\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][] = "\r\n\t\t\t\t \t\t\t<tr>\r\n\t\t\t\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t \t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t \t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($subtot);
    $VAT = sprint($vat);
    $TOTAL = sprint($total);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "vat");
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    // print $inv['ctyp']; exit;
    db_connect();
    $tot_post = 0;
    # bank  % cust
    if ($inv['ctyp'] == 's') {
        $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cus = pg_fetch_array($custRslt);
        # 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;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            $tot_post += $wamt;
            writetrans($stkacc, $dept['debtacc'], $td, $refnum, $wamt, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.");
        }
        if ($VAT != 0) {
            $tot_post += $VAT;
            writetrans($vatacc, $dept['debtacc'], $td, $refnum, $VAT, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT. Customer {$inv['cusname']}.");
        }
        $tot_dif = sprint($tot_post - $TOTAL);
        if ($tot_dif > 0) {
            writetrans($dept['debtacc'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($varacc, $dept['debtacc'], $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        }
    } elseif ($inv['ctyp'] == 'b') {
        $dept['debtacc'] = getbankaccid($inv['accid']);
        $amounts = "";
        $accids = "";
        $vats = "";
        $chrgvats = "";
        $gamt = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            # Cook vars
            $amounts .= "|{$wamt}";
            $accids .= "|{$stkacc}";
            $vats .= "|0";
            $chrgvats .= "|no";
            # Debit Customer and Credit stock
            $tot_post += $wamt;
            writetrans($stkacc, $dept['debtacc'], $td, $refnum, $wamt, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid}.");
        }
        # Debit bank and credit the account involved
        if ($VAT != 0) {
            # Cook vars
            $amounts .= "|{$VAT}";
            $accids .= "|{$vatacc}";
            $vats .= "|0";
            $chrgvats .= "|no";
            $tot_post += $VAT;
            writetrans($vatacc, $dept['debtacc'], $td, $refnum, $VAT, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT.");
        }
    } else {
        $cusacc = $inv['accid'];
        $sdate = date("Y-m-d");
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            # Debit Customer and Credit stock
            $tot_post += $wamt;
            writetrans($stkacc, $cusacc, $td, $refnum, $wamt, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid}.");
            pettyrec($cusacc, $td, "dt", "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid}.", $wamt, "Account Sale Credit note");
        }
        # Debit bank and credit the account involved
        $tot_post += $VAT;
        writetrans($vatacc, $cusacc, $td, $refnum, $VAT, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT.");
        pettyrec($cusacc, $td, "dt", "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT.", $VAT, "Account Sale Credit note VAT");
        $tot_dif = sprint($tot_post - $TOTAL);
        if ($tot_dif > 0) {
            writetrans($cusacc, $varacc, $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($varacc, $cusacc, $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        }
    }
    $sdate = date("Y-m-d");
    db_connect();
    if ($inv['ctyp'] == 's') {
        # Record the payment on the statement
        $sql = "\r\n\t\t\tINSERT INTO stmnt \r\n\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \r\n\t\t\tVALUES \r\n\t\t\t\t('{$inv['cusid']}', '{$real_noteid}', '-{$TOTAL}','{$td}', 'Non Stock Credit Note, for invoice {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance less)
        $sql = "UPDATE customers SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Update the customer (make balance less)
        $sql = "UPDATE open_stmnt SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Make ledge record
        custledger($inv['cusid'], $stkacc, $td, $real_noteid, "Non Stock Credit note {$real_noteid}", $TOTAL, "c");
        #record entry for age analysis ...
        #this function seems a little ... broken
        //custfCT($TOTAL, $inv['cusid'], $inv['age']);
        #lets rather use the system wide function and send it the invoice transaction date to do the entry for that age
        custCT($TOTAL, $inv['cusid'], $inv['odate']);
    } elseif ($inv['ctyp'] == 'cb') {
        $date = date("Y-m-d");
        # Record the Receipt record
        db_connect();
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accids, amounts,  chrgvats, vats, div,accinv) VALUES ('{$inv['jobid']}', 'withdrawal', '{$td}', '{$inv['cusname']}', 'Nons Stock Credit note for invoice {$inv['invnum']}', '0', '{$TOTAL}', 'no', '', '0', '{$inv['chrgvat']}', '0', '" . USER_DIV . "','{$stkacc}')";
        die($sql);
        $Rslt = db_exec($sql) or errDie("Unable to add bank Receipt to database.", SELF);
    }
    db_connect();
    $sql = "UPDATE hire.hire_nons_invoices SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
    # write note
    $sql = "INSERT INTO hire.hire_nons_inv_notes(invid, invnum, cusname, cusaddr, cusvatno, chrgvat, date, subtot, vat, total, username, prd, notenum, ctyp, remarks, div)";
    $sql .= " VALUES('{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['chrgvat']}', '{$td}', {$SUBTOT}, {$VAT}, {$TOTAL}, '" . USER_NAME . "', '" . PRD_DB . "', '{$real_noteid}', '{$inv['ctyp']}', '{$remarks}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to create template Non-Stock Invoice.", SELF);
    # write note items
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM hire.hire_nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $nstk = pg_fetch_array($stkdRslt);
    }
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\r\n\tVALUES('{$td}', '{$noteid}', '{$real_noteid}', '0', '{$VAT}', '{$TOTAL}', 'nnon', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\r\n\t('{$inv['cusid']}','{$inv['cusname']}','Credit Note: {$real_noteid}, Invoice {$inv['invnum']}','{$td}','" . -sprint($TOTAL - $VAT) . "','-{$VAT}','" . -sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    com_invoice($inv['salespn'], -($TOTAL - $VAT), 0, $inv['invnum'], $td);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $cc = "<script> CostCenter('ct', 'Credit Note', '{$td}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($TOTAL - $VAT) . "', ''); </script>";
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // 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
    db_conn("cubit");
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank information from Cubit.");
    $bank_data = pg_fetch_array($bank_rslt);
    // Retrieve customer information
    db_conn("cubit");
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
    $cust_data = pg_fetch_array($cust_rslt);
    if ($inv['cusid'] == "0") {
        $cust_data['surname'] = $inv['cusname'];
        $cust_data['addr1'] = $inv['cusaddr'];
        $cust_data['paddr1'] = $inv['cusaddr'];
    }
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;\r\n\t";
    // 	$nolr_borders = "
    // 		border-top: 2px solid #000;
    // 		border-left: none;
    // 		border-right: none;
    // 		border-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;
        }
        $vattot = sprint($vattot);
        $amttot = sprint($amttot);
        $details .= "<center>\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='left' rowspan='2'><img src='compinfo/getimg.php' width=230 height=47></td>\r\n\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Credit Note</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t</tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Credit Note No:</b> {$real_noteid}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$inv['invnum']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='center'><font size='4'><b>Credit Note To:</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cust_data['surname']}</b></td>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\r\n\t\t\t\t\t<td>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\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>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$products_out}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$remarks}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$SUBTOT}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$VAT}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$TOTAL}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t<tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\t\t";
    }
    #fix teh date
    $date_arr = explode("-", $date);
    $cdate = "{$date_arr['2']}-{$date_arr['1']}-{$date_arr['0']}";
    // 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);
    if ($template == "invoice-print.php") {
        $OUTPUT = "\r\n\t\t\t<script>\r\n\t\t\t\tCostCenter('ct', 'Credit Note', '{$cdate}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($TOTAL - $VAT) . "', '');\r\n\t\t\t</script>\r\n\t\t\t{$details}";
        require "tmpl-print.php";
    } else {
        $OUTPUT = "\r\n\t\t\t<script>\r\n\t\t\t\tCostCenter('ct', 'Credit Note', '{$cdate}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($TOTAL - $VAT) . "', '');\r\n\t\t\t\tmove(\"{$template}?noteid={$noteid}&type=nonsnote\");\r\n\t\t\t</script>";
        require "template.php";
    }
}
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 cwrite($_GET)
{
    $showvat = TRUE;
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    if (isset($ctyp) && $ctyp == 's') {
        $v->isOk($cusnum, "num", 1, 20, "Invalid customer number.");
    } elseif (isset($ctyp) && $ctyp == 'c') {
        $v->isOk($deptid, "num", 1, 20, "Invalid Department.");
    }
    if (isset($stkaccs)) {
        foreach ($stkaccs as $key => $accid) {
            $v->isOk($accid, "num", 1, 20, "Invalid Item Account number.");
        }
    } else {
        $v->isOk($invid, "num", 0, 0, "Invalid Item Account number.");
    }
    # display errors, if any
    if ($v->isError()) {
        $err = $v->genErrors();
        $err .= "<input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $err;
    }
    db_connect();
    # Get invoice info
    $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);
    $td = $inv['odate'];
    db_connect();
    # cust % bank
    if ($ctyp == 's') {
        $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);
        $details = "\r\n\t\t<tr><td>{$cus['surname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($cus['addr1']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$cus['vatnum']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $cus['surname'];
    } elseif ($ctyp == 'c') {
        $cus['surname'] = $inv['cusname'];
        $cus['addr1'] = $inv['cusaddr'];
        $cus["del_addr1"] = "";
        $cus["paddr1"] = "";
        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);
        $details = "\r\n\t\t<tr><td>{$inv['cusname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($inv['cusaddr']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$inv['cusvatno']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $inv['cusname'];
    } else {
        $cus["del_addr1"] = "";
        $cus["paddr1"] = "";
        $cus['surname'] = $inv['cusname'];
        $cus['addr1'] = $inv['cusaddr'];
        $details = "\r\n\t\t<tr><td>{$inv['cusname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($inv['cusaddr']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$inv['cusvatno']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $inv['cusname'];
    }
    # Begin updates
    $refnum = getrefnum();
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "NO VAT");
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    /* - End Hooks - */
    //lock(2);
    $real_invid = divlastid('inv', USER_DIV);
    //unlock(2);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # Put in product
    $i = 0;
    $page = 0;
    while ($stk = pg_fetch_array($stkdRslt)) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $stkacc = $stk["accid"];
        $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";
        }
        //print $inv['chrgvat'];exit;
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $t = $inv['chrgvat'];
        $VATP = TAX_VAT;
        $hs_acc = qryAccountsNum(1050, 00);
        $hs_acc = $hs_acc["accid"];
        $inv_acc = qryAccountsNum(6350, 00);
        $inv_acc = $inv_acc["accid"];
        # keep records for transactions
        if ($stkacc == $inv_acc) {
            if (!isset($totstkamt[$stkacc])) {
                $totstkamt[$stkacc] = 0;
            }
            $totstkamt[$stkacc] += $cost_prices[$stk["id"]];
            $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
            if ($inv['chrgvat'] == "no") {
                $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
            }
            $totstkamt[$hs_acc] += vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
        } else {
            if (isset($totstkamt[$stkacc])) {
                # Is it stock sold?
                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] = $stk['amt'];
                    $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);
        $inv['chrgvat'] = $t;
        // 		if(isset($totstkamt[$stkacc])){
        // 			$totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat']);
        // 		}else{
        // 			$totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat']);
        // 		}
        $sql = "UPDATE nons_inv_items SET accid = '{$stkacc}' WHERE id = '{$stk['id']}'";
        $sRslt = db_exec($sql);
        if ($stk['vatex'] == 'y') {
            $ex = "#";
        } else {
            //			$ex = "&nbsp;&nbsp;";
            $ex = "";
        }
        $i++;
    }
    /* --- 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", "novat");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    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;
        $hs_acc = qryAccountsNum(1050, 00);
        $hs_acc = $hs_acc["accid"];
        $inv_acc = qryAccountsNum(6350, 00);
        $inv_acc = $inv_acc["accid"];
        $coh_acc = qryAccountsNum(7200, 00);
        $coh_acc = $coh_acc["accid"];
        $cos_acc = qryAccountsNum(2150, 00);
        $cos_acc = $cos_acc["accid"];
        # record transaction from data
        foreach ($totstkamt as $stkacc => $wamt) {
            $use_acc = $coh_acc;
            if ($stkacc == $hs_acc) {
                $use_acc = $coh_acc;
            } else {
                if ($stkacc == $inv_acc) {
                    $use_acc = $cos_acc;
                }
            }
            $tot_post += $wamt;
            writetrans($use_acc, $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$cus['surname']}.");
        }
        # Debit bank and credit the account involved
        if ($VAT != 0) {
            $tot_post += $VAT;
            writetrans($coh_acc, $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$cus['surname']}.");
        }
        $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;
        }
        $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 {$cust['surname']}.");
        }
        if (isset($bankid)) {
            db_connect();
            $bankid += 0;
            $sql = "\r\n\t\t\tINSERT INTO cashbook (bankid, trantype, date, name, descript, cheqnum, \r\n\t\t\t\tamount, vat, chrgvat, banked, accinv, div)\r\n\t\t\tVALUES (\r\n\t\t\t\t\t'{$bankid}', 'deposit', '{$td}', '{$inv['cusname']}', \r\n\t\t\t\t\t'Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}', '0', \r\n\t\t\t\t\t'{$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 {$cust['surname']}.");
        }
        $sdate = date("Y-m-d");
    }
    $tot_post = sprint($tot_post);
    db_connect();
    if ($ctyp == 's') {
        $sql = "\r\n\t\tUPDATE nons_invoices SET balance=total, cusid='{$cusnum}', ctyp='{$ctyp}',\r\n\t\t\tcusname='{$cus['surname']}', cusaddr='{$cus['addr1']}', cusvatno='{$cus['vatnum']}',\r\n\t\t\tdone='y', invnum='{$real_invid}'\r\n\t\tWHERE invid='{$invid}' AND div='" . USER_DIV . "'";
        $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
        /*
        # Record the payment on the statement
        $sql = "
        	INSERT INTO stmnt (
        		cusnum, invid, docref, amount, date, 
        		type, div, allocation_date
        	) VALUES (
        		'$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");
        */
        $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 = "\r\n\t\tUPDATE nons_invoices SET balance=total, cusname = '{$cust['surname']}',\r\n\t\t\taccid = '{$dept['pca']}', ctyp = '{$ctyp}', cusaddr = '{$cust['addr1']}',\r\n\t\t\tdone = 'y', invnum = '{$real_invid}'\r\n\t\tWHERE 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");
        #		}
    }
    db_connect();
    $sql = "\r\n\tINSERT INTO salesrec (edate, invid, invnum, debtacc, vat, total, typ, div)\r\n\tVALUES ('{$inv['odate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$VAT}', \r\n\t\t'{$TOTAL}', 'non', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    com_invoice($inv['salespn'], $TOTAL - $VAT, 0, $real_invid, $inv["odate"]);
    db_conn('cubit');
    if (!isset($cusnum)) {
        $cusnum = 0;
    }
    $Sl = "\r\n\tINSERT INTO sj (cid, name, des, date, exl, vat, inc, div)\r\n\tVALUES ('{$cusnum}', '{$na}', 'Non stock Invoice {$real_invid}', '{$inv['sdate']}',\r\n\t\t'" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Get selected stock in this invoice
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    # $stkdRslt = db_exec($sql);
    $cc = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', ''); </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 = "<tr><td><b>Sales Person:</b> {$inv['salespn']}</td></tr>";
    } else {
        $sp = "";
    }
    if ($inv['chrgvat'] == "yes") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "no") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if ($inv["remarks"] == "") {
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
        $commRslt = db_exec($sql) or errDie("Unable to retrieve the default comments from Cubit.");
        $inv["remarks"] = pg_fetch_result($commRslt, 0);
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // 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);
    #make sure we have a valid bank id for customer
    if (!isset($inv['bankid']) or strlen($inv['bankid']) < 1) {
        $inv['bankid'] = '2';
    }
    // Retrieve the banking information
    db_conn("cubit");
    $sql = "SELECT * FROM bankacct WHERE bankid='{$inv['bankid']}' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank information from Cubit.");
    $bank_data = pg_fetch_array($bank_rslt);
}
function write($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice number.");
    $sndate = mkdate($s_year, $s_month, $s_day);
    if (!checkdate($s_month, $s_day, $s_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    foreach ($ids as $key => $id) {
        $v->isOk($id, "num", 1, 20, "Invalid Item number.");
        //		if (!is_int($qtys[$key])) {
        if (!ctype_digit($qtys[$key])) {
            $v->addError(0, "Invalid Item Quantity.");
        }
        $v->isOk($amts[$key], "float", 1, 20, "Invalid Item amount.");
    }
    $v->isOk($subtot, "float", 1, 20, "Invalid sub-total amount.");
    $v->isOk($vat, "float", 1, 20, "Invalid vat amount.");
    $v->isOk($total, "float", 1, 20, "Invalid total amount.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $err .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $err;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM nons_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);
    # Update xrate
    cus_xrate_update($inv['fcid'], $inv['xrate']);
    xrate_update($inv['fcid'], $inv['xrate'], "invoices", "invid");
    xrate_update($inv['fcid'], $inv['xrate'], "custran", "id");
    db_connect();
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $refnum = getrefnum();
    /*refnum*/
    $real_noteid = divlastid('note', USER_DIV);
    db_connect();
    /* --- Start Products Display --- */
    $td = $sndate;
    # Products layout
    $products = "";
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        $stkacc = $stkd['accid'];
        # keep records for transactions
        // 		if(isset($totstkamt[$stkacc])){
        // 			$totstkamt[$stkacc] += vats($amts[$key], $inv['chrgvat']);
        // 		}else{
        // 			$totstkamt[$stkacc] = vats($amts[$key], $inv['chrgvat']);
        // 		}
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $stkd['vatex'] = "y";
        }
        $t = $inv['chrgvat'];
        $VATP = TAX_VAT;
        $stkacc = $stkd['accid'];
        # keep records for transactions
        if (isset($totstkamt[$stkacc])) {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] += $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] += vats($amts[$key], $inv['chrgvat']);
                $va = sprint($stkd['amt'] - vats($amts[$key], $inv['chrgvat']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        } else {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] = $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] = vats($amts[$key], $inv['chrgvat']);
                $va = sprint($amts[$key] - vats($amts[$key], $inv['chrgvat']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        }
        $f = -vats($amts[$key], $inv['chrgvat']);
        $f = $f * $inv['xrate'];
        $va = $va * $inv['xrate'];
        vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.", $f - $va, -$va);
        $inv['chrgvat'] = $t;
        $sql = "UPDATE nons_inv_items SET rqty = (rqty + '{$qtys[$key]}') WHERE id = '{$stkd['id']}'";
        $sRslt = db_exec($sql);
        $products .= "\n\t\t\t\t\t\t<tr valign='top'>\n\t\t\t\t\t\t\t<td>{$stkd['description']}</td>\n\t\t\t\t\t\t\t<td>{$qtys[$key]}</td>\n\t\t\t\t\t\t\t<td>{$inv['currency']} {$stkd['unitcost']}</td>\n\t\t\t\t\t\t\t<td>{$inv['currency']} {$amts[$key]}</td>\n\t\t\t\t\t\t</tr>";
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($subtot);
    $VAT = sprint($vat);
    $TOTAL = sprint($total);
    $LVAT = sprint($VAT * $inv['xrate']);
    $LTOTAL = sprint($TOTAL * $inv['xrate']);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    /* - End Hooks - */
    # todays date
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    if (pg_numrows($custRslt) < 1) {
        return "<li class='err'>Error : Customer not Found.</li>";
    }
    $cus = pg_fetch_array($custRslt);
    $na = $cus['surname'];
    # 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) {
        return "<li class='err'>Department not Found.</li>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    $wtot = array_sum($totstkamt) + $va;
    $lwtot = sprint($wtot * $inv['xrate']);
    $lva = sprint($va * $inv["xrate"]);
    $tpp = 0;
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        writetrans($stkacc, $dept['debtacc'], $sndate, $refnum, $lwtot, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.");
    }
    if ($lva != 0) {
        writetrans($vatacc, $dept['debtacc'], $sndate, $refnum, $lva, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Vat. Customer {$inv['cusname']}.");
    }
    db_connect();
    # Record the payment on the statement
    $sql = "\n\t\tINSERT INTO stmnt \n\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\tVALUES \n\t\t\t('{$inv['cusid']}', '{$real_noteid}', '-{$wtot}','{$sndate}', 'Non Stock Credit Note, for invoice {$inv['invnum']}', '" . USER_DIV . "', '{$sndate}')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Update the customer (make balance less)
    $sql = "UPDATE customers \n\t\t\tSET balance = (balance - '{$lwtot}'::numeric(13,2)), \n\t\t\t\tfbalance = (fbalance - '{$wtot}'::numeric(13,2)) WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Make ledge record
    custledger($inv['cusid'], $dept['incacc'], $sndate, $real_noteid, "Non Stock Credit note {$real_noteid}", $lwtot, "c");
    frecordCT($wtot, $inv['cusid'], $inv['xrate'], $inv['fcid'], $sndate);
    // custCT($TOTAL, $inv['cusid']);
    db_connect();
    $sql = "UPDATE nons_invoices \n\t\t\tSET balance = (balance - '{$lwtot}'::numeric(13,2)), \n\t\t\t\tfbalance = (fbalance - '{$wtot}'::numeric(13,2)) WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
    # write note
    $sql = "INSERT INTO nons_inv_notes(invid, invnum, cusname, cusaddr, cusvatno, chrgvat, location, currency, date, subtot, vat, total, username, prd, notenum, ctyp, div)";
    $sql .= " VALUES('{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['chrgvat']}', 'int', '{$inv['currency']}', '{$sndate}', '" . sprint($wtot - $va) . "', {$va}, {$wtot}, '" . USER_NAME . "', '" . PRD_DB . "', '{$real_noteid}', '{$inv['ctyp']}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to create template Non-Stock Invoice.", SELF);
    $noteid = pglib_lastid("nons_inv_notes", "noteid");
    # write note items
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $nstk = pg_fetch_array($stkdRslt);
        $sql = "INSERT INTO nons_note_items(noteid, qty, description, amt, unitcost) \n\t\t\t\tVALUES('{$noteid}', '{$qtys[$key]}', '{$nstk['description']}', '{$amts[$key]}', \n\t\t\t\t\t'{$nstk['unitcost']}')";
        $stkdRslt = db_exec($sql);
    }
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\tVALUES('{$sndate}', '{$noteid}', '{$real_noteid}', '0', '{$lva}', '{$lwtot}', 'nnon', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    db_conn('cubit');
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t('{$inv['cusid']}','{$na}','Credit note: {$real_noteid}, Non-stock International Invoice {$inv['invnum']} ','{$sndate}','" . -sprint($lwtot - $lva) . "','-{$lva}','" . -sprint($lwtot) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* -- Format the remarks boxlet -- */
    $inv["remarks"] = "<table border=1><tr><td>Remarks:<br>{$inv['remarks']}</td></tr></table>";
    $cc = "<script> CostCenter('ct', 'Credit Note', '{$sndate}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($LTOTAL - $LVAT) . "', ''); </script>";
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t{$cc}\n\t\t\t\t\t<center>\n\t\t\t\t\t<h2>Credit Note</h2>\n\t\t\t\t\t<table cellpadding='0' cellspacing='4' border='0' width='750'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>{$inv['cusname']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>" . nl2br($inv['cusaddr']) . "</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>(Vat No. {$inv['cusvatno']})</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='top' width='30%'>\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\tVat No. " . COMP_VATNO . "\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td width='20%'><img src='compinfo/getimg.php' width=230 height=47></td>\n\t\t\t\t\t\t\t<td valign='bottom' align='right' width='20%'>\n\t\t\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border=1 bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Credit Note No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$real_noteid}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>Date</b></td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$sndate}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='4'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border=1 width=100% bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th width='65%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t\t\t\t<th width='10%'>QTY</th>\n\t\t\t\t\t\t\t\t\t\t<th width='10%'>UNIT PRICE</th>\n\t\t\t\t\t\t\t\t\t\t<th width='10%'>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>{$inv['remarks']}</td>\n\t\t\t\t\t\t\t<td align='right' colspan='3'>\n\t\t\t\t\t\t\t\t<table cellpadding='5' cellspacing='0' border=1 width=50% bordercolor='#000000'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$SUBTOT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td><b>VAT @ " . TAX_VAT . "%</b></td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$VAT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th><b>GRAND TOTAL<b></th>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</center>";
    $OUTPUT = $details;
    require "tmpl-print.php";
}
function cwrite($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $v->isOk($cusnum, "num", 1, 20, "Invalid customer number.");
    if (isset($stkaccs)) {
        foreach ($stkaccs as $key => $accid) {
            $v->isOk($accid, "num", 1, 20, "Invalid Item Account number.");
        }
    } else {
        $v->isOk($invid, "num", 0, 0, "Invalid Item Account 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 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);
    # 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>";
    }
    $td = $inv['sdate'];
    $currs = getSymbol($inv['fcid']);
    # Update xrate
    cus_xrate_update($inv['fcid'], $inv['xrate']);
    xrate_update($inv['fcid'], $inv['xrate'], "invoices", "invid");
    xrate_update($inv['fcid'], $inv['xrate'], "custran", "id");
    db_connect();
    # cust
    $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);
    $details = "\n\t<tr><td>{$cus['surname']}</td></tr>\n\t<tr><td>" . nl2br($cus['addr1']) . "</td></tr>\n\t<tr><td>{$cus['vatnum']}</td></tr>";
    $na = $cus['surname'];
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $refnum = getrefnum();
    /*refnum*/
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "non");
    /* - End Hooks - */
    $real_invid = divlastid('inv', USER_DIV);
    db_connect();
    # Put in product
    while ($stk = pg_fetch_array($stkdRslt)) {
        $stkacc = $stkaccs[$stk['id']];
        # keep records for transactions
        // 		if(isset($totstkamt[$stkacc])){
        // 			$totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat']);
        // 		}else{
        // 			$totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat']);
        // 		}
        $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";
        }
        //print $inv['chrgvat'];exit;
        $t = $inv['chrgvat'];
        $VATP = $vd['vat_amount'];
        # keep records for transactions
        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'] * $VATP / 100);
                }
            }
        } else {
            if ($stk['vatex'] == "y") {
                $totstkamt[$stkacc] = $stk['amt'];
                $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'] * $VATP / 100);
                }
            }
        }
        $f = vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
        $f = $f * $inv['xrate'];
        $va = $va * $inv['xrate'];
        vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock Sales, invoice No.{$real_invid}", $f + $va, $va);
        $inv['chrgvat'] = $t;
        $sql = "UPDATE nons_inv_items SET accid = '{$stkacc}' WHERE id = '{$stk['id']}'";
        $sRslt = db_exec($sql);
        $products .= "<tr valign=top><td>{$stk['description']}</td><td>{$stk['qty']}</td><td>{$inv['currency']}  {$stk['unitcost']}</td><td>{$inv['currency']} {$stk['amt']}</td></tr>";
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $LVAT = sprint($VAT * $inv['xrate']);
    $LTOTAL = sprint($TOTAL * $inv['xrate']);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "non");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    # 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);
    }
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        # Debit Customer and Credit stock
        writetrans($dept['debtacc'], $stkacc, $td, $refnum, $wamt * $inv['xrate'], "Non-Stock Sales on invoice No.{$real_invid} customer {$cus['surname']}.");
    }
    # Debit bank and credit the account involved
    writetrans($dept['debtacc'], $vatacc, $td, $refnum, $LVAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$cus['surname']}.");
    $sdate = date("Y-m-d");
    db_connect();
    $sql = "UPDATE nons_invoices SET cusid = '{$cusnum}', 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\tINSERT INTO stmnt \n\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\tVALUES \n\t\t\t('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}','{$inv['sdate']}', '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 + '{$LTOTAL}'::numeric(13,2)), fbalance = (fbalance + '{$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, $dept['incacc'], $td, $real_invid, "Non Stock Invoice No. {$real_invid}", $LTOTAL, "d");
    frecordDT($TOTAL, $cusnum, $inv['xrate'], $inv['fcid'], $inv['sdate']);
    db_connect();
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\tVALUES('{$inv['sdate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$LVAT}', '{$LTOTAL}', '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('{$cusnum}','{$na}','Non-stock International Invoice {$real_invid}','{$inv['sdate']}','" . sprint($LTOTAL - $LVAT) . "','{$LVAT}','" . sprint($LTOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Get selected stock in this invoice
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    # $stkdRslt = db_exec($sql);
    /* -- Format the remarks boxlet -- */
    $inv["remarks"] = "<table border=1><tr><td>Remarks:<br>{$inv['remarks']}</td></tr></table>";
    $cc = "<script> CostCenter('dt', 'Sales', '{$td}', 'Non Stock Invoice No.{$real_invid}', '" . ($LTOTAL - $LVAT) . "', ''); </script>";
    if ($inv['chrgvat'] == "yes") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "no") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t<center>\n\t\t\t\t{$cc}\n\t\t\t\t<h2>Tax Invoice</h2>\n\t\t\t\t<table cellpadding='0' cellspacing='4' border=0 width='750'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t{$details}\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td valign='top' width='30%'>\n\t\t\t\t\t\t\t" . COMP_NAME . "<br>\n\t\t\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t\t\t" . COMP_TEL . "<br>\n\t\t\t\t\t\t\t" . COMP_FAX . "<br>\n\t\t\t\t\t\t\tReg No. " . COMP_REGNO . "<br>\n\t\t\t\t\t\t\tVAT No. " . COMP_VATNO . "\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td width='20%'><img src='compinfo/getimg.php' width='230' height='47'></td>\n\t\t\t\t\t\t<td valign='bottom' align='right' width='20%'>\n\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<tr>\n\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<td valign='center'>{$real_invid}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>Proforma Inv No.</b></td>\n\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['docref']}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\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<td valign='center'>{$inv['sdate']}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>VAT</b></td>\n\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['chrgvat']}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t" . TBL_BR . "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='4'>\n\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<tr>\n\t\t\t\t\t\t\t\t\t<th width='65%'>DESCRIPTION</th>\n\t\t\t\t\t\t\t\t\t<th width='10%'>QTY</th>\n\t\t\t\t\t\t\t\t\t<th width='10%'>UNIT PRICE</th>\n\t\t\t\t\t\t\t\t\t<th width='10%'>AMOUNT</th>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t{$products}\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>{$inv['remarks']}</td>\n\t\t\t\t\t\t<td>" . BNK_BANKDET . "</td>\n\t\t\t\t\t\t<td align='right' colspan='2'>\n\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<tr>\n\t\t\t\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$SUBTOT}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td><b>VAT @ " . TAX_VAT . "%</b></td>\n\t\t\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$VAT}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\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<td align='right'>{$inv['currency']} {$TOTAL}</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t" . TBL_BR . "\n\t\t\t\t</table>\n\t\t\t\t</center>\n\t\t\t";
    $OUTPUT = $details;
    require "tmpl-print.php";
}
function cwrite($_GET)
{
    $showvat = TRUE;
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    if (isset($ctyp) && $ctyp == 's') {
        $v->isOk($cusnum, "num", 1, 20, "Invalid customer number.");
    } elseif (isset($ctyp) && $ctyp == 'c') {
        $v->isOk($deptid, "num", 1, 20, "Invalid Department.");
    }
    if (isset($stkaccs)) {
        foreach ($stkaccs as $key => $accid) {
            $v->isOk($accid, "num", 1, 20, "Invalid Item Account number.");
        }
    } else {
        $v->isOk($invid, "num", 0, 0, "Invalid Item Account number.");
    }
    # display errors, if any
    if ($v->isError()) {
        $err = $v->genErrors();
        $err .= "<input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $err;
    }
    db_connect();
    # Get invoice info
    $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);
    $td = $inv['odate'];
    db_connect();
    # cust % bank
    if ($ctyp == 's') {
        $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);
        $details = "\r\n\t\t<tr><td>{$cus['surname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($cus['addr1']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$cus['vatnum']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $cus['surname'];
    } elseif ($ctyp == 'c') {
        $cus['surname'] = $inv['cusname'];
        $cus['addr1'] = $inv['cusaddr'];
        $cus["del_addr1"] = "";
        $cus["paddr1"] = "";
        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);
        $details = "\r\n\t\t<tr><td>{$inv['cusname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($inv['cusaddr']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$inv['cusvatno']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $inv['cusname'];
    } else {
        $cus["del_addr1"] = "";
        $cus["paddr1"] = "";
        $cus['surname'] = $inv['cusname'];
        $cus['addr1'] = $inv['cusaddr'];
        $details = "\r\n\t\t<tr><td>{$inv['cusname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($inv['cusaddr']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$inv['cusvatno']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $inv['cusname'];
    }
    # Begin updates
    $refnum = getrefnum();
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "NO VAT");
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    /* - End Hooks - */
    //lock(2);
    $real_invid = divlastid('inv', USER_DIV);
    //unlock(2);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # Put in product
    $i = 0;
    $page = 0;
    while ($stk = pg_fetch_array($stkdRslt)) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $stkacc = $stkaccs[$stk['id']];
        $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";
        }
        //print $inv['chrgvat'];exit;
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $t = $inv['chrgvat'];
        $VATP = TAX_VAT;
        # keep records for transactions
        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] = $stk['amt'];
                $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);
        if ($stk["asset_id"] > 0) {
            $asset_vat[$stk["id"]] = $va;
        }
        $inv['chrgvat'] = $t;
        // 		if(isset($totstkamt[$stkacc])){
        // 			$totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat']);
        // 		}else{
        // 			$totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat']);
        // 		}
        $sql = "UPDATE nons_inv_items SET accid = '{$stkacc}' WHERE id = '{$stk['id']}'";
        $sRslt = db_exec($sql);
        if ($stk['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        $products[$page][] = "\r\n\t\t\t<tr valign=top>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$stk['description']}&nbsp;</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>{$stk['qty']}&nbsp;</td>\r\n\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stk['unitcost']}&nbsp;</td>\r\n\t\t\t\t<td align='right'>" . CUR . " {$stk['amt']}&nbsp;</td>\r\n\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][] = "\r\n\t \t\t\t<tr>\r\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t \t\t\t\t<td>&nbsp;</td>\r\n\t \t\t\t</tr>";
        }
    }
    /* --- 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", "novat");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    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.</li>";
            $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.</li>";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $tpp = 0;
        # 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 {$cus['surname']}.");
        }
        # 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 {$cus['surname']}.");
        }
        $sdate = date("Y-m-d");
        $asset_dtacc = $dept["debtacc"];
    } else {
        if (!isset($accountc)) {
            $accountc = 0;
        }
        if (!isset($dept['pca'])) {
            $accountc += 0;
            $dept['pca'] = $accountc;
            $dept['debtacc'] = $accountc;
        }
        if (isset($bankid)) {
            $dept['pca'] = $BA;
        }
        $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 {$cust['surname']}.");
        }
        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 {$cust['surname']}.");
        }
        $sdate = date("Y-m-d");
        $asset_dtacc = $dept["pca"];
    }
    $tot_post = sprint($tot_post);
    db_connect();
    if ($ctyp == 's') {
        $sql = "UPDATE nons_invoices SET balance = total, cusid = '{$cusnum}', ctyp = '{$ctyp}', cusname = '{$cus['surname']}', 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 = "INSERT INTO stmnt(cusnum, invid, docref, amount, date, type, div) VALUES('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}','{$inv['odate']}', 'Non-Stock Invoice', '" . USER_DIV . "')";
        $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);
        $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, cusname = '{$cust['surname']}', accid = '{$dept['pca']}', ctyp = '{$ctyp}', cusaddr = '{$cust['addr1']}', 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}");
        }
    }
    $sql = "SELECT * FROM cubit.nons_inv_items WHERE invid='{$invid}'";
    $nii_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
    while ($nii_data = pg_fetch_array($nii_rslt)) {
        if ($nii_data["asset_id"] > 0) {
            $asset_vatamt = $asset_vat[$nii_data["id"]];
            if ($inv['chrgvat'] == "yes") {
                $asset_amt = sprint($nii_data["amt"] - $asset_vatamt);
            } else {
                if ($inv['chrgvat'] == "no") {
                    $asset_amt = $nii_data["amt"];
                }
            }
            asset_accounting($nii_data["asset_id"], $nii_data["qty"], $refnum, $asset_amt, $asset_vatamt, $inv["odate"], $invid, $asset_dtacc, $nii_data["accid"]);
        }
    }
    db_connect();
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\r\n\tVALUES('{$inv['odate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$VAT}', '{$TOTAL}', 'non', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    com_invoice($inv['salespn'], $TOTAL - $VAT, 0, $real_invid, $inv["odate"]);
    db_conn('cubit');
    if (!isset($cusnum)) {
        $cusnum = 0;
    }
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\r\n\t('{$cusnum}','{$na}','Non stock Invoice {$real_invid}','{$inv['sdate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Get selected stock in this invoice
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    # $stkdRslt = db_exec($sql);
    $date = date("d-m-Y");
    $cc = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', ''); </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 = "<tr><td><b>Sales Person:</b> {$inv['salespn']}</td></tr>";
    } else {
        $sp = "";
    }
    if ($inv['chrgvat'] == "yes") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "no") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if ($inv["remarks"] == "") {
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
        $commRslt = db_exec($sql) or errDie("Unable to retrieve the default comments from Cubit.");
        $inv["remarks"] = pg_fetch_result($commRslt, 0);
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // 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
    db_conn("cubit");
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank information from Cubit.");
    $bank_data = pg_fetch_array($bank_rslt);
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;\r\n\t";
    // 	$nolr_borders = "
    // 		border-top: 2px solid #000;
    // 		border-left: none;
    // 		border-right: none;
    // 		border-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;
        }
        $details .= "<center>\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='left' rowspan='2'><img src='compinfo/getimg.php' width=230 height=47></td>\r\n\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Invoice</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t</tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$real_invid}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$sp}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='center'><font size='4'><b>Tax Invoice To:</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cus['surname']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cus["addr1"]) . "&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cus["paddr1"]) . "&nbsp;</td>\r\n\t\t\t\t\t<td>" . nl2br($cus["del_addr1"]) . "&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\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>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$products_out}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$inv['remarks']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['subtot']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['vat']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['total']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t<tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\t\t";
    }
    // Retrieve the 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 template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        $OUTPUT = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', '');</script>\r\n\t\t\t{$details}";
        require "tmpl-print.php";
    } else {
        $OUTPUT = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', '');\r\n\t\tmove (\"{$template}?invid={$inv['invid']}&type=nons\");\r\n\t\t</script>";
        require "template.php";
    }
}
function cwrite($_GET)
{
    $showvat = TRUE;
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    if (isset($ctyp) && $ctyp == 's') {
        $v->isOk($cusnum, "num", 1, 20, "Invalid customer number.");
    } elseif (isset($ctyp) && $ctyp == 'c') {
        $v->isOk($deptid, "num", 1, 20, "Invalid Department.");
    }
    // 	if(isset($stkaccs)){
    // 		foreach($stkaccs as $key => $accid){
    // 			$v->isOk ($accid, "num", 1, 20, "Invalid Item Account number.");
    // 		}
    // 	}else{
    // 		$v->isOk ($invid, "num", 0, 0, "Invalid Item Account number.");
    // 	}
    if (!isset($description) && !count($description)) {
        $v->addError(0, "No items selected.");
    }
    # display errors, if any
    if ($v->isError()) {
        $err = $v->genErrors();
        $err .= "<input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $err;
    }
    // Update descriptions
    foreach ($description as $key => $value) {
        $sql = "UPDATE hire.hire_nons_inv_items SET description='{$value}' WHERE id='{$key}'";
        db_exec($sql) or errDie("Unable to update descriptions.");
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM cubit.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);
    $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>";
    }
    db_connect();
    # cust % bank
    if ($ctyp == 's') {
        $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);
        $details = "\r\n\t\t<tr><td>{$cus['surname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($cus['addr1']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$cus['vatnum']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $cus['surname'];
    } elseif ($ctyp == 'c') {
        $cus['surname'] = $inv['cusname'];
        $cus['addr1'] = $inv['cusaddr'];
        $cus["del_addr1"] = "";
        $cus["paddr1"] = "";
        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);
        $details = "\r\n\t\t<tr><td>{$inv['cusname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($inv['cusaddr']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$inv['cusvatno']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $inv['cusname'];
    } else {
        $cus["del_addr1"] = "";
        $cus["paddr1"] = "";
        $cus['surname'] = $inv['cusname'];
        $cus['addr1'] = $inv['cusaddr'];
        $details = "\r\n\t\t<tr><td>{$inv['cusname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($inv['cusaddr']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$inv['cusvatno']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $inv['cusname'];
    }
    # Begin updates
    $refnum = getrefnum();
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "NO VAT");
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    /* - End Hooks - */
    //lock(2);
    $real_invid = divlastid('inv', USER_DIV);
    //unlock(2);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.");
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM hire.hire_nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # Put in product
    $i = 0;
    $page = 0;
    while ($stk = pg_fetch_array($stkdRslt)) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $sql = "SELECT basis, hours, weeks,\r\n\t\t\t\t\textract('epoch' from from_date) AS e_from,\r\n\t\t\t\t\textract('epoch' from to_date) AS e_to\r\n\t\t\t\tFROM hire.hire_invitems\r\n\t\t\t\tWHERE id='{$stk['item_id']}'";
        $hired_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
        $hired_data = pg_fetch_array($hired_rslt);
        // --------------------------------------------------------------------
        $sql = "SELECT * FROM cubit.assets WHERE id='{$stk['asset_id']}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
        $asset_data = pg_fetch_array($asset_rslt);
        $sql = "SELECT traddisc FROM hire.hire_invoices WHERE invid='{$inv['hire_invid']}'";
        $disc_rslt = db_exec($sql) or errDie("Unable to retrieve discount.");
        $traddisc = pg_fetch_result($disc_rslt, 0);
        $sql = "UPDATE hire.assets_hired SET return_time=CURRENT_TIMESTAMP\r\n\t\t\t\tWHERE item_id='{$stk['item_id']}'";
        db_exec($sql) or errDie("Unable to update hired assets.");
        if (isset($monthly) && !$monthly) {
            if (!isSerialized($asset_data["id"])) {
                $new_qty = $asset_data["serial2"] + $stk["qty"];
                $sql = "UPDATE cubit.assets SET serial2='{$new_qty}' WHERE id='{$stk['asset_id']}'";
                db_exec($sql) or errDie("Unable to update assets.");
            }
            $hire_num = getHirenum($inv["hire_invid"]);
            if ($hire_num) {
                $sql = "SELECT * FROM hire.hire_invoices WHERE invnum='{$hire_num}'";
                $hi_rslt = db_exec($sql) or errDie("Unable to retrieve invoices.");
                while ($hi_data = pg_fetch_array($hi_rslt)) {
                    $sql = "DELETE FROM hire.hire_invitems\r\n\t\t\t\t\t\t\tWHERE invid='{$hi_data['invid']}'";
                    db_exec($sql) or errDie("Unable to remove old items.");
                }
                $sql = "DELETE FROM hire.hire_invoices WHERE invnum='{$hire_num}'";
                db_exec($sql) or errDie("Unable to remove invoices.");
                $sql = "DELETE FROM hire.monthly_invoices WHERE invnum='{$hire_num}'";
                db_exec($sql) or errDie("Unable to remove invoices.");
                $sql = "UPDATE hire.assets_hired SET return_time=current_timestamp\r\n\t\t\t\t\t\tWHERE invnum='{$hire_num}'";
                db_exec($sql) or errDie("Unable to update return time.");
            }
            $sql = "DELETE FROM hire.hire_invitems WHERE id='{$stk['item_id']}'";
            db_exec($sql) or errDie("Unable to remove returned item.");
            $sql = "DELETE FROM hire.monthly_invitems WHERE item_id='{$stk['item_id']}'";
            db_exec($sql) or errDie("Unable to remove old items.");
            $sql = "UPDATE hire.assets_hired SET return_time=current_timestamp\r\n\t\t\t\t\tWHERE item_id='{$stk['item_id']}'";
            db_exec($sql) or errDie("Unable to remove old items.");
            $sql = "DELETE FROM hire.monthly_invoices\r\n\t\t\t\t\tWHERE invid='{$inv['hire_invid']}'";
            db_exec($sql) or errDie("Unable to remove monthly.");
            $sql = "DELETE FROM hire.hire_invitems\r\n\t\t\t\t\tWHERE invid='{$inv['hire_invid']}'";
            db_exec($sql) or errDie("Unable to remove monthly.");
        }
        $stkacc = $stkaccs[$stk['id']];
        $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";
        }
        //print $inv['chrgvat'];exit;
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $t = $inv['chrgvat'];
        $VATP = TAX_VAT;
        # keep records for transactions
        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] = $stk['amt'];
                $inv['chrgvat'] = "";
                $va = 0;
            } else {
                // Seems only this one is used for our hiring purposes
                $totstkamt[$stkacc] = $stk['amt'];
                $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                }
            }
        }
        // 		if(isset($totstkamt[$stkacc])){
        // 			$totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat']);
        // 		}else{
        // 			$totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat']);
        // 		}
        $sql = "UPDATE hire.hire_nons_inv_items SET accid = '{$stkacc}' WHERE id = '{$stk['id']}'";
        $sRslt = db_exec($sql);
        if ($stk['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        // 		$time_from = "$from_day-$from_month-$from_year $from_hour:$from_minute";
        // 		$time_to = "$to_day-$to_month-$to_year $to_hour:$to_minute";
        if ($hired_data["weeks"]) {
            $hired_days = sprint($hired_data["weeks"] * 7);
        } elseif ($hired_data["e_from"] > 0) {
            $secs = $hired_data["e_to"] - $hired_data["e_from"];
            $hired_days = sprint($secs / (60 * 60 * 24) + 1);
        } elseif ($hired_data["hours"]) {
            $secs = $hired_data["hours"] / 24;
            $hired_days = sprint($secs);
        } else {
            $hired_days = 0;
        }
        $hired_days = floor($hired_days);
        switch ($hired_data["basis"]) {
            case "per_hour":
                $basis = "Hourly";
                $basis_s = "hour";
                $basis_p = "per_hour";
                break;
            case "per_day":
                $basis = "Daily";
                $basis_s = "day";
                $basis_p = "per_day";
                break;
            case "per_week":
                $basis = "Weekly";
                $basis_s = "week";
                $basis_p = "per_week";
        }
        $rate = basisPrice($inv["cusnum"], $stk["asset_id"], $basis_p);
        if (empty($rate)) {
            $rate = "0.00";
        }
        $sql = "UPDATE hire.hire_nons_inv_items SET hired_days='{$hired_days}',\r\n\t\t\trate='{$rate}' WHERE id='{$stk['id']}'";
        db_exec($sql) or errDie("Unable to save to items.");
        $products[$page][] = "<tr valign=top>\r\n\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$stk['description']}&nbsp;</td>\r\n\t\t\t<td style='border-right: 2px solid #000'>{$stk['qty']}&nbsp;</td>\r\n\t\t\t<td style='border-right: 2px solid #000'>{$hired_days}&nbsp;</td>\r\n\t\t\t<td align='right' style='border-right: 2px solid #000'>({$basis}) " . sprint($rate) . " &nbsp;</td>\r\n\t\t\t<td align='right'>" . CUR . sprint($stk["amt"]) . "&nbsp;</td>\r\n\t\t</tr>";
        $i++;
    }
    $inv['chrgvat'] = $t;
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "<tr>\r\n \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n  \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n \t\t\t\t<td>&nbsp;</td>\r\n \t\t\t</tr>";
        }
    }
    $sql = "INSERT INTO hire.hires (inv_id, user_id, cust_id, from_time)\r\n\t\t\tVALUES ('{$inv['invid']}', " . USER_ID . ", '{$inv['cusnum']}', CURRENT_TIMESTAMP)";
    db_exec($sql) or errDie("Unable to create new hire.");
    /* --- 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", "novat");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    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.</li>";
            $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.</li>";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $tpp = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            $wamt += $inv["delivery"] / count($totstkamt);
            $wamt -= $inv["discount"] / count($totstkamt);
            # Debit Customer and Credit stock
            $tot_post += $wamt;
            writetrans($dept['debtacc'], $stkacc, $td, $refnum, $SUBTOT, "Non-Stock Sales on invoice No.{$real_invid} customer {$cus['surname']}.");
        }
        # 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 {$cus['surname']}.");
        }
        $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;
        }
        $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
            $wamt += $inv["delivery"] / count($totstkamt);
            $tot_post += $wamt;
            writetrans($dept['pca'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$cust['surname']}.");
        }
        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 cubit.hire_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 {$cust['surname']}.");
        }
        $sdate = date("Y-m-d");
    }
    $tot_post = sprint($tot_post);
    db_connect();
    if ($ctyp == 's') {
        $sql = "UPDATE cubit.nons_invoices SET cusid = '{$cusnum}', ctyp = '{$ctyp}', cusname = '{$cus['surname']}', cusaddr = '{$cus['addr1']}', cusvatno = '{$cus['vatnum']}', done = 'y', invnum = '{$real_invid}', balance = total 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 = "INSERT INTO stmnt(cusnum, invid, docref, amount, date, type, div) VALUES('$cusnum', '$real_invid', '$inv[docref]', '$TOTAL','$inv[odate]', 'Non-Stock Invoice', '".USER_DIV."')";
        // 		$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);
        //
        // 		$tot_dif=sprint($tot_post-$TOTAL);
        if (!isset($tot_dif)) {
            $tot_dif = 0;
        }
        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 cubit.nons_invoices SET balance=total, cusname = '{$cust['surname']}', accid = '{$dept['pca']}', ctyp = '{$ctyp}', cusaddr = '{$cust['addr1']}', 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}");
        }
    }
    db_connect();
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\r\n\tVALUES('{$inv['odate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$VAT}', '{$TOTAL}', 'non', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    com_invoice($inv['salespn'], $TOTAL - $VAT, 0, $real_invid, $inv["odate"]);
    db_conn('cubit');
    if (!isset($cusnum)) {
        $cusnum = 0;
    }
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\r\n\t('{$cusnum}','{$na}','Non stock Invoice {$real_invid}','{$inv['sdate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    // Customer Statement -----------------------------------------------------
    # Record the payment on the statement
    $sql = "INSERT INTO stmnt(cusnum, invid, docref, amount, date, type, div)\r\n\t\t\tVALUES('{$inv['cusnum']}', '{$inv['invid']}', '{$inv['invnum']}', '{$TOTAL}',\r\n\t\t\t\t'{$inv['odate']}', 'Hire Invoice H{$real_invid}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record");
    # Record the payment on the statement
    $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance,\r\n\t\t\t\tdate, type, div)\r\n\t\t\tVALUES ('{$inv['cusnum']}', '{$inv['invid']}', '{$inv['invnum']}', '{$TOTAL}',\r\n\t\t\t\t'{$TOTAL}', '{$inv['odate']}', 'Hire Invoice no H{$real_invid}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record.");
    # Update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$TOTAL}'::numeric(13,2))\r\n\t\t\tWHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $stkacc = qryAccountsName("Hire Sales");
    $stkacc = $stkacc["accid"];
    # Make ledger record
    custledger($inv["cusnum"], $stkacc, $inv["odate"], $inv["invid"], "Hire Invoice No. H{$real_invid}", $TOTAL, "d");
    custDT($TOTAL, $inv["cusnum"], $inv["odate"]);
    // ------------------------------------------------------------------------
    # Get selected stock in this invoice
    $sql = "SELECT * FROM hire.hire_nons_inv_items\r\n\t\t\tWHERE invid='{$invid}' AND div='" . USER_DIV . "'";
    $item_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
    $item_count = pg_num_rows($item_rslt);
    $totamt = 0;
    while ($item_data = pg_fetch_array($item_rslt)) {
        $totamt += $item_data["amt"];
        $sql = "SELECT * FROM cubit.assets WHERE id='{$item_data['asset_id']}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
        $asset_data = pg_fetch_array($asset_rslt);
        $discount = $item_data["amt"] / 100 * $traddisc;
        // Add up revenue
        $sql = "INSERT INTO hire.revenue (group_id, asset_id, total, discount,\r\n\t\t\t\t\thire_invnum, inv_invnum, cusname)\r\n\t\t\t\tVALUES ('{$asset_data['grpid']}', '{$item_data['asset_id']}',\r\n\t\t\t\t\t'{$item_data['amt']}', '{$discount}', '{$hirenum}',\r\n\t\t\t\t\t'{$real_invid}', '{$inv['cusname']}')";
        db_exec($sql) or errDie("Unable to update revenue");
        $sql = "INSERT INTO cubit.nons_inv_items (invid, qty, description,\r\n\t\t\tdiv, amt, unitcost, vatex, accid, asset_id)\r\n\t\tVALUES ('{$invid}', '{$item_data['qty']}',\r\n\t\t\t'{$item_data['description']}', '{$item_data['div']}', '{$item_data['amt']}',\r\n\t\t\t'{$item_data['amt']}',  '2', '{$item_data['accid']}', '{$item_data['asset_id']}')";
        db_exec($sql) or errDie("Unable to add non stock items.");
        $sql = "UPDATE hire.assets_hired SET return_time=CURRENT_TIMESTAMP,\r\n\t\t\t\t\tinv_invnum='{$real_invid}', value='{$item_data['amt']}'\r\n\t\t\t\tWHERE item_id='{$item_data['item_id']}'";
        db_exec($sql) or errDie("Unable to record asset return time.");
    }
    // Add the delivery discount to the total revenue
    if ($inv["delivery"]) {
        $discount = $inv["delivery"] / 100 * $traddisc;
        $sql = "INSERT INTO hire.revenue (discount)\r\n\t\t\t\tVALUES ('{$discount}')";
        db_exec($sql) or errDie("Unable to update revenue");
    }
    $cc = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', ''); </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 = "<tr><td><b>Sales Person:</b> {$inv['salespn']}</td></tr>";
    } else {
        $sp = "";
    }
    if ($inv['chrgvat'] == "yes") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "no") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if ($inv["remarks"] == "") {
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
        $commRslt = db_exec($sql) or errDie("Unable to retrieve the default comments from Cubit.");
        $inv["remarks"] = pg_fetch_result($commRslt, 0);
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // 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
    db_conn("cubit");
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank information from Cubit.");
    $bank_data = pg_fetch_array($bank_rslt);
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;\r\n\t";
    // 	$nolr_borders = "
    // 		border-top: 2px solid #000;
    // 		border-left: none;
    // 		border-right: none;
    // 		border-bottom: none;
    // 	";
    $sql = "UPDATE hire.hire_invoices SET done='y', delivery='0.00'\r\n\t\t\tWHERE invnum='" . getHirenum($inv["hire_invid"]) . "'";
    db_exec($sql) or errDie("Unable to update invoices.");
    vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock Sales, invoice No.{$real_invid}", $TOTAL, $inv["vat"]);
    $details = "";
    $SUBTOT = sprint($totamt);
    for ($i = 0; $i <= $page; $i++) {
        if ($monthly) {
            $monthly_out = "\r\n\t\t\t<tr>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>Invoiced to date " . date("d-m-Y") . "</td>\r\n\t\t\t</tr>";
        } else {
            $monthly_out = "";
        }
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $details .= "<center>\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='left' rowspan='2'><img src='../compinfo/getimg.php' width='230' height='47'></td>\r\n\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Invoice</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t</tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$real_invid}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Hire No:</b> {$hirenum}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$sp}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='center'><font size='4'><b>Tax Invoice To:</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cus['surname']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cus["addr1"]) . "&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cus["paddr1"]) . "&nbsp;</td>\r\n\t\t\t\t\t<td>" . nl2br($cus["del_addr1"]) . "&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>No of Days</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Rate</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$products_out}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$inv['remarks']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$SUBTOT}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>Delivery</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['delivery']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>Discount</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['discount']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['vat']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['total']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t<tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$monthly_out}\r\n\t\t\t</table>\r\n\t\t</table>\r\n\t\t";
    }
    $amt = $pcash + $pcheque + $pcc;
    $_POST["amt"] = $amt;
    $_POST["date"] = $inv["odate"];
    recvpayment_write();
    $sql = "UPDATE cubit.nons_invoices SET cash='{$pcash}' WHERE invid='{$inv['invid']}'";
    db_exec($sql) or errDie("Unable to update cash value.");
    pglib_transaction("COMMIT");
    // Retrieve the 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 template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        $OUTPUT = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', '');</script>\r\n\t\t\t{$details}";
        require "../tmpl-print.php";
    } else {
        $OUTPUT = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', '');\r\n\t\tmove (\"../{$template}?invid={$inv['invid']}&type=nons\");\r\n\t\t</script>";
        require "template.php";
    }
}