function add($err = "")
{
    extract($_POST);
    if (!isset($bankid)) {
        $bankid = getdSetting("BANK_DET");
    }
    $banks = qryBankAcct();
    if ($banks->num_rows() < 1) {
        return "<li class=err> There Are No Bank Accounts on Cubit.";
    }
    $bank = "<select name='bankid'>";
    while ($acc = $banks->fetch_array()) {
        if ($acc['bankid'] == $bankid) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $bank .= "<option value='{$acc['bankid']}' {$sel}>({$acc['acctype']}) {$acc['accname']} - {$acc['bankname']}</option>";
    }
    $bank .= "</select>";
    $OUT = "\n\t<h3>Banking Details Account</h3>\n\t{$err}\n\t<table " . TMPL_tblDflts . ">\n\t<form action='" . SELF . "' method='post' name='form'>\n\t<input type='hidden' name='key' value='confirm' />\n\t<tr>\n\t\t<th>Field</th>\n\t\t<th>Value</th>\n\t</tr>\n\t<tr class='bg-even'>\n\t\t<td>Bank Account</td>\n\t\t<td valign='center'>{$bank}</td>\n\t</tr>\n\t" . TBL_BR . "\n\t<tr>\n\t\t<td></td>\n\t\t<td valign='center' align='right'><input type='submit' value='Confirm &raquo' /></td>\n\t</tr>\n\t</table>" . mkQuickLinks();
    return $OUT;
}
function genpdf($quoid)
{
    global $_GET;
    extract($_GET);
    global $set_mainFont;
    $showvat = TRUE;
    $pdf =& new Cezpdf();
    $pdf->selectFont($set_mainFont);
    // Validate
    require_lib("validate");
    $v = new Validate();
    $v->isOk($quoid, "num", 1, 20, "Invalid quote number.");
    // Any errors?
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>{$e['msg']}</li>";
        }
        $OUTPUT = $confirm;
        require "../template.php";
    }
    // Invoice info
    db_conn("cubit");
    $sql = "SELECT * FROM quotes WHERE quoid='{$quoid}' AND DIV='" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to retrieve quote info.");
    if (pg_num_rows($invRslt) < 1) {
        return "<li class='err'>Not found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    db_conn("cubit");
    $sql = "SELECT symbol FROM currency WHERE fcid='{$inv['fcid']}'";
    $curRslt = db_exec($sql) or errDie("Unable to retrieve currency from Cubit.");
    $curr = pg_fetch_result($curRslt, 0);
    if (!$curr) {
        $curr = CUR;
    }
    // Check if stock was selected
    db_conn("cubit");
    $sql = "SELECT stkid FROM quote_items WHERE quoid='{$quoid}' AND DIV='" . USER_DIV . "'";
    $cRslt = db_exec($sql) or errDie("Unable to retrieve quote info.");
    if (pg_num_rows($cRslt) < 1) {
        $error = "<li class='err'>Quote number <b>{$quoid}</b> has no items</li>";
        $OUTPUT = $error;
    }
    // Only needs to be blank, we're manually adding text
    $heading = array(array(""));
    // Company info ----------------------------------------------------------
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo WHERE div='" . USER_DIV . "'";
    $ciRslt = db_exec($sql) or errDie("Unable to retrieve company info from Cubit.");
    $comp = pg_fetch_array($ciRslt);
    // Banking information ---------------------------------------------------
    $bnkData = qryBankAcct(getdSetting("BANK_DET"));
    $compinfo = array();
    $compinfo[] = array($comp["addr1"], $comp["paddr1"]);
    $compinfo[] = array(pdf_lstr($comp["addr2"], 35), pdf_lstr($comp["paddr2"], 35));
    $compinfo[] = array(pdf_lstr($comp["addr3"], 35), pdf_lstr($comp["paddr3"], 35));
    $compinfo[] = array(pdf_lstr($comp["addr4"], 35), "{$comp['postcode']}");
    $compinfo[] = array("<b>REG: </b>{$comp['regnum']}", "<b>{$bnkData['bankname']}</b>");
    $compinfo[] = array("<b>VAT REG: </b>{$comp['vatnum']}", "<b>Branch: </b>{$bnkData['branchname']}");
    $compinfo[] = array("<b>Tel:</b> {$comp['tel']}", "<b>Branch Code: </b>{$bnkData['branchcode']}");
    $compinfo[] = array("<b>Fax:</b> {$comp['fax']}", "<b>Acc Num: </b>{$bnkData['accnum']}");
    // Date ------------------------------------------------------------------
    $date = array(array("<b>Date</b>"), array($inv['odate']));
    // Document info ---------------------------------------------------------
    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);
    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 = "<b>Sales Person: </b>{$inv['salespn']}";
    } else {
        $sp = "";
    }
    $docinfo = array(array("<b>Quote No:</b> {$inv['quoid']}"), array("<b>Proforma Inv No:</b> {$inv['docref']}"), array("<b>Sales Order No:</b> {$inv['ordno']}"), array("{$sp}"));
    if (isset($salespn)) {
        $docinfo[] = array("<b>Sales Person:</b> {$salespn}");
    }
    // Retrieve the customer information -------------------------------------
    db_conn("cubit");
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusnum']}'";
    $cusRslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
    $cusData = pg_fetch_array($cusRslt);
    // Customer info ---------------------------------------------------------
    $invoice_to = array(array(""));
    $cusinfo = array(array("<b>{$inv['surname']}</b>"));
    $cusaddr = explode("\n", $cusData['addr1']);
    foreach ($cusaddr as $v) {
        $cusinfo[] = array(pdf_lstr($v, 40));
    }
    $cusinfo[] = array("<b>Account no: </b>{$cusData['accno']}");
    $cuspaddr = array(array("<b>Postal Address</b>"));
    $paddr = explode("\n", $cusData["paddr1"]);
    foreach ($paddr as $addr) {
        $cuspaddr[] = array($addr);
    }
    $cusdaddr = array(array("<b>Delivery Address:</b>"));
    if ($inv['branch'] == 0) {
        $branchname = "Head Office";
        $cusaddr = explode("\n", $cusData['addr1']);
    } else {
        $get_addr = "SELECT * FROM customer_branches WHERE id = '{$inv['branch']}' LIMIT 1";
        $run_addr = db_exec($get_addr);
        if (pg_numrows($run_addr) < 1) {
            $cusaddr = array();
            $branchname = "Head Office";
        } else {
            $barr = pg_fetch_array($run_addr);
            $cusaddr = explode("\n", $barr['branch_descrip']);
            $branchname = $barr['branch_name'];
        }
    }
    $cusdaddr[] = array(pdf_lstr("Branch : {$branchname}", 30));
    $del_addr = explode("\n", $inv["del_addr"]);
    foreach ($del_addr as $addr) {
        $cusdaddr[] = array(pdf_lstr($addr, 30));
    }
    // Registration numbers --------------------------------------------------
    $regnos = array(array("<b>VAT No:</b>", "<b>Order No:</b>"), array("{$inv['cusvatno']}", "{$inv['cordno']}"));
    // Items display ---------------------------------------------------------
    $items = array();
    db_conn("cubit");
    $sql = "SELECT * FROM quote_items WHERE quoid='{$quoid}' AND DIV='" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        // Get warehouse
        db_conn("exten");
        $sql = "SELECT * FROM warehouses WHERE whid='{$stkd['whid']}' AND DIV='" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        // Get stock in this warehouse
        db_conn("cubit");
        $sql = "SELECT * FROM stock WHERE stkid='{$stkd['stkid']}' AND DIV='" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        $sp = "";
        // Check Tax Excempt
        db_conn("cubit");
        $sql = "SELECT zero FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $zRslt = db_exec($sql) or errDie("Unable to retrieve vat code from Cubit.");
        $vatex = pg_fetch_result($zRslt, 0);
        if ($vatex == "Yes") {
            $ex = "#";
        } else {
            $ex = "";
        }
        $sql = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $runsql = db_exec($sql) or errDie("Unable to retrieve vat code from Cubit.");
        if (pg_numrows($runsql) < 1) {
            return "Invalid VAT code entered";
        }
        $vd = pg_fetch_array($runsql);
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        // keep track of discounts
        //$disc += $stkd['disc'];
        if ($stkd["account"] > 0) {
            $description = $stkd["description"];
        } else {
            $description = $stk["stkdes"];
        }
        // Remove any new lines from the description
        $ar_desc = explode("\n", $description);
        $description = implode(" ", $ar_desc);
        $items[] = array("Code" => makewidth($pdf, 75, 12, $stk['stkcod']), "Description" => makewidth($pdf, 175, 12, $ex . $description), "Qty" => $stkd['qty'], "Unit Price" => $curr . $stkd['unitcost'], "Unit Discount" => $curr . $stkd['disc'], "Amount" => $curr . $stkd['amt']);
    }
    $inv["comm"] = fixparag(&$pdf, 3, 520, 11, $inv["comm"]);
    /*$inv["comm"] = preg_replace("/[\n]/", " ", $inv["comm"]);
    
    	$lines = array();
    	$txtleft = $inv["comm"];
    	$done = false;
    	while (count($lines) < 3 && !$done) {
    		$mc = maxwidth(&$pdf, 520, 11, $txtleft);
    
    		// run until end of a word.
    		while ($txtleft[$mc - 1] != ' ' && $mc < strlen($txtleft)) ++$mc;
    
    		if ($mc == strlen($txtleft)) {
    			$done = true;
    		}
    
    		$lines[] = substr($txtleft, 0, $mc);
    		$txtleft = substr($txtleft, $mc);
    	}
    
    	if (strlen($txtleft) > 0) {
    		$lines[2] .= "...";
    	}
    
    	$inv["comm"] = preg_replace("/  /", " ", implode("\n", $lines));*/
    // Comment ---------------------------------------------------------------
    $comment = array(array("<i>VAT Exempt Indicator : #</i>"), array($inv["comm"]));
    // Box for signature -----------------------------------------------------
    $sign = array(array("<b>Terms:</b> {$inv['terms']} days"), array(''), array("<b>Received in good order by:</b> ____________________"), array(''), array("                                      <b>Date:</b> ____________________"));
    // Totals ----------------------------------------------------------------
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    $totals = array(array("1" => "<b>Subtotal:</b> ", "2" => $curr . "{$inv['subtot']}"), array("1" => "<b>Trade Discount:</b> ", "2" => $curr . "{$inv['discount']}"), array("1" => "<b>Delivery Charge:</b> ", "2" => $curr . "{$inv['delivery']}"), array("1" => "<b>VAT {$vat14}:</b> ", "2" => $curr . "{$inv['vat']}"), array("1" => "<b>Total Incl VAT:</b> ", "2" => $curr . "{$inv['total']}"));
    $totCols = array("1" => array("width" => 90), "2" => array("justification" => "right"));
    $ic = 0;
    while (++$ic * 22 < count($items)) {
    }
    // Draw the pages, determine by the amount of items how many pages
    // if items > 20 start a new page
    $items_print = array();
    for ($i = 0; $i < $ic; $i++) {
        if ($i) {
            $pdf->ezNewPage();
        }
        // Page number -------------------------------------------------------
        $pagenr = array(array("<b>Page number</b>"), array($i + 1));
        // Heading
        $heading_pos = drawTable(&$pdf, $heading, 0, 0, 520, 5);
        drawText(&$pdf, "<b>{$comp['compname']}</b>", 18, 0, $heading_pos['y'] / 2 + 6);
        drawText(&$pdf, "<b>Quote</b>", 20, $heading_pos['x'] - 120, $heading_pos['y'] / 2 + 9);
        // Should we display reprint on the invoice
        if ($type == "invreprint") {
            drawText(&$pdf, "<b>Reprint</b>", 12, $heading_pos['x'] - 70, $heading_pos['y'] / 2 + 22);
        }
        $compinfo_pos = drawTable(&$pdf, $compinfo, 0, $heading_pos['y'], 320, 8);
        $date_pos = drawTable(&$pdf, $date, $compinfo_pos['x'], $heading_pos['y'], 100, 3);
        $pagenr_pos = drawTable(&$pdf, $pagenr, $date_pos['x'], $heading_pos['y'], 100, 3);
        $docinfo_pos = drawTable(&$pdf, $docinfo, $compinfo_pos['x'], $date_pos['y'], 200, 5);
        $invoice_to_pos = drawTable(&$pdf, $invoice_to, 0, $compinfo_pos['y'], 520, 2);
        drawText(&$pdf, "<b>Quote To:</b>", 12, 520 / 2 - 45, $invoice_to_pos['y'] - 7);
        $cusinfo_pos = drawTable(&$pdf, $cusinfo, 0, $invoice_to_pos['y'], 173, 8);
        $cuspaddr_pos = drawTable(&$pdf, $cuspaddr, $cusinfo_pos['x'], $invoice_to_pos['y'], 173, 8);
        $cusdaddr_pos = drawTable(&$pdf, $cusdaddr, $cuspaddr_pos['x'], $invoice_to_pos['y'], 174, 8);
        $regnos_pos = drawTable(&$pdf, $regnos, 0, $cusinfo_pos['y'], 520, 2);
        $items_start = $i * 22;
        if ($i) {
            $items_start++;
        }
        if ($items_start >= count($items) - 22) {
            $items_end = count($items) - 1;
        } else {
            $items_end = ($i + 1) * 22;
        }
        $items_print = array();
        for ($j = $items_start; $j <= $items_end; $j++) {
            $items_print[$j] = $items[$j];
        }
        $cols = array("Code" => array("width" => 80), "Description" => array("width" => 180), "Qty" => array("width" => 33), "Unit Price" => array("width" => 80, "justification" => "right"), "Unit Discount" => array("width" => 67, "justification" => "right"), "Amount" => array("width" => 80, "justification" => "right"));
        $items_pos = drawTable(&$pdf, $items_print, 0, $regnos_pos['y'] + 2, 520, 22, $cols, 1);
        $comment_pos = drawTable(&$pdf, $comment, 0, $items_pos['y'], 520, 2);
        $sign_pos = drawTable(&$pdf, $sign, 0, $comment_pos['y'], 320, 5);
        $totals_pos = drawTable(&$pdf, $totals, $sign_pos['x'], $comment_pos['y'], 200, 5, $totCols);
    }
    return $pdf->output();
}
function details($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>{$e['msg']}</li>";
        }
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $sql = "SELECT stkid FROM inv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
    $crslt = db_exec($sql);
    if (pg_numrows($crslt) < 1) {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has no items.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        return $error;
    }
    # check if invoice has been serialised
    if ($inv['serd'] == "n") {
        $error = "<li class='err'> Error : You must select serial numbers for some Items on Invoice No. <b>T {$invid}</b> before you can print it.</li>";
        return $error;
    }
    #check if this transaction date is allowed
    // 	$curyr = getActiveFinYear();
    // 	if ($yr > $curyr || ($yr == $curyr && $mon > $PRDMON[12])) {
    // 		$v->addError("", "Cannot do transaction in future financial year. ".(DEBUG>0?"\"$details\"":""));
    // 	}
    db_conn('cubit');
    $showvat = TRUE;
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($inv['odate']) >= strtotime($blocked_date_from) and strtotime($inv['odate']) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $invnum = divlastid('inv', USER_DIV);
    $Sl = "INSERT INTO ncsrec (oldnum, newnum, div) VALUES ('{$invid}', '{$invnum}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert into db");
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    /* --- Start Products Display --- */
    # Products layout
    $commision = 0;
    $products = array();
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM inv_items WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $taxex = 0;
    $i = 0;
    $page = 0;
    $salesp = qrySalesPersonN($inv["salespn"]);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                $showvat = FALSE;
            }
            $sp = "";
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "";
            }
            # all must be excempted
            if ($inv['chrgvat'] == 'nov') {
                $ex = "#";
            }
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            # Insert stock record
            $sdate = date("Y-m-d");
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            # Sales rep commission
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = $stk["com"];
            }
            #if this item is not exvat (ie. $ex != #) then reduce by the vat amount
            if ((strlen($ex) != "#" or $vd['vat_amount'] > 0) and $inv['chrgvat'] == "inc") {
                $vat = sprint($stkd['amt'] * $vd['vat_amount'] / (100 + $vd['vat_amount']));
                $exvatamt = sprint($stkd['amt'] - $vat);
            } else {
                $exvatamt = sprint($stkd['amt']);
            }
            $commision = $commision + coms($inv['salespn'], sprint($exvatamt), $itemcommission);
            if (strlen($stkd['serno']) > 0) {
                $showser = "<br>" . trim($stkd['serno']);
            } else {
                $showser = "";
            }
            # Put in product
            $products[$page][] = "\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$stk['stkcod']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$sp} {$stk['stkdes']}&nbsp; {$showser}</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$stkd['qty']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['unitcost']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['disc']}&nbsp;</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$stkd['amt']}&nbsp;</td>\n\t\t\t\t</tr>";
            $i++;
        } else {
            db_conn('core');
            $Sl = "SELECT * FROM accounts WHERE accid='{$stkd['account']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get account data.");
            $ad = pg_fetch_array($Ri);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                $showvat = FALSE;
            }
            $sp = "";
            # Check Tax Excempt
            if ($vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "";
            }
            # all must be excempted
            if ($inv['chrgvat'] == 'nov') {
                $ex = "#";
            }
            #if this item is not exvat (ie. $ex != #) then reduce by the vat amount
            if ((strlen($ex) != "#" or $vd['vat_amount'] > 0) and $inv['chrgvat'] == "inc") {
                $vat = sprint($stkd['amt'] * $vd['vat_amount'] / (100 + $vd['vat_amount']));
                $exvatamt = sprint($stkd['amt'] - $vat);
            } else {
                $exvatamt = sprint($stkd['amt']);
            }
            if ($salesp["com"] > 0) {
                $itemcommission = $salesp['com'];
            } else {
                $itemcommission = 0;
            }
            $commision = $commision + coms($inv['salespn'], sprint($exvatamt), $itemcommission);
            # Put in product
            $products[$page][] = "\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$sp} {$stkd['description']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$stkd['qty']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['unitcost']}&nbsp;</td>\n\t\t\t\t\t<td align='right' style='border-right: 2px solid #000'>{$stkd['disc']}&nbsp;</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$stkd['amt']}&nbsp;</td>\n\t\t\t\t</tr>";
            $i++;
        }
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\n\t \t\t\t<tr>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t \t\t\t\t<td>&nbsp;</td>\n\t \t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    if (strlen($inv['traddisc']) > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * $SUBTOT);
    } else {
        $traddiscm = "0.00";
    }
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOTAL = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    com_invoice($inv['salespn'], $TOTAL - $VAT, sprint($commision), $invnum, $inv["odate"], true);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    /* - End Hooks - */
    # Todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*refnum*/
    if ($inv['branch'] != 0) {
        db_conn("cubit");
        $get_addr = "SELECT * FROM customer_branches WHERE id = '{$inv['branch']}' LIMIT 1";
        $run_addr = db_exec($get_addr);
        if (pg_numrows($run_addr) < 1) {
            $address = "";
        } else {
            $barr = pg_fetch_array($run_addr);
            $address = " - {$barr['branch_name']}";
        }
    } else {
        $address = "";
    }
    /* --- Updates ---- */
    db_connect();
    $Sql = "UPDATE invoices SET printed = 'y', done = 'y', invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
    //dont make consignment order from invoice if customer number is entered ...
    //		if (isset($inv['cordno']) AND strlen($inv['cordno']) > 0){
    //			$inv_type = "Consignment Order";
    //		}else {
    $inv_type = "Invoice";
    //		}
    # Record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt (\n\t\t\t\tcusnum, invid, docref, amount, date, \n\t\t\t\ttype, branch, div, allocation_date, \n\t\t\t\tallocation_balance\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}', '{$inv['odate']}', \n\t\t\t\t'{$inv_type}', '{$address}', '" . USER_DIV . "', '{$inv['odate']}', \n\t\t\t\t'" . abs($inv['total']) . "'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO open_stmnt (\n\t\t\t\tcusnum, invid, docref, amount, balance, \n\t\t\t\tdate, type, div\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}','{$inv['total']}', \n\t\t\t\t'{$inv['odate']}', '{$inv_type}', '" . USER_DIV . "'\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Save invoice discount
    $sql = "\n\t\t\tINSERT INTO inv_discs (\n\t\t\t\tcusnum, invid, traddisc, itemdisc, inv_date, delchrg, \n\t\t\t\tdiv, total\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$invnum}', '{$traddiscm}', '{$disc}', '{$inv['odate']}', '{$inv['delchrg']}', \n\t\t\t\t'" . USER_DIV . "', ({$SUBTOT}+{$inv['delchrg']})\n\t\t\t)";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$inv['total']}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    # Make ledge record
    custledger($inv['cusnum'], $dept['incacc'], $inv['odate'], $invnum, "Invoice No. {$invnum}", $inv['total'], "d");
    db_connect();
    # get selected stock in this invoice
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    $sdate = date("Y-m-d");
    $nsp = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            db_connect();
            # get selamt from selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            if ($stk['units'] - $stkd['qty'] < 0) {
                if ($stk['units'] <= 0) {
                    $cosamt = 0;
                    $cosamt2 = 0;
                } else {
                    $cosamt = round($stk['units'] * $stk['csprice'], 2);
                    $cosamt2 = round($stk['units'] * $stk['csprice'], 4);
                }
            } else {
                $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
                $cosamt2 = round($stkd['qty'] * $stk['csprice'], 4);
            }
            # update stock(alloc - qty)
            $sql = "\n\t\t\t\t\tUPDATE stock \n\t\t\t\t\tSET csamt = (csamt - '{$cosamt}'),units = (units - '{$stkd['qty']}'), alloc=(alloc - '{$stkd['qty']}') \n\t\t\t\t\tWHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            if ($inv["pslip_sordid"] > 0) {
                $sql = "UPDATE stock SET alloc = (alloc - '{$stkd['qty']}') WHERE stkid='{$stkd['stkid']}'";
                //					db_exec($sql) or errDie("Unable to update allocation.");
            }
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            ####################################################
            $amtexvat = sprint($stkd['amt']);
            //	$uc=sprint($cosamt2/$stkd['qty']);
            $uc = round($cosamt2 / $stkd['qty'], 4);
            // '$cosamt',
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            db_connect();
            $sql = "\n\t\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, \n\t\t\t\t\t\tcsprice, csamt, details, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$inv['odate']}', '{$stkd['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'invoice', '{$stkd['qty']}', \n\t\t\t\t\t\t'{$amtexvat}', '{$csprice}', 'Stock sold - Invoice No. {$invnum}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
            if ($stk['csprice'] > 0) {
                $Sl = "INSERT INTO scr (inv, stkid, amount, invid) VALUES ('{$invnum}', '{$stkd['stkid']}', '{$uc}', '{$stkd['id']}')";
                $Rg = db_exec($Sl);
            }
            if ($stk['serd'] == 'yes') {
                ext_invSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $invnum, $inv['odate']);
            }
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            $sdate = date("Y-m-d");
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $inv['odate'], $stkd['qty'], $cosamt, "Sold to Customer : {$inv['surname']} - Invoice No. {$invnum}");
            # get accounts
            db_conn("exten");
            $sql = "SELECT stkacc, cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $stockacc = $wh['stkacc'];
            $cosacc = $wh['cosacc'];
            if ($cosamt < 0) {
                $cosamt = 0;
            }
            # dt(cos) ct(stock)
            writetrans($cosacc, $stockacc, $inv['odate'], $refnum, $cosamt, "Cost Of Sales for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
            $tcosamt += $cosamt;
            #record the entry for the stock report
            db_connect();
            $sql = "\n\t\t\t\t\tINSERT INTO salesrec (\n\t\t\t\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'stk', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
        } else {
            db_connect();
            ###################VAT CALCS#######################
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if ($vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            ####################################################
            $amtexvat = sprint($stkd['amt']);
            db_connect();
            $sdate = date("Y-m-d");
            $nsp += sprint($iamount - $ivat);
            writetrans($dept['debtacc'], $stkd['account'], $inv['odate'], $refnum, $iamount - $ivat, "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
            db_connect();
            $sql = "\n\t\t\t\t\tINSERT INTO salesrec (\n\t\t\t\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'non', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $recRslt = db_exec($sql);
        }
    }
    ###################VAT CALCS#######################
    $inv['delvat'] += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
        $showvat = FALSE;
    }
    if ($vd['zero'] == "Yes") {
        $excluding = "y";
    } else {
        $excluding = "";
    }
    $vr = vatcalc($inv['delchrg'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
    $vrs = explode("|", $vr);
    $ivat = $vrs[0];
    $iamount = $vrs[1];
    vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", sprint($iamount + $ivat), $ivat);
    ####################################################
    /* - Start Transactoins - */
    # dt(debtors) ct(income/sales)
    writetrans($dept['debtacc'], $dept['incacc'], $inv['odate'], $refnum, sprint($TOTAL - $VAT - $nsp), "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    # dt(debtors) ct(vat account)
    writetrans($dept['debtacc'], $vatacc, $inv['odate'], $refnum, $VAT, "VAT Received on Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
    db_conn('cubit');
    $Sl = "\n\t\t\tINSERT INTO sj (\n\t\t\t\tcid, name, des, date, exl, \n\t\t\t\tvat, inc, div\n\t\t\t) VALUES (\n\t\t\t\t'{$inv['cusnum']}', '{$inv['surname']}', 'Invoice {$invnum}', '{$inv['odate']}', '" . sprint($TOTAL - $VAT) . "', \n\t\t\t\t'{$VAT}', '" . sprint($TOTAL) . "', '" . USER_DIV . "'\n\t\t\t)";
    $Ri = db_exec($Sl);
    //		db_connect();
    //		$sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)
    //		VALUES('$inv[odate]', '$invid', '$invnum', '$dept[debtacc]', '$VAT', '$TOTAL', 'stk', '".USER_DIV."')";
    //		$recRslt = db_exec($sql);
    //exit;
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* - End Transactoins - */
    # vat explanation
    if ($inv['chrgvat'] == 'nov') {
        $expl = "VAT Exempt indicator";
    } else {
        $expl = "VAT Exempt indicator";
    }
    if (strlen($inv['comm']) > 0) {
        $inv['comm'] = "\n\t\t\t<table border='1' cellspacing='0' bordercolor='#000000'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Remarks:</td>\n\t\t\t\t\t<td>" . nl2br($inv['comm']) . "</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    $cc = "<script> sCostCenter('dt', 'Sales', '{$inv['odate']}', 'Invoice No.{$invnum} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', ''); </script>";
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='SALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sp = "\n\t\t\t<tr>\n\t\t\t\t<td><b>Sales Person:</b> {$inv['salespn']}</td>\n\t\t\t</tr>";
    } else {
        $sp = "";
    }
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if ($inv['branch'] == 0) {
        $branchname = "Head Office";
    } else {
        $get_bname = "SELECT * FROM customer_branches WHERE id = '{$inv['branch']}' LIMIT 1";
        $run_bname = db_exec($get_bname);
        if (pg_numrows($run_bname) < 1) {
            $branchname = "";
        } else {
            $arr = pg_fetch_array($run_bname);
            $branchname = $arr['branch_name'];
        }
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    if (strlen(COMP_TEL) > 0) {
        $showtel = "Tel: ";
    } else {
        $showtel = "";
    }
    if (strlen(COMP_FAX) > 0) {
        $showfax = "Fax: ";
    } else {
        $showfax = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company information from Cubit.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    $bank_data = qryBankAcct(getdSetting("BANK_DET"));
    // Retrieve customer information
    db_conn("cubit");
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusnum']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
    $cust_data = pg_fetch_array($cust_rslt);
    $table_borders = "\n\t\tborder-top: 2px solid #000000;\n\t\tborder-left: 2px solid #000000;\n\t\tborder-right: 2px solid #000000;\n\t\tborder-bottom: none;";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $barcode = "<img src='manufact/" . pick_slip_barcode($inv["invid"], 1) . "' />";
        $details .= "\n\t\t<center>\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='left'><img src='compinfo/getimg.php' width='230' height='47'>{$barcode}</td>\n\t\t\t\t\t<td align='left'><font size='5'><b>" . COMP_NAME . "</b></font></td>\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Invoice</b></font></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td valign='top'>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td><td valign='top'>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\n\t\t\t\t\t<td><b>Page Number</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\n\t\t\t\t</tr>\n\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr><td>&nbsp</td></tr>\n\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$invnum}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Sales Order No:</b> {$inv['ordno']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><b>Account No:</b> {$cust_data['accno']}</td>\n\t\t\t\t</tr>\n\t\t\t\t{$sp}\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='center'><font size='4'><b>Tax Invoice To:</b></font></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$inv['surname']}</b></td>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\n\t\t\t\t\t<td>Branch: {$branchname}<br />" . nl2br($inv["del_addr"]) . "</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer Order No:</b> {$inv['cordno']}</td>\n\t\t\t\t\t<td width='33%'><b>Delivery Date:</b> {$inv['deldate']}</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;'><b>Code</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;'><b>Description</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;'><b>Qty</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;' align='right'><b>Unit Price</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;' align='right'><b>Unit Discount</b></td>\n\t\t\t\t\t<td style='border-bottom: 2px solid #000' align='right'><b>Amount</b></td>\n\t\t\t\t</tr>\n\t\t\t\t{$products_out}\n\t\t\t</table>\n\t\t\t</td></tr>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$inv['comm']}</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t</table>\n\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\n\t\t\t<tr><td>\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms: {$inv['terms']} days</b></td>\n\t\t\t\t\t<td><b>Subtotal:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['subtot']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t\t\t\t\t<td><b>Trade Discount:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['discount']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\n\t\t\t\t\t<td><b>Delivery Charge</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['delivery']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['vat']}</b></td>\n\t\t\t\t<tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['total']}</b></td>\n\t\t\t\t</tr>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t</table>";
    }
    // Retrieve template settings from Cubit
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve the template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    $OUTPUT = "\n\t\t<script>\n\t\t\tsCostCenter('dt', 'Sales', '{$inv['odate']}', 'Invoice No.{$invnum} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', '');\n\t\t</script>";
    if (isset($email)) {
        $OUTPUT .= "\n\t\t\t<script>\n\t\t\t\tmove(\"invoices-email.php?evs={$inv['invid']}\");\n\t\t\t</script>";
        require "template.php";
    }
    if ($template == "invoice-print.php") {
        $OUTPUT .= $details;
        require "tmpl-print.php";
    } else {
        $OUTPUT .= "\n\t\t\t<script>\n\t\t\t\tmove(\"{$template}?invid={$inv['invid']}&type=inv\");\n\t\t\t</script>";
        require "template.php";
    }
}
function printStmnt($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer number.");
    if (isset($from_day)) {
        $BYDATE = true;
        $v->isOk($from_day, "num", 1, 2, "Invalid from Date day.");
        $v->isOk($from_month, "num", 1, 2, "Invalid from Date month.");
        $v->isOk($from_year, "num", 1, 4, "Invalid from Date Year.");
        $v->isOk($to_day, "num", 1, 2, "Invalid to Date day.");
        $v->isOk($to_month, "num", 1, 2, "Invalid to Date month.");
        $v->isOk($to_year, "num", 1, 4, "Invalid to Date Year.");
        # mix dates
        $fromdate = $from_year . "-" . $from_month . "-" . $from_day;
        $todate = $to_year . "-" . $to_month . "-" . $to_day;
        if (!checkdate($from_month, $from_day, $from_year)) {
            $v->isOk($fromdate, "num", 1, 1, "Invalid from date.");
        }
        if (!checkdate($to_month, $to_day, $to_year)) {
            $v->isOk($todate, "num", 1, 1, "Invalid to date.");
        }
    } else {
        $BYDATE = false;
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $err;
    }
    if ($BYDATE) {
        $bdfilter = "date >= '{$fromdate}' AND date <= '{$todate}'";
        $heading = "Period Range Statement : {$fromdate} - {$todate}";
    } else {
        $fdate = date("Y") . "-" . date("m") . "-" . "01";
        $bdfilter = "date >= '{$fdate}'";
        $heading = "Monthly Statement";
    }
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    if (pg_numrows($custRslt) < 1) {
        return "<li class='err'>Invalid Customer Number.</li>";
    }
    $cust = pg_fetch_array($custRslt);
    # connect to database
    db_connect();
    $fdate = date("Y") . "-" . date("m") . "-" . "01";
    $stmnt = array();
    $totout = 0;
    #check for sort ...
    if (isset($sort) and $sort == "branch") {
        $sortinga = "ORDER BY branch";
        $sorting = "branch,";
    } else {
        $sortinga = "";
        $sorting = "";
    }
    if (!open()) {
        # Query server
        $sql = "SELECT * FROM stmnt WHERE cusnum = '{$cusnum}' AND {$bdfilter} AND div = '" . USER_DIV . "' ORDER BY {$sorting} date ASC";
        $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
        if (pg_numrows($stRslt) < 1) {
            //$stmnt .= "<tr><td colspan=4>No invoices for this month.</td></tr>";
        } else {
            while ($st = pg_fetch_array($stRslt)) {
                # keep track of da totals
                $totout += $st['amount'];
            }
        }
    } else {
        # Query server
        $sql = "SELECT * FROM open_stmnt WHERE cusnum = '{$cusnum}' AND {$bdfilter} AND balance != '0' AND div = '" . USER_DIV . "' ORDER BY {$sorting} date ASC";
        $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
        if (pg_numrows($stRslt) < 1) {
            //$stmnt .= "<tr><td colspan=4>No invoices for this month.</td></tr>";
        } else {
            while ($st = pg_fetch_array($stRslt)) {
                # keep track of da totals
                $totout += $st['balance'];
            }
        }
    }
    // we need a way to get this for a date range selection as well ....
    // balance brought forward == sum of all transactions before selected start date
    //	$balbf = ($cust['balance'] - $totout);
    if ($BYDATE) {
        $bdfilter2 = "date < '{$fromdate}'";
    } else {
        $fdate = date("Y") . "-" . date("m") . "-" . "01";
        $bdfilter2 = "date < '{$fdate}'";
    }
    if (!open()) {
        $sql = "SELECT sum(amount) FROM stmnt WHERE cusnum = '{$cusnum}' AND {$bdfilter2} AND div = '" . USER_DIV . "'";
        $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
        if (pg_numrows($stRslt) < 1) {
            $stmnt .= "<tr><td colspan='4'>No invoices for this month.</td></tr>";
        } else {
            $st = pg_fetch_array($stRslt);
        }
    } else {
        $sql = "SELECT sum(amount) FROM open_stmnt WHERE cusnum = '{$cusnum}' AND {$bdfilter2} AND balance != '0' AND div = '" . USER_DIV . "'";
        $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
        if (pg_numrows($stRslt) < 1) {
            $stmnt .= "<tr><td colspan='4'>No invoices for this month.</td></tr>";
        } else {
            $st = pg_fetch_array($stRslt);
        }
    }
    //	$balbf = ($cust['balance'] - $totout);
    $balbf = $st['sum'];
    $balbf = sprint($balbf);
    $rbal = $balbf;
    # Query server
    if (!open()) {
        db_conn("cubit");
        $sql = "SELECT * FROM stmnt WHERE cusnum = '{$cusnum}' AND {$bdfilter} AND div = '" . USER_DIV . "' ORDER BY {$sorting} date ASC";
        $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
    } else {
        db_conn("cubit");
        $sql = "SELECT * FROM open_stmnt WHERE cusnum = '{$cusnum}' AND {$bdfilter} AND balance != '0' AND div = '" . USER_DIV . "' ORDER BY {$sorting} date ASC";
        $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
    }
    if (pg_numrows($stRslt) > 0) {
        while ($st = pg_fetch_array($stRslt)) {
            if (!open()) {
                $amtbal = sprint($st['amount']);
                $rbal = sprint($rbal + $st['amount']);
            } else {
                $amtbal = sprint($st['balance']);
                $rbal = sprint($rbal + $st['balance']);
            }
            # format date
            $st['date'] = explode("-", $st['date']);
            $st['date'] = $st['date'][2] . "-" . $st['date'][1] . "-" . $st['date'][0];
            $st['amount'] = sprint($st['amount']);
            if (substr($st['type'], 0, 7) == "Invoice") {
                $ex = "INV";
            } elseif (substr($st['type'], 0, 21) == "Non Stock Credit Note") {
                $ex = "CR";
            } elseif (substr($st['type'], 0, 17) == "Non-Stock Invoice") {
                $ex = "INV";
            } elseif (substr($st['type'], 0, 11) == "Credit Note") {
                $ex = "CR";
            } else {
                $ex = "";
            }
            $stmnt[] = grp(m('date', $st['date']), m('invid', $ex . " " . $st['invid']), m('type', $st['type']), m('amount', "{$cust['currency']} {$amtbal}"), m('balance', "{$cust['currency']} {$rbal}"));
            # keep track of da totals
            //$totout += $amtbal;
        }
    }
    if ($cust['location'] == 'int') {
        $cust['balance'] = $cust['fbalance'];
    }
    //$balbf = ($cust['balance'] - $totout);
    if ($BYDATE) {
        $bdfilter2 = "date < '{$fromdate}'";
    } else {
        $fdate = date("Y") . "-" . date("m") . "-" . "01";
        $bdfilter2 = "date < '{$fdate}'";
    }
    if (!open()) {
        $sql = "SELECT sum(amount) FROM stmnt WHERE cusnum = '{$cusnum}' AND {$bdfilter2} AND div = '" . USER_DIV . "'";
        $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
        if (pg_numrows($stRslt) < 1) {
            $stmnt .= "<tr><td colspan='4'>No invoices for this month.</td></tr>";
        } else {
            $st = pg_fetch_array($stRslt);
        }
    } else {
        $sql = "SELECT sum(amount) FROM open_stmnt WHERE cusnum = '{$cusnum}' AND {$bdfilter2} AND balance != '0' AND div = '" . USER_DIV . "'";
        $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
        if (pg_numrows($stRslt) < 1) {
            $stmnt .= "<tr><td colspan='4'>No invoices for this month.</td></tr>";
        } else {
            $st = pg_fetch_array($stRslt);
        }
    }
    $balbf = $st['sum'];
    $balbf = sprint($balbf);
    $cust['balance'] = sprint($cust['balance']);
    # Check type of age analisys
    if (div_isset("DEBT_AGE", "mon")) {
        $curr = ageage($cust['cusnum'], 0, $cust['fcid'], $cust['location']);
        $age30 = ageage($cust['cusnum'], 1, $cust['fcid'], $cust['location']);
        $age60 = ageage($cust['cusnum'], 2, $cust['fcid'], $cust['location']);
        $age90 = ageage($cust['cusnum'], 3, $cust['fcid'], $cust['location']);
        $age120 = ageage($cust['cusnum'], 4, $cust['fcid'], $cust['location']);
    } else {
        $curr = age($cust['cusnum'], 29, $cust['fcid'], $cust['location']);
        $age30 = age($cust['cusnum'], 59, $cust['fcid'], $cust['location']);
        $age60 = age($cust['cusnum'], 89, $cust['fcid'], $cust['location']);
        $age90 = age($cust['cusnum'], 119, $cust['fcid'], $cust['location']);
        $age120 = age($cust['cusnum'], 149, $cust['fcid'], $cust['location']);
        $custtot = $curr + $age30 + $age60 + $age90 + $age120;
        if (sprint($custtot) != sprint($cust['balance'])) {
            $curr = sprint($curr + $cust['balance'] - $custtot);
            $custtot = sprint($cust['balance']);
        }
    }
    $stmnthead = array('date' => "Date", 'invid' => "Ref No.", 'type' => "Details", 'amount' => "Amount", 'balance' => "Balance");
    $agehead = array('cur' => "Current", '30' => "30", '60' => "60", '90' => "90", '120' => "120");
    $age = array();
    $age[] = array('cur' => "{$curr}", '30' => "{$age30}", '60' => "{$age60}", '90' => "{$age90}", '120' => "{$age120}");
    /* Start PDF Layout */
    include "../pdf-settings.php";
    $pdf =& new Cezpdf();
    $pdf->selectFont($set_mainFont);
    # put a line top and bottom on all the pages
    $all = $pdf->openObject();
    $pdf->saveState();
    $pdf->setStrokeColor(0, 0, 0, 1);
    $pdf->line(20, 40, 578, 40);
    # $pdf->line(20,822,578,822);
    $pdf->addText(20, 34, 6, 'Cubit Accounting');
    $pdf->restoreState();
    $pdf->closeObject();
    # note that object can be told to appear on just odd or even pages by changing 'all' to 'odd'
    # or 'even'.
    $pdf->addObject($all, 'all');
    /* End PDF Layout */
    /* start PDF Layout */
    # Heading
    $pdf->ezText("<b>Customer {$heading}</b>", $set_txtSize + 2, array('justification' => 'centre'));
    # Set y so its away from the top
    $pdf->ezSetY($set_tlY);
    # Company details
    $smTxtSz = $set_txtSize - 3;
    $pdf->addText($set_tlX, $set_tlY, $smTxtSz, COMP_NAME);
    $nl = pdf_addnl($pdf, $set_tlX, $set_tlY, $smTxtSz, COMP_ADDRESS);
    $pdf->addText($set_tlX, $set_tlY - $smTxtSz * $nl, $smTxtSz, COMP_PADDR);
    # Company details cont
    $lrite = $set_pgXCenter + 60;
    $pdf->addText($lrite, $set_tlY - $smTxtSz, $smTxtSz, "COMPANY REG. " . COMP_REGNO);
    $pdf->addText($lrite, $set_tlY - $smTxtSz * 2, $smTxtSz, "TEL : " . COMP_TEL);
    $pdf->addText($lrite, $set_tlY - $smTxtSz * 3, $smTxtSz, "FAX : " . COMP_FAX);
    $pdf->addText($lrite, $set_tlY - $smTxtSz * 4, $smTxtSz, "VAT REG. " . COMP_VATNO);
    # Set y so its away from the company details
    $pdf->ezSetY($set_tlY - $set_txtSize * ($nl + 1));
    $address_ar = explode("\n", $cust["addr1"]);
    $address_out = "";
    foreach ($address_ar as $addr) {
        $address_out .= makewidth($pdf, 175, 12, $addr);
    }
    # customer details data
    $cusdet[] = array('tit' => "Account number : {$cust['accno']}");
    $cusdet[] = array('tit' => "{$cust['surname']}\n {$address_out}");
    $cusdet[] = array('tit' => "Balance Brought Forward : {$cust['currency']} {$balbf}");
    # customer details table
    $pdf->ezTable($cusdet, '', "", array('shaded' => 0, 'showLines' => 2, 'showHeadings' => 0, 'xPos' => 100));
    $bnkData = qryBankAcct(getdSetting("BANK_DET"));
    $banking = array(array("{$bnkData['bankname']}"), array("<b>Branch: </b>{$bnkData['branchname']}"), array("<b>Branch Code: </b>{$bnkData['branchcode']}"), array("<b>Account Number: </b>{$bnkData['accnum']}"));
    global $set_pgHeight;
    $pdf->ezSetY($set_tlY - $set_txtSize * ($nl + 1));
    $pdf->ezTable($banking, '', "", array('shaded' => 0, 'showLines' => 2, 'showHeadings' => 0, 'xPos' => 300));
    # just a new line
    $pdf->ezText("\n", $set_txtSize);
    # Statement table
    if (count($stmnt) < 1) {
        $stmnt = array($stmnthead);
        //$pdf->ezTable($stmnthead, "", "", array_merge($set_maxTblOptNl, grp(m("showHeadings", 0))));
        $pdf->ezTable($stmnt, "", '', array_merge($set_maxTblOptNl, array("showHeadings" => 0)));
        $stmnt = array(grp(m("err", "No previous invoices/transactions for this month.")));
        $pdf->ezTable($stmnt, "", '', array_merge($set_maxTblOptNl, array("showHeadings" => 0)));
    } else {
        $pdf->ezTable($stmnt, $stmnthead, '', $set_maxTblOptNl);
    }
    # just a new line
    $pdf->ezText("\n", $set_txtSize);
    # balance table data
    //$cust[balance]
    $baldat[] = array('tit' => "Total Outstanding Balance : {$cust['currency']} {$rbal}");
    //$pdf->ezSetY($set_tlY -200);
    # balance table
    $pdf->ezTable($baldat, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => $set_pgWidth - 63));
    $pdf->ezText("\n", $set_txtSize);
    $pdf->ezTable($age, $agehead, '', $set_maxTblOptNl);
    # Send stream
    $pdf->ezStream();
    exit;
}
            $script = basename(getenv("SCRIPT_NAME"));
            $sql = "SELECT * FROM perm WHERE script = '{$script}'";
            $rs = db_exec($sql);
            if (pg_numrows($rs) < 1) {
                $sql = "INSERT INTO perm(script) VALUES('{$script}')";
                $rs = db_exec($sql);
                $sql = "INSERT INTO userscripts (username, script) VALUES ('{$_SESSION['USER_NAME']}', '{$script}')";
                //$rs = db_exec($sql);
            }
            $OUTPUT = "<li class=err>You <b>don't have sufficient permissions</b> to use this command." . getenv("SCRIPT_NAME") . "<br>\n\t\t\tIf you have been given permission to this function please email andre@cubit.co.za with the details of this problem";
            require "template.php";
        }
    }
}
if (isSetting("BANK_DET")) {
    $bankid = getdSetting("BANK_DET");
    # Get bank account name
    db_connect();
    $sql = "SELECT * FROM bankacct WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $bankRslt = db_exec($sql);
    $bank = pg_fetch_array($bankRslt);
    define("BNK_BANKNAME", $bank['bankname']);
    define("BNK_BRANCHNAME", $bank['branchname']);
    define("BNK_BRANCHCODE", $bank['branchcode']);
    define("BNK_ACCNAME", $bank['accname']);
    define("BNK_ACCNUM", $bank['accnum']);
    define("BNK_BANKDET", "Bank : {$bank['bankname']}<br>Branch : {$bank['branchname']} ({$bank['branchcode']})<br>Acc No. : {$bank['accnum']}");
} else {
    define("BNK_BANKNAME", "");
    define("BNK_BRANCHNAME", "");
    define("BNK_BRANCHCODE", "");