function print_stmnt()
{
    extract($_REQUEST);
    define("PAGE_SPLIT", 25);
    $fields = array();
    $fields["cusnum"] = 0;
    $fields["stmnt_type"] = "detailed";
    $fields["from_year"] = date("Y");
    $fields["from_month"] = date("m");
    $fields["from_day"] = "01";
    $fields["to_year"] = date("Y");
    $fields["to_month"] = date("m");
    $fields["to_day"] = date("d");
    $fields["comments"] = "[_BLANK_]";
    extract($fields, EXTR_SKIP);
    if (isset($b64_comments)) {
        $comments = base64_decode($b64_comments);
    }
    if (!checkdate($from_month, $from_day, $from_year)) {
        $from_day = date("d");
        $from_month = date("m");
        $from_year = date("Y");
    }
    if (!checkdate($to_month, $to_day, $to_year)) {
        $to_day = date("d");
        $to_month = date("m");
        $to_year = date("Y");
    }
    // Date Selections Concatenated
    $from_date = "{$from_year}-{$from_month}-{$from_day}";
    $to_date = "{$to_year}-{$to_month}-{$to_day}";
    // Border styles
    $rborder = "style='border-right: 2px solid #000'";
    $bborder = "style='border-bottom: 2px solid #000'";
    $tborder = "style='border-top: 2px solid #000'";
    $thborder = "style='border-right: 2px solid #000; border-bottom: 2px solid #000'";
    $aborder = "style='border-right: 2px solid #000; border-top: 2px solid #000'";
    $br = "<br style='line-height: 2px'>";
    $page_break = "<br style='page-break-after:always;'>";
    // Retrieve customer information
    $sql = "\n\t\tSELECT  cusnum, accno, surname, balance, paddr1, addr1, fcid, location, bankid \n\t\tFROM cubit.customers\n\t\tWHERE cusnum='{$cusnum}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer information.");
    $cust_data = pg_fetch_array($cust_rslt);
    // Retrieve company information
    $sql = "\n\t\tSELECT compname, addr1, addr2, addr3, addr4, tel, fax, vatnum, regnum\n\t\tFROM cubit.compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company information.");
    $comp_data = pg_fetch_array($comp_rslt);
    #handle unset bank information
    if ($cust_data['bankid'] == "0") {
        $get_bid = "SELECT * FROM bankacct LIMIT 1";
        $run_bid = db_exec($get_bid) or errDie("Unable to get default bank information.");
        if (pg_numrows($run_bid) < 1) {
            #no bank accounts in cubit ????
            $bank_data = array();
            $bank_data['bankname'] = "";
            $bank_data['branchname'] = "";
            $bank_data['branchcode'] = "";
            $bank_data['accnum'] = "";
        } else {
            $cust_data['bankid'] = pg_fetch_result($run_bid, 0, 0);
            $bank_data = qryBankAcct($cust_data['bankid']);
        }
    } else {
        $bank_data = qryBankAcct($cust_data['bankid']);
    }
    // Retrieve banking details
    //	$bank_data = qryBankAcct(getdSetting("BANK_DET"));
    // Should payments or credit notes be displayed
    $payment_sql = "";
    if ($stmnt_type == "open") {
        $payment_sql = "\n\t\tAND type NOT LIKE 'Payment for%'\n\t\tAND type NOT LIKE '%Credit Note%for invoice%'\n\t\tAND (allocation = '0' OR allocation = '')";
    }
    // Retrieve statement information
    $sql = "\n\t\tSELECT id, date, invid, type, amount, docref, refnum FROM cubit.stmnt \n\t\tWHERE cusnum='{$cusnum}' {$payment_sql} AND date BETWEEN '{$from_date}' AND '{$to_date}' \n\t\tORDER BY date, allocation_date, invid, allocation ASC";
    $stmnt_rslt = db_exec($sql) or errDie("Unable to retrieve statement.");
    // Retrieve balance before the 'from date'
    $sql = "\n\t\tSELECT sum(amount) \n\t\tFROM cubit.stmnt \n\t\tWHERE cusnum='{$cusnum}' AND date<'{$from_date}'";
    $balance_rslt = db_exec($sql) or errDie("Unable to retrieve balance.");
    $balance = pg_fetch_result($balance_rslt, 0);
    $stmnt_ar = array();
    $pages = 1;
    $item_count = 0;
    while ($stmnt_data = pg_fetch_array($stmnt_rslt)) {
        // Deduct payments and credit notes from balances only
        // if this is an open item statement
        if ($stmnt_type == "open" && ($stmnt_data["type"] == "Invoice" || $stmnt_data["type"] == "Non-Stock Invoice")) {
            $sql = "\n\t\t\t\tSELECT sum(amount) \n\t\t\t\tFROM cubit.stmnt\n\t\t\t\tWHERE \n\t\t\t\t\ttype LIKE 'Payment for % {$stmnt_data['invid']}' OR \n\t\t\t\t\ttype LIKE '%Credit Note%for invoice%{$stmnt_data['invid']}' OR \n\t\t\t\t\tallocation = '{$stmnt_data['id']}'";
            $payment_rslt = db_exec($sql) or errDie("Unable to retrieve payments.");
            $payment = pg_fetch_result($payment_rslt, 0);
            // If the amount has been paid/credit note'ed in full
            // then no need to display this line
            if ($stmnt_data["amount"] == $payment * -1) {
                continue;
            }
            $stmnt_data["amount"] += $payment;
        }
        // Increase the balance
        $balance += $stmnt_data["amount"];
        // What should we prepend the ref num with, either invoice or credit note
        if (preg_match("/Payment/", $stmnt_data["type"])) {
            $refnum = "";
        } elseif (preg_match("/Invoice\$/", $stmnt_data["type"])) {
            $refnum = "INV";
        } elseif (preg_match("/Credit Note/", $stmnt_data["type"])) {
            $refnum = "CR";
        }
        if (isset($refnum)) {
            $refnum .= " " . $stmnt_data["invid"];
        } else {
            $refnum = "";
        }
        if (empty($refnum)) {
            $refnum = $stmnt_data["invid"];
        }
        if ($stmnt_type == "open") {
            $show_bal = "";
        } else {
            $show_bal = "<td align='right'>" . sprint($balance) . "</td>";
        }
        if ($stmnt_data['type'] == "Invoice") {
            db_connect();
            $get_invid = "SELECT invid FROM invoices WHERE invnum = '{$stmnt_data['invid']}' LIMIT 1";
            $run_invid = db_exec($get_invid) or errDie("Unable to get invoice information.");
            if (pg_numrows($run_invid) == 1) {
                $stmnt_invid = pg_fetch_result($run_invid, 0, 0);
                $showtype = "<font onClick=\"window.open('invoice-reprint.php?invid={$stmnt_invid}&type=invreprint','window1','height=600, width=900, scrollbars=yes');\">{$stmnt_data['type']}</font>";
            } else {
                $showtype = $stmnt_data['type'];
            }
        } elseif ($stmnt_data['type'] == "Non-Stock Invoice") {
            db_connect();
            $get_invid = "SELECT invid FROM nons_invoices WHERE invnum = '{$stmnt_data['invid']}' LIMIT 1";
            $run_invid = db_exec($get_invid) or errDie("Unable to get non stock invoice information.");
            if (pg_numrows($run_invid) == 1) {
                $stmnt_invid = pg_fetch_result($run_invid, 0, 0);
                $showtype = "<font onClick=\"window.open('nons-invoice-reprint.php?invid={$stmnt_invid}&type=nonsreprint','window1','height=600, width=900, scrollbars=yes');\">{$stmnt_data['type']}</font>";
            } else {
                $showtype = $stmnt_data['type'];
            }
        } else {
            $showtype = "{$stmnt_data['type']}";
        }
        // Add the line to the current page
        $stmnt_ar[$pages][] = "\n\t\t\t<tr>\n\t\t\t\t<td align='center' {$rborder}>\n\t\t\t\t\t" . date("d-m-Y", strtotime($stmnt_data["date"])) . " &nbsp;\n\t\t\t\t</td>\n\t\t\t\t<td align='center' {$rborder}>{$refnum} &nbsp;</td>\n\t\t\t\t<td align='center' {$rborder}>{$stmnt_data['docref']} &nbsp;</td>\n\t\t\t\t<td {$rborder}>{$showtype} &nbsp;</td>\n\t\t\t\t<td align='right' {$rborder}>" . sprint($stmnt_data["amount"]) . " &nbsp;</td>\n\t\t\t\t{$show_bal}\n\t\t\t</tr>";
        unset($refnum);
        $item_count++;
        // Time for a new page
        if ($item_count == PAGE_SPLIT) {
            $pages++;
            $item_count = 0;
        }
    }
    if ($stmnt_type == "open") {
        $show_bal_space = "";
        $unmatch = "Unmatched";
    } else {
        $show_bal_space = "<td>&nbsp;</td>";
        $unmatch = "";
    }
    // If there's wasn't one single line returned from the database
    // at the very least make the user aware of this.
    if (count($stmnt_ar) == 0) {
        $stmnt_ar[1][] = "\n\t\t\t<tr>\n\t\t\t\t<td {$rborder}>&nbsp;</td>\n\t\t\t\t<td {$rborder}>&nbsp;</td>\n\t\t\t\t<td {$rborder}>&nbsp;</td>\n\t\t\t\t<td {$rborder} align='center'><b>No {$unmatch} Invoices for this date range.</b></td>\n\t\t\t\t<td {$rborder}>&nbsp;</td>\n\t\t\t\t{$show_bal_space}\n\t\t\t</tr>";
    }
    // Generate blank lines to fill the the page
    foreach ($stmnt_ar as $page => $lv2) {
        $blank_lines = PAGE_SPLIT - count($stmnt_ar[$page]);
        for ($i = 0; $i < $blank_lines; $i++) {
            $stmnt_ar[$page][] = "\n\t\t\t\t<tr>\n\t\t\t\t\t<td {$rborder}>&nbsp;</td>\n\t\t\t\t\t<td {$rborder}>&nbsp;</td>\n\t\t\t\t\t<td {$rborder}>&nbsp;</td>\n\t\t\t\t\t<td {$rborder}>&nbsp;</td>\n\t\t\t\t\t<td {$rborder}>&nbsp;</td>\n\t\t\t\t\t{$show_bal_space}\n\t\t\t\t</tr>";
        }
    }
    // Decide which radio button should be selected
    if ($stmnt_type == "detailed") {
        $detailed_sel = "checked='checked'";
        $open_sel = "";
    } elseif ($stmnt_type == "open") {
        $detailed_sel = "";
        $open_sel = "checked='checked'";
    }
    // Comments
    if ($comments == "[_BLANK_]") {
        $sql = "\n\t\t\tSELECT value FROM cubit.settings \n\t\t\tWHERE constant='DEFAULT_STMNT_COMMENTS'";
        $comment_rslt = db_exec($sql) or errDie("Unable to retrieve comments.");
        $comments = base64_decode(pg_fetch_result($comment_rslt, 0));
    }
    // Get age analysis
    if (div_isset("DEBT_AGE", "mon")) {
        #shouldnt be used ...
        $curr = ageage($cust_data['cusnum'], 0, $cust_data['fcid'], $cust_data['location']);
        $age30 = ageage($cust_data['cusnum'], 1, $cust_data['fcid'], $cust_data['location']);
        $age60 = ageage($cust_data['cusnum'], 2, $cust_data['fcid'], $cust_data['location']);
        $age90 = ageage($cust_data['cusnum'], 3, $cust_data['fcid'], $cust_data['location']);
        $age120 = ageage($cust_data['cusnum'], 4, $cust_data['fcid'], $cust_data['location']);
    } else {
        #this is the used setting ...
        $curr = cust_age($cust_data['cusnum'], 29, $cust_data['fcid'], $cust_data['location'], $to_month, $to_date, $from_date);
        $age30 = cust_age($cust_data['cusnum'], 59, $cust_data['fcid'], $cust_data['location'], $to_month, $to_date, $from_date);
        $age60 = cust_age($cust_data['cusnum'], 89, $cust_data['fcid'], $cust_data['location'], $to_month, $to_date, $from_date);
        $age90 = cust_age($cust_data['cusnum'], 119, $cust_data['fcid'], $cust_data['location'], $to_month, $to_date, $from_date);
        $age120 = cust_age($cust_data['cusnum'], 149, $cust_data['fcid'], $cust_data['location'], $to_month, $to_date, $from_date);
    }
    $custtot = $curr + $age30 + $age60 + $age90 + $age120;
    $OUTPUT = "\n\t\t<center>\n\t\t<style>\n\t\t\ttable { border: 2px solid #000 }\n\t\t\tinput, textarea { border: 1px solid #000 }\n\t\t</style>";
    // Statement settings, only display when not printing
    if (!isset($key) || $key != "print") {
        $OUTPUT .= "\n\t\t\t<form method='post' action='" . SELF . "' name='form'>\n\t\t\t<input type='hidden' name='cusnum' value='{$cusnum}' />\n\t\t\t<table " . TMPL_tblDflts . " style='border: 1px solid #000'>\n\t\t\t\t<tr class='bg-even'>\n\t\t\t\t\t<td colspan='3' align='center'>\n\t\t\t\t\t\t<input type='radio' name='stmnt_type' value='detailed'\n\t\t\t\t\t\tonchange='javascript:document.form.submit()' {$detailed_sel}>\n\t\t\t\t\t\tDetailed\n\t\t\t\t\t\t<input type='radio' name='stmnt_type' value='open'\n\t\t\t\t\t\tonchange='javascript:document.form.submit()' {$open_sel}>\n\t\t\t\t\t\tOpen Item\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>" . mkDateSelect("from", $from_year, $from_month, $from_day) . "</td>\n\t\t\t\t\t<td align='center'>&nbsp; <b>To</b> &nbsp;</td>\n\t\t\t\t\t<td>" . mkDateSelect("to", $to_year, $to_month, $to_day) . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='3' align='center'><b>Comments</b></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='3'>\n\t\t\t\t\t\t<textarea name='comments' style='width: 100%'>{$comments}</textarea>\n\t\t\t\t\t</td>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t<input type='button'  value='Print'\n\t\t\t\t\t\tonclick='javascript:popupOpen(\"" . SELF . "?" . "key=print&cusnum={$cusnum}&stmnt_type={$stmnt_type}&" . "b64_comments=" . base64_encode($comments) . "&from_year={$from_year}" . "&from_month={$from_month}&from_day={$from_day}&to_year={$to_year}&" . "to_month={$to_month}&to_day={$to_day}\");' />\n\t\t\t\t\t</td>\n\t\t\t\t\t<td><input type='submit' value='Apply' style='font-weight: bold' /></td>\n\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t<input type='button' value='View PDF'\n\t\t\t\t\t\tonclick='javascript:popupOpen(\"pdf/pdf-statement.php?" . "key=cust_statement&cusnum={$cusnum}&stmnt_type={$stmnt_type}&" . "from_year={$from_year}&from_month={$from_month}&from_day={$from_day}&" . "to_year={$to_year}&to_month={$to_month}&to_day={$to_day}&" . "b64_comments=" . base64_encode($comments) . "\");' />\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t{$page_break}";
    }
    if ($stmnt_type == "open") {
        $show_bal_head = "";
    } else {
        $show_bal_head = "<th width='15%' {$bborder}>Balance</th>";
    }
    // Actual Statement per page
    for ($i = 1; $i <= $pages; $i++) {
        $stmnt_out = "";
        foreach ($stmnt_ar[$i] as $items_out) {
            $stmnt_out .= $items_out;
        }
        $OUTPUT .= "\n\t\t</form>\n\t\t<table cellpadding='5' cellspacing='2'' width='90%'>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='center'><b>Page {$i}</b></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td rowspan='2' valign='middle'>\n\t\t\t\t\t<h1>" . COMP_NAME . "</h3>\n\t\t\t\t</td>\n\t\t\t\t<td width='10%' align='center'>\n\t\t\t\t\t<h1>Statement</h3>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='center' nowrap>\n\t\t\t\t\t<h3>\n\t\t\t\t\t\t" . date("d-m-Y", strtotime($from_date)) . " -\n\t\t\t\t\t\t" . date("d-m-Y", strtotime($to_date)) . "\n\t\t\t\t\t</h3>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t\n\t\t{$br}\n\t\t\n\t\t<table cellpadding='0' cellspacing='0' width='90%'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top' {$rborder}>\n\t\t\t\t\t{$cust_data['surname']}<br />\n\t\t\t\t\t" . nl2br($cust_data["paddr1"]) . "<br />\n\t\t\t\t\t<br />\n\t\t\t\t\t<b>Account Number:</b> {$cust_data['accno']}<br />\n\t\t\t\t</td>\n\t\t\t\t\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t{$comp_data['compname']}<br />\n\t\t\t\t\t{$comp_data['addr1']}<br />\n\t\t\t\t\t{$comp_data['addr2']}<br />\n\t\t\t\t\t{$comp_data['addr3']}<br />\n\t\t\t\t\t{$comp_data['addr4']}<br />\n\t\t\t\t\t<br />\n\t\t\t\t\t<b>Tel:</b> {$comp_data['tel']}<br />\n\t\t\t\t\t<b>Fax:</b> {$comp_data['fax']}<br />\n\t\t\t\t\t<b>VAT Reg:</b> {$comp_data['vatnum']}<br />\n\t\t\t\t\t<b>Company Reg:</b> {$comp_data['regnum']}<br />\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t{$br}\n\t\t<table cellpadding='0' cellspacing='0' width='90%'>\n\t\t\t<tr>\n\t\t\t\t<th width='10%' {$thborder}>Date</th>\n\t\t\t\t<th width='10%' {$thborder}>Ref No.</th>\n\t\t\t\t<th width='10%' {$thborder}>Customer Ref No.</th>\n\t\t\t\t<th width='40%' {$thborder}>Details</th>\n\t\t\t\t<th width='15%' {$thborder}>Amount</th>\n\t\t\t\t{$show_bal_head}\n\t\t\t</tr>\n\t\t\t{$stmnt_out}\n\t\t</table>\n\t\t{$br}\n\t\t<table cellpadding='0' cellspacing='0' width='90%'>\n\t\t\t<tr>\n\t\t\t\t<td colspan='5' align='right'>\n\t\t\t\t\t&nbsp;\n\t\t\t\t\t<br />\n\t\t\t\t\t<b>Total Outstanding Balance:</b> " . sprint($balance) . "\n\t\t\t\t\t<br />\n\t\t\t\t\t&nbsp;\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td width='20%' {$aborder}>\n\t\t\t\t\t<b>120+ Days</b><br />\n\t\t\t\t\t{$age120}\n\t\t\t\t</td>\n\t\t\t\t<td width='20%' {$aborder}>\n\t\t\t\t\t<b>90 Days</b><br />\n\t\t\t\t\t{$age90}\n\t\t\t\t</td>\n\t\t\t\t<td width='20%' {$aborder}>\n\t\t\t\t\t<b>60 Days</b><br />\n\t\t\t\t\t{$age60}\n\t\t\t\t</td>\n\t\t\t\t<td width='20%' {$aborder}>\n\t\t\t\t\t<b>30 Days</b><br />\n\t\t\t\t\t{$age30}\n\t\t\t\t</td>\n\t\t\t\t<td width='20%' {$tborder}>\n\t\t\t\t\t<b>Current</b><br />\n\t\t\t\t\t{$curr}\n\t\t\t\t</td>\n\t\t</table>\n\n\t\t{$br}\t\t\n\n\t\t<table cellpadding='0' cellspacing='0' width=90%'>\n\t\t\t<tr>\n\t\t\t\t<td rowspan='5' {$rborder} width='50%'>" . nl2br($comments) . " &nbsp;</td>\n\t\t\t</tr>\n\t\t\t<tr><td>{$bank_data['bankname']} &nbsp;</td></tr>\n\t\t\t<tr><td><b>Branch:</b> {$bank_data['branchname']}</td></tr>\n\t\t\t<tr><td><b>Branch Code:</b> {$bank_data['branchcode']}</td></tr>\n\t\t\t<tr><td><b>Account Number:</b> {$bank_data['accnum']}</td></tr>\n\t\t</table>";
        if ($i >= 1) {
            $OUTPUT .= $page_break;
        }
    }
    $OUTPUT .= "\n\t</center>";
    require "tmpl-print.php";
}
function details($_GET)
{
    $showvat = TRUE;
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM sorders WHERE sordid = '{$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);
    /* --- Start some checks --- */
    # Check if stock was selected(yes = put done button)
    db_connect();
    $sql = "SELECT stkid FROM sorders_items WHERE sordid = '{$inv['sordid']}' AND div = '" . USER_DIV . "'";
    $crslt = db_exec($sql);
    if (pg_numrows($crslt) < 1) {
        $error = "<li class='err'> Error : Consignment number <b>{$invid}</b> has no items.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    /* --- End some checks --- */
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM sorders_items  WHERE sordid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        if ($stkd['account'] == 0) {
            # Get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # Get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            $vd = pg_fetch_array($Ri);
            if ($vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
                $showvat = FALSE;
            }
            // 			$vr=vatcalc($stkd['unitcost'],$inv['chrgvat'],$excluding,$inv['traddisc'],$vd['vat_amount']);
            // 			$vrs=explode("|",$vr);
            // 			$ivat=$vrs[0];
            // 			$iamount=$vrs[1];
            //
            // 			$vatamount += $ivat;
        } else {
            $wh['whname'] = "";
            $stk['stkcod'] = "";
            $stk['stkdes'] = $stkd['description'];
        }
        # Keep track of discounts
        $disc += $stkd['disc'];
        // Should we display the costs
        if ($inv["display_costs"] == "yes") {
            $products_costs = "\r\n\t\t\t\t\t<td nowrap>" . CUR . " {$stkd['unitcost']}</td>\r\n\t\t\t\t\t<td>{$stkd['disc']}</td>\r\n\t\t\t\t\t<td nowrap>" . CUR . " {$stkd['amt']}</td>\r\n\t\t\t\t</tr>";
        } else {
            $products_costs = "";
        }
        # Put in product
        $products .= "\r\n\t\t\t<tr valign='top'>\r\n\t\t\t\t<td>{$stk['stkcod']}</td>\r\n\t\t\t\t<td>{$stk['stkdes']}</td>\r\n\t\t\t\t<td>{$stkd['qty']}</td>\r\n\t\t\t\t{$products_costs}";
    }
    /* --- 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";
    }
    $VATP = TAX_VAT;
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    /*
    # minus discount
    # $SUBTOT -= $disc; --> already minused
    
    # duplicate
    $SUBTOTAL = $SUBTOT;
    
    # minus trade discount
    $SUBTOTAL -= $traddiscm;
    
    # add del charge
    $SUBTOTAL += $inv['delchrg'];
    
    
    # if vat must be charged
    if($inv['chrgvat'] == "yes"){
    	$VATP = TAX_VAT;
    	$VAT = sprintf("%01.2f", (($VATP/100) * $SUBTOTAL));
    }else{
    	$VATP = 0;
    	$VAT = "0.00";
    }
    
    # total
    $TOTAL = sprint($SUBTOTAL + $VAT);
    */
    /* --- End Some calculations --- */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    # Avoid little box
    if (strlen($inv['comm']) > 0) {
        $inv['comm'] = "\r\n\t\t\t<table border=1 cellspacing='0' bordercolor='#000000'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>" . nl2br($inv['comm']) . "</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>";
    }
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Should we display the costs
    if ($inv["display_costs"] == "yes") {
        $headings_costs = "\r\n\t\t\t<td><b>UNIT PRICE</b></td>\r\n\t\t\t<td><b>UNIT DISCOUNT</b></td>\r\n\t\t\t<td><b>AMOUNT</b></td>";
        $totals_costs = "\r\n\t\t\t</td>\r\n\t\t\t<td align='right' colspan='3'>\r\n\t\t\t\t<table cellpadding='5' cellspacing='0' border='1' width='50%' bordercolor='#000000'>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td><b>SUBTOTAL</b></td>\r\n\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$SUBTOT}</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td><b>Trade Discount</b></td>\r\n\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$inv['discount']}</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td><b>Delivery Charge</b></td>\r\n\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$inv['delivery']}</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td><b>VAT {$vat14}</b></td>\r\n\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$VAT}</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td><b>GRAND TOTAL<b></td>\r\n\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$TOTAL}</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</table>";
    } else {
        $headings_costs = "";
        $totals_costs = "";
    }
    if (isset($inv['proforma']) and $inv['proforma'] == "yes") {
        $header = "Proforma Invoice";
    } else {
        $header = "Sales Order";
    }
    // check for cust
    if ($inv['cusnum'] != "0") {
        $get_bankid = "SELECT bankid FROM customers WHERE cusnum = '{$inv['cusnum']}' LIMIT 1";
        $run_bankid = db_exec($get_bankid) or errDie("Unable to get banking information.");
        if (pg_numrows($run_bankid) > 0) {
            $barr = pg_fetch_array($run_bankid);
        }
    } else {
        #no customer chosen, use default account only if there is 1
        $get_bankid = "SELECT bankid FROM bankacct";
        $run_bankid = db_exec($get_bankid) or errDie("Unable to get bank information.");
        if (pg_numrows($run_bankid) == 1) {
            $barr = pg_fetch_array($run_bankid);
        }
    }
    // Retrieve the banking information
    $bank_data = qryBankAcct($barr['bankid']);
    if (isset($inv['del_addr']) and strlen($inv['del_addr']) > 0) {
        $showdelivery = "<b>Delivery Address:</b><br>{$inv['del_addr']}";
    } else {
        $showdelivery = "";
    }
    /* -- Final Layout -- */
    $details = "\r\n\t\t<center>\r\n\t\t<h2>{$header}</h2>\r\n\t\t<table cellpadding='0' cellspacing='4' border=0 width='770'>\r\n\t\t\t<tr>\r\n\t\t\t\t<td valign='top' width='30%'>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td>{$inv['surname']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td>{$inv['cordno']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td>" . nl2br($inv['cusaddr']) . "</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td>(Vat No. {$inv['cusvatno']})</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td>{$showdelivery}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t\t<td valign='top' width='30%'>\r\n\t\t\t\t\t" . COMP_NAME . "<br>\r\n\t\t\t\t\t" . COMP_ADDRESS . "<br>\r\n\t\t\t\t\t" . COMP_TEL . "<br>\r\n\t\t\t\t\t" . COMP_FAX . "<br>\r\n\t\t\t\t\tReg No. " . COMP_REGNO . "<br>\r\n\t\t\t\t\tVAT No. " . COMP_VATNO . "<br>\r\n\t\t\t\t</td>\r\n\t\t\t\t<td align='left' width='20%' valign='top'>\r\n\t\t\t\t\t<img src='compinfo/getimg.php' width='230' height='47'><br><br>\r\n\t\t\t\t\t{$bank_data['bankname']}<br>\r\n\t\t\t\t\t{$bank_data['branchname']}<br>\r\n\t\t\t\t\t{$bank_data['branchcode']}<br>\r\n\t\t\t\t\t{$bank_data['accnum']}<br>\r\n\t\t\t\t</td>\r\n\t\t\t\t<td valign='bottom' align='right' width='20%'>\r\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='1' bordercolor='#000000'>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td><b>Sales Order No.</b></td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$inv['sordid']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td><b>Order No.</b></td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$inv['ordno']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td><b>Terms</b></td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$inv['terms']} Days</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td><b>Date</b></td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$inv['odate']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td><b>Vat</b></td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$inv['chrgvat']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr><td><br></td></tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td colspan='4'>\r\n\t\t\t\t\t<table cellpadding='5' cellspacing='0' border=1 width=100% bordercolor='#000000'>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td><b>ITEM NUMBER</b></td>\r\n\t\t\t\t\t\t\t<td width=45%><b>DESCRIPTION</b></td>\r\n\t\t\t\t\t\t\t<td><b>QTY</b></td>\r\n\t\t\t\t\t\t\t{$headings_costs}\r\n\t\t\t\t\t\t{$products}\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>\r\n\t\t\t\t\t{$inv['comm']}\r\n\t\t\t\t\t{$totals_costs}\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td colspan='5'>\r\n\t\t\t\t\t<table border=0>\r\n\t\t\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t\t\t\t<tr><td>Signature: __________________________________________</td></tr>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr><td><br></td></tr>\r\n\t\t</table>\r\n\t\t</center>";
    $OUTPUT = $details;
    require "tmpl-print.php";
}
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 templatePdf($_POST)
{
    extract($_POST);
    global $set_mainFont;
    $pdf =& new Cezpdf();
    $pdf->selectFont($set_mainFont);
    // Validate
    require_lib("validate");
    $v = new Validate();
    foreach ($invids as $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    }
    // Any errors?
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=error>{$e['msg']}</li>";
        }
        $OUTPUT = $confirm;
        require "template.php";
    }
    $ai = 0;
    foreach ($invids as $invid) {
        if ($ai) {
            $pdf->ezNewPage();
        }
        ++$ai;
        // Invoice info
        db_conn("cubit");
        $sql = "SELECT * FROM nons_invoices WHERE invid='{$invid}' AND DIV='" . USER_DIV . "'";
        $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice info.");
        if (pg_num_rows($invRslt) == 0) {
            return "<li class=err>Not found</li>";
        }
        $inv = pg_fetch_array($invRslt);
        // 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);
        $bnkData = qryBankAcct(cust_bank_id($inv["cusid"]));
        $compinfo = array();
        $compinfo[] = array($comp["addr1"], "{$comp['paddr1']}");
        $compinfo[] = array($comp["addr2"], "{$comp['paddr2']}");
        $compinfo[] = array($comp["addr3"], "{$comp['paddr3']}");
        $compinfo[] = array($comp["addr4"], "{$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);
        if ($data['value'] == "Yes") {
            $sp = "<b>Sales Person: </b>{$inv['salespn']}";
        } else {
            $sp = "";
        }
        $docinfo = array(array("<b>Invoice No:</b> {$inv['invnum']}"), array("<b>Proforma Inv No:</b> {$inv['docref']}"), array("{$sp}"));
        // Customer info ---------------------------------------------------------
        if ($inv["cusid"] != 0) {
            db_conn("cubit");
            $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
            $cusRslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
            $cusData = pg_fetch_array($cusRslt);
        } else {
            $cusData["surname"] = $inv["cusname"];
            $cusData["addr1"] = $inv["cusaddr"];
            $cusData["paddr1"] = "";
            $cusData["accno"] = "";
        }
        $cusinfo = array(array("<b>{$cusData['surname']}</b>"));
        $cusaddr = explode("\n", $cusData['paddr1']);
        foreach ($cusaddr as $v) {
            $cusinfo[] = array(pdf_lstr($v, 40));
        }
        $cusinfo[] = array("<b>Account no: </b>{$cusData['accno']}");
        $cusdaddr = array(array("<b>Physical Address:</b>"));
        $cusaddr = explode("\n", $cusData['addr1']);
        foreach ($cusaddr as $v) {
            $cusdaddr[] = array(pdf_lstr($v, 40));
        }
        // 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 nons_inv_items WHERE invid='{$invid}' AND DIV='" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        while ($stkd = pg_fetch_array($stkdRslt)) {
            // Check Tax Excempt
            db_conn("cubit");
            $sql = "SELECT zero FROM vatcodes WHERE id='{$stkd['vatex']}'";
            $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 = "";
            }
            $items[] = array("Description" => pdf_lstr($ex . $stkd['description'], 65), "Qty" => $stkd['qty'], "Unit Price" => CUR . $stkd['unitcost'], "Amount" => CUR . $stkd['amt']);
        }
        // Comment ---------------------------------------------------------------
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
        $commentRslt = db_exec($sql) or errDie("Unable to retrieve the default comment from Cubit.");
        $default_comment = pg_fetch_result($commentRslt, 0);
        $comment = array(array("<i>VAT Exempt Indicator: #</i>"), array(base64_decode($default_comment)));
        // Box to sign in --------------------------------------------------------
        $sign = array(array("<i>Thank you for your support</i>"), array(''), array("<b>Received in good order by:</b> ____________________"), array(''), array("                                      <b>Date:</b> ____________________"));
        // Totals ----------------------------------------------------------------
        $totals = array(array("1" => "<b>Subtotal:</b> ", "2" => CUR . "{$inv['subtot']}"), array("1" => "<b>VAT @ " . TAX_VAT . "%:</b> ", "2" => CUR . "{$inv['vat']}"), array("1" => "<b>Total Incl VAT:</b> ", "2" => CUR . "{$inv['total']}"));
        $totCols = array("1" => array("width" => 90), "2" => array("justification" => "right"));
        $ic = 0;
        while (++$ic * 20 < 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>Tax Invoice</b>", 18, $heading_pos['x'] - 120, $heading_pos['y'] / 2 + 9);
            $compinfo_pos = drawTable(&$pdf, $compinfo, 0, $heading_pos['y'], 320, 8);
            $date_pos = drawTable(&$pdf, $date, $compinfo_pos['x'], $heading_pos['y'], 100, 4);
            $pagenr_pos = drawTable(&$pdf, $pagenr, $date_pos['x'], $heading_pos['y'], 100, 4);
            $docinfo_pos = drawTable(&$pdf, $docinfo, $compinfo_pos['x'], $date_pos['y'], 200, 4);
            $cusinfo_pos = drawTable(&$pdf, $cusinfo, 0, $compinfo_pos['y'], 320, 10);
            $cusdaddr_pos = drawTable(&$pdf, $cusdaddr, $cusinfo_pos['x'], $compinfo_pos['y'], 200, 10);
            $regnos_pos = drawTable(&$pdf, $regnos, 0, $cusinfo_pos['y'], 520, 2);
            $items_start = $i * 20;
            if ($items_start >= count($items) - 20) {
                $items_end = count($items) - 1;
            } else {
                $items_end = ($i + 1) * 20;
            }
            $items_print = array();
            for ($j = $items_start; $j <= $items_end; $j++) {
                $items_print[$j] = $items[$j];
            }
            // Adjust the column widths
            $cols = array("Description" => array("width" => 310), "Qty" => array("width" => 50), "Unit Price" => array("width" => 80, "justification" => "right"), "Amount" => array("width" => 80, "justification" => "right"));
            $items_pos = drawTable(&$pdf, $items_print, 0, $regnos_pos['y'] + 2, 520, 20, $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);
        }
    }
    $pdf->ezStream();
}
function confirm($_POST)
{
    extract($_POST);
    if (isset($back)) {
        return method($cusid);
    }
    //	$date = "$date_day-$date_month-$date_year";
    $amt = sprint(array_sum($paidamt));
    $setamt = sprint(array_sum($stock_setamt));
    if (!isset($print_recpt)) {
        $print_recpt = "";
    }
    if (!isset($descript) or strlen($descript) < 1) {
        $descript = $reference;
    }
    if (!isset($out1)) {
        $out1 = '';
    }
    if (!isset($out2)) {
        $out2 = '';
    }
    if (!isset($out3)) {
        $out3 = '';
    }
    if (!isset($out4)) {
        $out4 = '';
    }
    if (!isset($out5)) {
        $out5 = '';
    }
    $date = "{$date_year}-{$date_month}-{$date_day}";
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($descript, "string", 1, 255, "Invalid Description.");
    $v->isOk($reference, "string", 1, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 40, "Invalid amount.");
    $v->isOk($setamt, "float", 1, 40, "Invalid Settlement Amount.");
    $v->isOk($setvat, "string", 1, 10, "Invalid Settlement VAT Option.");
    $v->isOk($setvatcode, "string", 1, 40, "Invalid Settlement VAT code");
    //	$v->isOk($out, "float", 1, 40, "Invalid out amount.");
    $v->isOk($out1, "float", 0, 40, "Invalid paid amount(currant).");
    $v->isOk($out2, "float", 0, 40, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 40, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 40, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 40, "Invalid paid amount(120).");
    $v->isOk($cusid, "num", 1, 10, "Invalid customer number.");
    $v->isOk($overpay, "float", 1, 40, "Invalid Unallocated Amount.");
    $v->isOk($print_recpt, "string", 0, 10, "Invalid Print Receipt Setting.");
    if ($amt + $overpay <= 0) {
        $v->addError(0, "Invalid Amount Allocated To Receipt.");
    }
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            if ($paidamt[$key] < 0.01) {
                continue;
            }
            if (!isset($stock_setamt[$key]) or strlen($stock_setamt[$key]) < 1) {
                $stock_setamt[$key] = 0;
            }
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No. [{$key}]");
            $v->isOk($paidamt[$key], "float", 1, 40, "Invalid amount to be paid. [{$key}]");
            $v->isOk($stock_setamt[$key], "float", 1, 40, "Invalid Settlement Discount Amount");
        }
    }
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['OUT1'] = $out1 + 0;
        $_POST['OUT2'] = $out2 + 0;
        $_POST['OUT3'] = $out3 + 0;
        $_POST['OUT4'] = $out4 + 0;
        $_POST['OUT5'] = $out5 + 0;
        return $confirm . alloc($_POST);
    }
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= 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>";
    }
    $out += 0;
    $OUT1 = $out1 + 0;
    $OUT2 = $out2 + 0;
    $OUT3 = $out3 + 0;
    $OUT4 = $out4 + 0;
    $OUT5 = $out5 + 0;
    $tot = 0;
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            if ($paidamt[$key] < 0.01) {
                continue;
            }
            $tot += $paidamt[$key];
        }
    }
    if (isset($open_amount)) {
        $tot += array_sum($open_amount);
    }
    $tot = sprint($tot);
    $amt = sprint($amt);
    $out = sprint($out);
    if (sprint($tot + $out + $out1 + $out2 + $out3 + $out4 + $out5 - $amt) > sprint(0)) {
        $_POST['OUT1'] = $OUT1;
        $_POST['OUT2'] = $OUT2;
        $_POST['OUT3'] = $OUT3;
        $_POST['OUT4'] = $OUT4;
        $_POST['OUT5'] = $OUT5;
        return "<li class='err'>The total amount for invoices is greater than the amount received.\n\t\t\tPlease check the details.</li>" . alloc($_POST);
    }
    if (sprint($setamt) > 0) {
        if (array_sum($stock_setamt) != $setamt) {
            return "<li class='err'>The total settlement amount for invoices is not equal to the amount received.\n\t\t\tPlease check the details.</li>" . alloc($_POST);
        }
    }
    if (isset($bout)) {
        $out = $bout;
    }
    if (!isset($overpay)) {
        $overpay = 0;
    }
    $overpay = sprint($overpay);
    #generate a receipt number
    $receiptnumber = divlastid("receipt");
    $confirm = "\n\t\t<h3>New Bank Receipt</h3>\n\t\t<h4>Confirm entry (Please check the details)</h4>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='write'>\n\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t\t<input type='hidden' name='date' value='{$date}'>\n\t\t\t<input type='hidden' name='cusid' value='{$cusid}'>\n\t\t\t<input type='hidden' name='descript' value='{$descript}'>\n\t\t\t<input type='hidden' name='reference' value='{$reference}'>\n\t\t\t<input type='hidden' name='cheqnum' value='{$cheqnum}'>\n\t\t\t<input type='hidden' name='all' value='{$all}'>\n\t\t\t<input type='hidden' name='out' value='{$out}'>\n\t\t\t<input type='hidden' name='date_day' value='{$date_day}'>\n\t\t\t<input type='hidden' name='date_month' value='{$date_month}'>\n\t\t\t<input type='hidden' name='date_year' value='{$date_year}'>\n\t\t\t<input type='hidden' name='overpay' value='{$overpay}'>\n\t\t\t<input type='hidden' name='OUT1' value='{$OUT1}'>\n\t\t\t<input type='hidden' name='OUT2' value='{$OUT2}'>\n\t\t\t<input type='hidden' name='OUT3' value='{$OUT3}'>\n\t\t\t<input type='hidden' name='OUT4' value='{$OUT4}'>\n\t\t\t<input type='hidden' name='OUT5' value='{$OUT5}'>\n\t\t\t<input type='hidden' name='amt' value='{$amt}'>\n\t\t\t<input type='hidden' name='setamt' value='{$setamt}'>\n\t\t\t<input type='hidden' name='setvat' value='{$setvat}'>\n\t\t\t<input type='hidden' name='setvatcode' value='{$setvatcode}'>\n\t\t\t<input type='hidden' name='print_recpt' value='{$print_recpt}'>\n\t\t<table " . TMPL_tblDflts . ">";
    /* bank account name */
    if ($bankid == "0" or ($bank = qryBankAcct($bankid, "accname, bankname")) === false) {
        $bank['accname'] = "Cash";
        $bank['bankname'] = "";
    }
    /* customer name */
    $cus = qryCustomer($cusid, "accno, cusname, surname");
    if ($setvat == "inc") {
        $showsetvat = "VAT Inclusive";
    } else {
        $showsetvat = "No VAT";
    }
    //	$overpay = sprint ($amt - array_sum($paidamt));
    $overpay = sprint($overpay);
    if ($overpay < 0) {
        $overpay = 0.0;
    }
    if ($print_recpt == "yes") {
        $show_print_recpt = "Yes";
    } else {
        $show_print_recpt = "No";
    }
    $confirm .= "\n\t\t<tr>\n\t\t\t<th>Field</th>\n\t\t\t<th>Value</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Account</td>\n\t\t\t<td>{$bank['accname']} - {$bank['bankname']}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Payment Date</td>\n\t\t\t<td valign='center'>{$date}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Received from</td>\n\t\t\t<td valign='center'>{$cus['accno']} - {$cus['cusname']} {$cus['surname']}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Description</td>\n\t\t\t<td valign='center'>{$descript}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Reference</td>\n\t\t\t<td valign='center'>{$reference}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Cheque Number</td>\n\t\t\t<td valign='center'>{$cheqnum}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Amount</td>\n\t\t\t<td valign='center'>" . CUR . " {$amt}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Settlement Discount</td>\n\t\t\t<td valign='center'>" . CUR . " {$setamt} {$showsetvat}</td>\n\t\t</tr>\n\t\t" . TBL_BR . "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Print Receipt</td>\n\t\t\t<td>{$show_print_recpt}</td>\n\t\t</tr>\n\t\t" . TBL_BR . "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='5'><b>A general transaction will credit the client's account with " . CUR . " {$overpay} </b></td>\n\t\t</tr>";
    if (sprint($setamt) > 0) {
        $doset = TRUE;
    } else {
        $doset = FALSE;
    }
    /* OPTION 3 : ALLOCATE TO EACH INVOICE (confirm) */
    if ($all == 2) {
        if ($doset) {
            $showsethead = "<th>Settlement</th>";
        } else {
            $showsethead = "";
        }
        // Layout
        $confirm .= "\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><h3>Invoices</h3></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Invoice Number</th>\n\t\t\t\t<th>Outstanding amount</th>\n\t\t\t\t<th>Terms</th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t\t{$showsethead}\n\t\t\t</tr>";
        $i = 0;
        foreach ($invids as $key => $value) {
            if ($paidamt[$key] < 0.01) {
                continue;
            }
            $paidamt[$key] = sprint($paidamt[$key]);
            $ii = $invids[$key];
            if (!isset($itype[$key]) && !isset($ptype[$key])) {
                /* STOCK INVOICE ! */
                db_connect();
                $sql = "SELECT invnum,invid,balance,terms,odate FROM invoices\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to access database.");
                if (pg_numrows($invRslt) < 1) {
                    return "<li class='err'> -S- Invalid ord number {$invids[$key]}.</li>";
                }
                $inv = pg_fetch_array($invRslt);
                $invid = $inv['invid'];
                #handle warnings ...
                if ($paidamt[$invid] + $stock_setamt[$invid] < sprint($inv['balance'])) {
                    $warning = "<td><li class='err'>Paying Less Than Total Amount.</li></td>";
                } elseif ($paidamt[$invid] + $stock_setamt[$invid] > sprint($inv['balance'])) {
                    $warning = "<td><li class='err'>Paying More Than Total Amount Outstanding.</li></td>";
                } else {
                    $warning = "";
                }
                if ($doset) {
                    if (!isset($stock_setamt[$invid])) {
                        $stock_setamt[$invid] = "";
                    }
                    $showset = "<td>" . CUR . " " . sprint($stock_setamt[$invid]) . "</td>";
                } else {
                    $showset = "<td></td>";
                }
                $confirm .= "\n\t\t\t\t\t<input type='hidden' name='paidamt[{$key}]' size='7' value='{$paidamt[$invid]}'>\n\t\t\t\t\t<input type='hidden' name='stock_setamt[{$key}]' value='{$stock_setamt[$invid]}'>\n\t\t\t\t\t<input type='hidden' size='20' name='invids[{$key}]' value='{$inv['invid']}'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$paidamt[$key]}</td>\n\t\t\t\t\t\t{$showset}\n\t\t\t\t\t\t{$warning}\n\t\t\t\t\t</tr>";
            } else {
                if (!isset($ptype[$key])) {
                    /* NON STOCK INVOICE ! */
                    db_connect();
                    $sql = "SELECT invnum,invid,balance,sdate as odate FROM nons_invoices\n\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to access database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'> -N- Invalid ord number {$invids[$key]}.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    $invid = "i" . $inv['invid'];
                    #handle warnings ...
                    if ($paidamt[$invid] + $stock_setamt[$invid] < sprint($inv['balance'])) {
                        $warning = "<td><li class='err'>Paying Less Than Total Amount.</li></td>";
                    } elseif ($paidamt[$invid] + $stock_setamt[$invid] > sprint($inv['balance'])) {
                        $warning = "<td><li class='err'>Paying More Than Total Amount Outstanding.</li></td>";
                    } else {
                        $warning = "";
                    }
                    if ($doset) {
                        if (!isset($stock_setamt[$invid])) {
                            $stock_setamt[$invid] = "";
                        }
                        $showset = "<td>" . CUR . " " . sprint($stock_setamt[$invid]) . "</td>";
                    } else {
                        $showset = "<td></td>";
                    }
                    $confirm .= "\n\t\t\t\t\t<input type='hidden' size='20' name='invids[{$key}]' value='{$inv['invid']}'>\n\t\t\t\t\t<input type='hidden' name='paidamt[{$key}]' size='7' value='" . $paidamt[$key] . "'>\n\t\t\t\t\t<input type='hidden' name='stock_setamt[{$key}]' value='{$stock_setamt[$key]}'>\n\t\t\t\t\t<input type='hidden' name='itype[{$key}]' value='PcP'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t<td>" . CUR . " " . $paidamt[$key] . "</td>\n\t\t\t\t\t\t{$showset}\n\t\t\t\t\t\t{$warning}\n\t\t\t\t\t</tr>";
                } else {
                    /* POS INVOICE ! */
                    $sqls = array();
                    for ($i = 1; $i <= 12; ++$i) {
                        $sqls[] = "SELECT invnum,invid,balance,odate FROM \"{$i}\".pinvoices WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    }
                    $sql = implode(" UNION ", $sqls);
                    // (1jun07) only checks the current prd ??????
                    //				db_conn(PRD_DB);
                    //				$sql = "SELECT invnum,invid,balance,odate FROM pinvoices
                    //						WHERE invid = '$invids[$key]' AND div = '".USER_DIV."'";
                    $invRslt = db_exec($sql) or errDie("Unable to access database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'> -P- Invalid ord number {$invids[$key]}.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    $invid = "p" . $inv['invid'];
                    #handle warnings ...
                    if ($paidamt[$invid] + $stock_setamt[$invid] < sprint($inv['balance'])) {
                        $warning = "<td><li class='err'>Paying Less Than Total Amount.</li></td>";
                    } elseif ($paidamt[$invid] + $stock_setamt[$invid] > sprint($inv['balance'])) {
                        $warning = "<td><li class='err'>Paying More Than Total Amount Outstanding.</li></td>";
                    } else {
                        $warning = "";
                    }
                    if ($doset) {
                        if (!isset($stock_setamt[$invid])) {
                            $stock_setamt[$invid] = "";
                        }
                        $showset = "<td>" . CUR . " " . sprint($stock_setamt[$invid]) . "</td>";
                    } else {
                        $showset = "<td></td>";
                    }
                    $confirm .= "\n\t\t\t\t\t<input type='hidden' size='20' name='invids[{$key}]' value='{$inv['invid']}'>\n\t\t\t\t\t<input type='hidden' name='paidamt[{$key}]' size='7' value='" . $paidamt[$key] . "'>\n\t\t\t\t\t<input type='hidden' name='stock_setamt[{$key}]' value='{$stock_setamt[$key]}'>\n\t\t\t\t\t<input type='hidden' name='ptype[{$key}]' value='PcP'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t<td>" . CUR . " " . $paidamt[$key] . "</td>\n\t\t\t\t\t\t{$showset}\n\t\t\t\t\t\t{$warning}\n\t\t\t\t\t</tr>";
                }
            }
        }
        if (open()) {
            db_conn('cubit');
            $Sl = "SELECT * FROM open_stmnt WHERE balance>0 AND cusnum='{$cusid}' ORDER BY date";
            $Ri = db_exec($Sl) or errDie("Unable to get open items.");
            //$open_out=$out;
            $ox = "";
            $i = 0;
            while ($od = pg_fetch_array($Ri)) {
                $oid = $od['id'];
                if (!isset($open_amount[$oid]) || $open_amount[$oid] == 0) {
                    continue;
                }
                $ox .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$oid}]' value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t</tr>";
                $i++;
            }
            $confirm .= "\n\t\t\t\t<tr><td colspan='2'><br></td></tr>\n\t\t\t\t<tr><td colspan='2'>\n\t\t\t\t\t<h3>Outstanding Transactions</h3></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t<th>Amount</th>\n\t\t\t\t</tr>\n\t\t\t\t{$ox}";
        }
    }
    vsprint($out);
    vsprint($out1);
    vsprint($out2);
    vsprint($out3);
    vsprint($out4);
    vsprint($out5);
    /*
    	<tr>
    		<td colspan='5' align='right'><input type='submit' name='batch' value='Add To Batch'></td>
    	</tr>
    */
    $confirm .= "\n\t\t<input type='hidden' name='out1' value='{$out1}'>\n\t\t<input type='hidden' name='out2' value='{$out2}'>\n\t\t<input type='hidden' name='out3' value='{$out3}'>\n\t\t<input type='hidden' name='out4' value='{$out4}'>\n\t\t<input type='hidden' name='out5' value='{$out5}'>\n\t\t" . TBL_BR . "\n\t\t<tr>\n\t\t\t<td><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t<td align='right' colspan='4'><input type='submit' value='Write &raquo'></td>\n\t\t</tr>\n\t\t</table>\n\t\t</form>" . mkQuickLinks(ql("../core/trans-new.php", "Journal Transactions"), ql("../customers-view.php", "View Customers"));
    return $confirm;
}
function confirm($_POST)
{
    extract($_POST);
    if (isset($back)) {
        header("Location: bank-recpt-inv.php?cusnum={$cusid}&descript={$descript}&reference={$reference}&amt={$amt}");
        die;
    }
    if (!isset($print_recpt)) {
        $print_recpt = "";
    }
    if (isset($bulk_pay) and strlen($bulk_pay) > 0) {
        $send_bulk = "<input type='hidden' name='bulk_pay' value='yes'>";
    } else {
        $send_bulk = "";
    }
    if (!isset($out1)) {
        $out1 = '';
    }
    if (!isset($out2)) {
        $out2 = '';
    }
    if (!isset($out3)) {
        $out3 = '';
    }
    if (!isset($out4)) {
        $out4 = '';
    }
    if (!isset($out5)) {
        $out5 = '';
    }
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 40, "Invalid amount.");
    //	$v->isOk($out, "float", 1, 40, "Invalid out amount.");
    $v->isOk($out1, "float", 0, 40, "Invalid paid amount(currant).");
    $v->isOk($out2, "float", 0, 40, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 40, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 40, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 40, "Invalid paid amount(120).");
    $v->isOk($cusid, "num", 1, 10, "Invalid customer number.");
    $v->isOk($print_recpt, "string", 0, 10, "Invalid Print Receipt Setting.");
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            if ($paidamt[$key] < 0.01) {
                continue;
            }
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No. [{$key}]");
            $v->isOk($paidamt[$key], "float", 1, 40, "Invalid amount to be paid. [{$key}]");
        }
    }
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['OUT1'] = $out1 + 0;
        $_POST['OUT2'] = $out2 + 0;
        $_POST['OUT3'] = $out3 + 0;
        $_POST['OUT4'] = $out4 + 0;
        $_POST['OUT5'] = $out5 + 0;
        return $confirm . alloc($_POST);
    }
    $out += 0;
    $OUT1 = $out1 + 0;
    $OUT2 = $out2 + 0;
    $OUT3 = $out3 + 0;
    $OUT4 = $out4 + 0;
    $OUT5 = $out5 + 0;
    $tot = 0;
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            if ($paidamt[$key] < 0.01) {
                continue;
            }
            $tot += $paidamt[$key];
        }
    }
    if (isset($open_amount)) {
        $tot += array_sum($open_amount);
    }
    $tot = sprint($tot);
    $amt = sprint($amt);
    $out = sprint($out);
    if (sprint($tot + $out + $out1 + $out2 + $out3 + $out4 + $out5 - $amt) != sprint(0)) {
        $_POST['OUT1'] = $OUT1;
        $_POST['OUT2'] = $OUT2;
        $_POST['OUT3'] = $OUT3;
        $_POST['OUT4'] = $OUT4;
        $_POST['OUT5'] = $OUT5;
        return "<li class='err'>The total amount for invoices not equal to the amount received.\n\t\t\tPlease check the details.</li>" . alloc($_POST);
    }
    if (isset($bout)) {
        $out = $bout;
    }
    $confirm = "\n\t\t<h3>New Bank Receipt</h3>\n\t\t<h4>Confirm entry (Please check the details)</h4>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='write'>\n\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t\t<input type='hidden' name='date' value='{$date}'>\n\t\t\t<input type='hidden' name='cusid' value='{$cusid}'>\n\t\t\t<input type='hidden' name='descript' value='{$descript}'>\n\t\t\t<input type='hidden' name='reference' value='{$reference}'>\n\t\t\t<input type='hidden' name='cheqnum' value='{$cheqnum}'>\n\t\t\t<input type='hidden' name='all' value='{$all}'>\n\t\t\t<input type='hidden' name='out' value='{$out}'>\n\t\t\t<input type='hidden' name='date_day' value='{$date_day}'>\n\t\t\t<input type='hidden' name='date_month' value='{$date_month}'>\n\t\t\t<input type='hidden' name='date_year' value='{$date_year}'>\n\t\t\t<input type='hidden' name='OUT1' value='{$OUT1}'>\n\t\t\t<input type='hidden' name='OUT2' value='{$OUT2}'>\n\t\t\t<input type='hidden' name='OUT3' value='{$OUT3}'>\n\t\t\t<input type='hidden' name='OUT4' value='{$OUT4}'>\n\t\t\t<input type='hidden' name='OUT5' value='{$OUT5}'>\n\t\t\t<input type='hidden' name='amt' value='{$amt}'>\n\t\t\t<input type='hidden' name='print_recpt' value='{$print_recpt}'>\n\t\t\t{$send_bulk}\n\t\t<table " . TMPL_tblDflts . ">";
    /* bank account name */
    if ($bankid == "0" or ($bank = qryBankAcct($bankid, "accname, bankname")) === false) {
        $bank['accname'] = "Cash";
        $bank['bankname'] = "";
    }
    /* customer name */
    $cus = qryCustomer($cusid, "cusname, surname");
    if ($print_recpt == "yes") {
        $show_print_recpt = "Yes";
    } else {
        $show_print_recpt = "No";
    }
    $confirm .= "\n\t<tr>\n\t\t<th>Field</th>\n\t\t<th>Value</th>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Account</td>\n\t\t<td>{$bank['accname']} - {$bank['bankname']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Date</td>\n\t\t<td valign='center'>{$date}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Received from</td>\n\t\t<td valign='center'>{$cus['cusname']} {$cus['surname']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Description</td>\n\t\t<td valign='center'>{$descript}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Reference</td>\n\t\t<td valign='center'>{$reference}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Cheque Number</td>\n\t\t<td valign='center'>{$cheqnum}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Amount</td>\n\t\t<td valign='center'>" . CUR . " {$amt}</td>\n\t</tr>\n\t" . TBL_BR . "\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Print Receipt</td>\n\t\t<td>{$show_print_recpt}</td>\n\t</tr>";
    /* OPTION 1 : AUTO ALLOCATE (confirm) */
    if ($all == 0) {
        // Layout
        $confirm .= "\n\t\t" . TBL_BR . "\n\t\t<tr>\n\t\t\t<td colspan='2'><h3>Invoices</h3></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th>Invoice Number</th>\n\t\t\t<th>Outstanding amount</th>\n\t\t\t<th>Terms</th>\n\t\t\t<th>Date</th>\n\t\t\t<th>Amount</th>\n\t\t</tr>";
        $i = 0;
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                if ($paidamt[$invids[$key]] < 0.01) {
                    continue;
                }
                db_connect();
                $ii = $invids[$key];
                if (!isset($itype[$ii]) && !isset($ptype[$ii])) {
                    # Get all the details
                    $sql = "SELECT invnum,invid,balance,terms,odate FROM invoices\n\t\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to access database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'> - Invalid ord number {$invids[$key]}.";
                    }
                    $inv = pg_fetch_array($invRslt);
                    $invid = $inv['invid'];
                    $confirm .= "\n\t\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' size='7' value='{$paidamt[$invid]}'>\n\t\t\t\t\t<input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$paidamt[$invid]}</td>\n\t\t\t\t\t</tr>";
                } else {
                    if (!isset($ptype[$ii])) {
                        $sql = "SELECT invnum,invid,balance,sdate as odate FROM nons_invoices\n\t\t\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                        $invRslt = db_exec($sql) or errDie("Unable to access database.");
                        if (pg_numrows($invRslt) < 1) {
                            return "<li class='err'> - Invalid ord number {$invids[$key]}.</li>";
                        }
                        $inv = pg_fetch_array($invRslt);
                        $invid = $inv['invid'];
                        $confirm .= "\n\t\t\t\t\t<input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' size='7' value='{$paidamt[$invid]}'>\n\t\t\t\t\t<input type='hidden' name='itype[{$invid}]' value='y'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$paidamt[$invid]}</td>\n\t\t\t\t\t</tr>";
                    } else {
                        $sqls = array();
                        for ($i = 1; $i <= 12; ++$i) {
                            $sqls[] = "SELECT invnum,invid,balance,odate FROM \"{$i}\".pinvoices WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                        }
                        $sql = implode(" UNION ", $sqls);
                        $prnInvRslt = db_exec($sql);
                        $inv = pg_fetch_array($prnInvRslt);
                        $invid = $inv['invid'];
                        $paidamt[$invid] = sprint($paidamt[$invid]);
                        $confirm .= "\n\t\t\t\t\t<input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' size='7' value='{$paidamt[$invid]}'>\n\t\t\t\t\t<input type='hidden' name='ptype[{$invid}]' value='y'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$paidamt[$invid]}</td>\n\t\t\t\t\t</tr>";
                    }
                }
            }
        }
        if ($out > 0) {
            /* START OPEN ITEMS */
            $ox = "";
            db_conn('cubit');
            $sql = "SELECT * FROM open_stmnt WHERE balance>0 AND cusnum='{$cusid}' ORDER BY date";
            $rslt = db_exec($sql) or errDie("Unable to get open items.");
            $open_out = $out;
            $i = 0;
            while ($od = pg_fetch_array($rslt)) {
                if ($open_out == 0) {
                    continue;
                }
                $oid = $od['id'];
                if ($open_out >= $od['balance']) {
                    $open_amount[$oid] = $od['balance'];
                    $open_out = sprint($open_out - $od['balance']);
                    $ox .= "\n\t\t\t\t\t\t<input type='hidden' size='20' name='open[{$oid}]' value='{$oid}'>\n\t\t\t\t\t\t<input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>{$od['type']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t\t</tr>";
                } else {
                    if ($open_out < $od['balance']) {
                        $open_amount[$oid] = $open_out;
                        $open_out = 0;
                        $ox .= "\n\t\t\t\t\t\t<input type='hidden' size='20' name='open[{$oid}]' value='{$od['id']}'>\n\t\t\t\t\t\t<input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>{$od['type']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t\t</tr>";
                    }
                }
            }
            if (open()) {
                $confirm .= "\n\t\t\t\t" . TBL_BR . "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><h3>Outstanding Transactions</h3></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t<th>Amount</th>\n\t\t\t\t</tr>";
                $confirm .= $ox;
                $bout = $out;
                $out = $open_out;
                if ($out > 0) {
                    $confirm .= "\n\t\t\t\t\t<tr class='bg-even'>\n\t\t\t\t\t\t<td colspan='4'><b>A general transaction will credit the\n\t\t\t\t\t\t\tclient's account with " . CUR . " {$out} </b></td>\n\t\t\t\t\t</tr>";
                }
                $out = $bout;
            } else {
                $confirm .= "\n\t\t\t\t<tr class='bg-even'>\n\t\t\t\t\t<td colspan='5'><b>A general transaction will credit the\n\t\t\t\t\t\tclient's account with " . CUR . " {$out} </b></td>\n\t\t\t\t</tr>";
            }
        }
    }
    vsprint($out);
    vsprint($out1);
    vsprint($out2);
    vsprint($out3);
    vsprint($out4);
    vsprint($out5);
    /*
    	<tr>
    		<td colspan='5' align='right'><input type='submit' name='batch' value='Add To Batch'></td>
    	</tr>
    */
    $confirm .= "\n\t\t\t<input type='hidden' name='out1' value='{$out1}'>\n\t\t\t<input type='hidden' name='out2' value='{$out2}'>\n\t\t\t<input type='hidden' name='out3' value='{$out3}'>\n\t\t\t<input type='hidden' name='out4' value='{$out4}'>\n\t\t\t<input type='hidden' name='out5' value='{$out5}'>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t\t<td align='right' colspan='4'><input type='submit' value='Write &raquo'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>" . mkQuickLinks(ql("../core/trans-new.php", "Journal Transactions"), ql("../customers-view.php", "View Customers"));
    return $confirm;
}
function cusDetailsAll()
{
    extract($_REQUEST);
    global $set_mainFont;
    $fields = array();
    $fields["stmnt_type"] = "detailed";
    extract($fields, EXTR_SKIP);
    if (!isset($report_type)) {
        $report_type = "all";
    }
    switch ($report_type) {
        case "all":
            $search = "";
            break;
        case "bal":
            $search = "balance != '0.00' AND ";
            break;
        default:
            $search = "true";
    }
    $search2 = "";
    if (isset($filt_class) and strlen($filt_class) > 0 and $filt_class != "0") {
        $search2 .= " class = '{$filt_class}' AND ";
    }
    if (isset($filt_cat) and strlen($filt_cat) > 0 and $filt_cat != "0") {
        $search2 .= " category = '{$filt_cat}' AND ";
    }
    $from_date = dateFmt($from_year, $from_month, $from_day);
    $to_date = dateFmt($to_year, $to_month, $to_day);
    $fdate = $from_date;
    $pdf =& new Cezpdf();
    $pdf->selectFont($set_mainFont);
    // Heading --------------------------------------------------------------
    $heading = array(array(''));
    #check for sort ...
    if (isset($sort) and $sort == "branch") {
        $sortinga = "ORDER BY branch";
        $sorting = "branch,";
    } else {
        $sortinga = "";
        $sorting = "";
    }
    // Customer info ---------------------------------------------------------
    db_conn("cubit");
    $sql = "SELECT * FROM customers WHERE {$search} {$search2} div='" . USER_DIV . "' ORDER BY surname";
    $custmnt_rslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
    if (pg_numrows($custmnt_rslt) < 1) {
        return "<li class='err'>No Customers Found Matching Criteria.</li>";
    }
    while ($cust_data = pg_fetch_array($custmnt_rslt)) {
        $totout = 0;
        $cusnum = $cust_data["cusnum"];
        // Company info ----------------------------------------------------------
        db_conn("cubit");
        $sql = "SELECT * FROM compinfo WHERE div='" . USER_DIV . "'";
        $ciRlst = db_exec($sql) or errDie("Unable to retrieve the company information from Cubit.");
        $compinf = pg_fetch_array($ciRlst);
        $compinfo = array(array(COMP_NAME), array("{$compinf['addr1']}"), array("{$compinf['addr2']}"), array("{$compinf['addr3']}"), array("{$compinf['addr4']}"), array(""), array("<b>Tel:</b> {$compinf['tel']}"), array("<b>Fax:</b> {$compinf['fax']}"), array("<b>VAT REG:</b> {$compinf['vatnum']}"), array("<b>COMPANY REG:</b> {$compinf['regnum']}"));
        $info = array();
        /* base for balance brought forward */
        $info[0] = array("Date" => "", "Ref no" => "", "Details" => "<b>Balance Brought Forward: </b>", "Amount" => "", "Balance" => "");
        #check for sort ...
        if (isset($sort) and $sort == "branch") {
            $sortinga = "ORDER BY branch, date";
            $sorting = "branch,";
        } else {
            $sortinga = "ORDER BY date";
            $sorting = "";
        }
        // Should payments or credit notes be displayed
        $payment_sql = "";
        if ($stmnt_type == "open") {
            $payment_sql = "\n\t\t\tAND type NOT LIKE 'Payment for%'\n\t\t\tAND type NOT LIKE '%Credit Note%for invoice%'";
        }
        // Retrieve statement information
        $sql = "\n\t\tSELECT date, invid, type, amount, docref, branch FROM cubit.stmnt\n\t\tWHERE cusnum='{$cusnum}' {$payment_sql} AND\n\t\t\tdate BETWEEN '{$from_date}' AND '{$to_date}'\n\t\tORDER BY date, id ASC";
        $stmnt_rslt = db_exec($sql) or errrDie("Unable to retrieve statement.");
        // Retrieve balance before the 'from date'
        $sql = "\n\t\tSELECT sum(amount) FROM cubit.stmnt\n\t\tWHERE cusnum='{$cusnum}' AND date < '{$from_date}'";
        $balance_rslt = db_exec($sql) or errDie("Unable to retrieve balance.");
        $balance = pg_fetch_result($balance_rslt, 0);
        //		$oldest_date = mktime(0, 0, 0, date("m"), 1, date("Y"));
        $oldest_date = mktime(0, 0, 0, $from_month, $from_day - 1, $from_year);
        if (pg_numrows($stmnt_rslt) < 1) {
            $info[] = array("Date" => "", "Ref no" => "", "Details" => "No invoices for this month", "Amount" => "");
            // Fill the info array
        } else {
            while ($stmnt_data = pg_fetch_array($stmnt_rslt)) {
                // Deduct payments and credit notes from balances only
                // if this is an open item statement
                if ($stmnt_type == "open" && ($stmnt_data["type"] == "Invoice" || $stmnt_data["type"] == "Non-Stock Invoice")) {
                    $sql = "\n\t\t\t\t\tSELECT sum(amount) FROM cubit.stmnt\n\t\t\t\t\tWHERE type LIKE 'Payment for % {$stmnt_data['invid']}'\n\t\t\t\t\t\tOR type LIKE '%Credit Note%for invoice%{$stmnt_data['invid']}'";
                    $payment_rslt = db_exec($sql) or errDie("Unable to retrieve payments.");
                    $payment = pg_fetch_result($payment_rslt, 0);
                    // If the amount has been paid/credit note'ed in full
                    // then no need to display this line
                    if ($stmnt_data["amount"] == $payment * -1) {
                        continue;
                    }
                    $stmnt_data["amount"] += $payment;
                }
                // Increase the balance
                $balance += $stmnt_data["amount"];
                // What should we prepend the ref num with, either invoice or credit note
                if (preg_match("/Invoice/", $stmnt_data["type"])) {
                    $refnum = "INV";
                } elseif (preg_match("/Credit Note/", $stmnt_data["type"])) {
                    $refnum = "CR";
                } else {
                    $refnum = "";
                }
                $refnum .= " " . $stmnt_data["invid"];
                $info[] = array("Date" => makewidth(&$pdf, 60, 12, $stmnt_data['date']), "Ref no" => makewidth(&$pdf, 70, 12, $refnum), "Details" => makewidth(&$pdf, 200, 12, "{$stmnt_data['type']} {$stmnt_data['branch']}"), "Amount" => makewidth(&$pdf, 75, 12, "{$cust_data['currency']}{$stmnt_data['amount']}"), "Balance" => makewidth(&$pdf, 75, 12, "{$cust_data['currency']}" . sprint($balance) . ""));
            }
        }
        if (isset($from_date) && isset($to_date)) {
            # get overlapping amount
            //			$sql = "
            //			SELECT sum(amount) as amount FROM cubit.stmnt
            //			WHERE cusnum='$cusnum' AND date>'$to_date'";
            //			$balRslt = db_exec ($sql) or errDie ("Unable to retrieve invoices statement from database.");
            //			$bal = pg_fetch_array ($balRslt);
            $get_bal = "SELECT sum(amount) FROM stmnt WHERE cusnum = '{$cust_data['cusnum']}'";
            $run_bal = db_exec($get_bal) or errDie("Unable to get customer balance.");
            if (pg_numrows($run_bal) < 1) {
                $cust_data['balance'] = sprint(0);
            } else {
                $cust_data['balance'] = sprint(pg_fetch_result($run_bal, 0, 0));
            }
            $get_bal = "SELECT sum(amount) FROM stmnt WHERE cusnum = '{$cust_data['cusnum']}' AND date>'{$from_date}'";
            $run_bal = db_exec($get_bal) or errDie("Unable to get customer balance.");
            if (pg_numrows($run_bal) < 1) {
                $bal['amount'] = sprint(0);
            } else {
                $bal['amount'] = sprint(pg_fetch_result($run_bal, 0, 0));
            }
            $cust_data['balance'] = $cust_data['balance'] - $bal['amount'];
        }
        /* alter the balance brought forward entry's (info[0]) amount */
        if ($cust_data['location'] == 'int') {
            $cust_data['balance'] = $cust_data['fbalance'];
        }
        $balbf = $cust_data['balance'] - $totout;
        $balbf = sprint($balbf);
        //		$balbf = "test";
        $info[0]["Date"] = date("d-m-Y", $oldest_date);
        // - 24*60*60);
        $info[0]["Amount"] = "{$cust_data['currency']}{$balbf}";
        $custinfo = array(array("{$cust_data['surname']}"));
        // Add the address to the array
        $custaddr_ar = explode("\n", $cust_data["paddr1"]);
        foreach ($custaddr_ar as $addr) {
            $custinfo[] = array(pdf_lstr("{$addr}", 70));
        }
        $custinfo[] = array("");
        $custinfo[] = array("<b>Account Number:</b> {$cust_data['accno']}");
        //$custinfo[] = array("<b>Balance Brought Forward: </b>$cust_data[currency]$balbf");
        // Comments --------------------------------------------------------------
        if (isset($comment)) {
            db_conn("cubit");
            $sql = "SELECT comment FROM saved_statement_comments WHERE id='{$comment}'";
            $rslt = db_exec($sql) or errDie("Unable to retrieve comments from Cubit.");
            $default_comment = base64_decode(pg_fetch_result($rslt, 0));
        } elseif (isset($b64_comments)) {
            $default_comment = base64_decode($b64_comments);
        } else {
            db_conn("cubit");
            $sql = "SELECT value FROM settings WHERE constant='DEFAULT_STMNT_COMMENTS'";
            $cmntRslt = db_exec($sql) or errDie("Unable to retrieve comments from Cubit.");
            $default_comment = base64_decode(pg_fetch_result($cmntRslt, 0));
        }
        $comments = array();
        $default_comment = wordwrap($default_comment, 55, "\n");
        $default_comment_ar = explode("\n", $default_comment);
        $i = 1;
        foreach ($default_comment_ar as $val) {
            if ($i == 4) {
                $comments[] = array(pdf_lstr($val, 55));
                break;
            } else {
                $comments[] = array($val);
            }
            $i++;
        }
        #handle unset bank information
        if ($cust_data['bankid'] == "0") {
            $get_bid = "SELECT * FROM bankacct LIMIT 1";
            $run_bid = db_exec($get_bid) or errDie("Unable to get default bank information.");
            if (pg_numrows($run_bid) < 1) {
                #no bank accounts in cubit ????
                $bank_data = array();
                $bank_data['bankname'] = "";
                $bank_data['branchname'] = "";
                $bank_data['branchcode'] = "";
                $bank_data['accnum'] = "";
            } else {
                $cust_data['bankid'] = pg_fetch_result($run_bid, 0, 0);
                $bank_data = qryBankAcct($cust_data['bankid']);
            }
        } else {
            $bank_data = qryBankAcct($cust_data['bankid']);
        }
        $banking = array(array("{$bank_data['bankname']}"), array("<b>Branch: </b>{$bank_data['branchname']}"), array("<b>Branch Code: </b>{$bank_data['branchcode']}"), array("<b>Account Number: </b>{$bank_data['accnum']}"));
        $get_bal = "SELECT sum(amount) FROM stmnt WHERE cusnum = '{$cust_data['cusnum']}'";
        $run_bal = db_exec($get_bal) or errDie("Unable to get customer balance.");
        if (pg_numrows($run_bal) < 1) {
            $cust_data['balance'] = sprint(0);
        } else {
            $cust_data['balance'] = sprint(pg_fetch_result($run_bal, 0, 0));
        }
        // Totals ----------------------------------------------------------------
        $totals = array(array(""), array("<b>Total Outstanding Balance</b> : {$cust_data['currency']} " . sprint($cust_data["balance"])));
        // Age analysis ----------------------------------------------------------
        if ($cust_data['location'] == 'int') {
            $cust_data['balance'] = $cust_data['fbalance'];
        }
        $balbf = $cust_data['balance'] - $totout;
        $balbf = sprint($balbf);
        $cust_data['balance'] = sprint($cust_data['balance']);
        //		$from_date = date ("Y-m-d",mktime (0,0,0,date("m"),"01",date("Y")));
        $from_date = "{$from_year}-{$from_month}-{$from_day}";
        # Check type of age analisys
        if (div_isset("DEBT_AGE", "mon")) {
            $curr = ageage($cust_data['cusnum'], 0, $cust_data['fcid'], $cust_data['location']);
            $age30 = ageage($cust_data['cusnum'], 1, $cust_data['fcid'], $cust_data['location']);
            $age60 = ageage($cust_data['cusnum'], 2, $cust_data['fcid'], $cust_data['location']);
            $age90 = ageage($cust_data['cusnum'], 3, $cust_data['fcid'], $cust_data['location']);
            $age120 = ageage($cust_data['cusnum'], 4, $cust_data['fcid'], $cust_data['location']);
        } else {
            $curr = cust_age($cust_data['cusnum'], 29, $cust_data['fcid'], $cust_data['location'], $to_month, $to_date, $from_date);
            $age30 = cust_age($cust_data['cusnum'], 59, $cust_data['fcid'], $cust_data['location'], $to_month, $to_date, $from_date);
            $age60 = cust_age($cust_data['cusnum'], 89, $cust_data['fcid'], $cust_data['location'], $to_month, $to_date, $from_date);
            $age90 = cust_age($cust_data['cusnum'], 119, $cust_data['fcid'], $cust_data['location'], $to_month, $to_date, $from_date);
            $age120 = cust_age($cust_data['cusnum'], 149, $cust_data['fcid'], $cust_data['location'], $to_month, $to_date, $from_date);
        }
        $custtot = $curr + $age30 + $age60 + $age90 + $age120;
        //		if(sprint($custtot) != sprint($cust_data['balance'])) {
        //			$curr = sprint($curr + $cust_data['balance'] - $custtot);
        //			$custtot = sprint($cust_data['balance']);
        //		}
        $age = array(array("Current" => "<b>Current</b>", "30 Days" => "<b>30 Days:</b>", "60 Days" => "<b>60 Days</b>", "90 Days" => "<b>90 Days</b>", "120 Days" => "<b>120 Days</b>"), array("Current" => $curr, "30 Days" => $age30, "60 Days" => $age60, "90 Days" => $age90, "120 Days" => $age120));
        // Table layout ----------------------------------------------------------
        $ic = 0;
        while (++$ic * 25 < count($info)) {
        }
        // Draw the pages, determine by the amount of items how many pages
        // if items > 25 start a new page
        $info_print = array();
        for ($i = 0; $i < $ic; $i++) {
            if ($i) {
                $pdf->ezNewPage();
            }
            if (isset($from_date) && isset($to_date)) {
                $date = "{$from_date} to {$to_date}";
                $dalign_x = 130;
            } else {
                $date = date("d-m-Y");
                $dalign_x = 105;
            }
            // Heading
            $heading_pos = drawTable(&$pdf, $heading, 0, 0, 520, 5);
            drawText(&$pdf, "<b>Page " . ($i + 1) . "</b>", 8, $heading_pos['x'] / 2 - 8, 10);
            drawText(&$pdf, "<b>{$compinf['compname']}</b>", 18, 8, $heading_pos['y'] / 2 + 6);
            drawText(&$pdf, "<b>Statement</b>", 18, $heading_pos['x'] - 120, $heading_pos['y'] / 2);
            drawText(&$pdf, $date, 10, $heading_pos['x'] - $dalign_x, $heading_pos['y'] / 2 + 18);
            $custinfo_pos = drawTable(&$pdf, $custinfo, 0, $heading_pos['y'] + 5, 300, 10);
            $compinfo_pos = drawTable(&$pdf, $compinfo, $custinfo_pos['x'], $heading_pos['y'] + 5, 220, 10);
            $info_start = $i * 25;
            if ($i) {
                $info_start++;
            }
            if ($info_start >= count($info) - 25) {
                $info_end = count($info) - 1;
            } else {
                $info_end = ($i + 1) * 25;
            }
            $info_print = array();
            for ($j = $info_start; $j <= $info_end; $j++) {
                $info_print[$j] = $info[$j];
            }
            // Adjust the column widths
            $cols = array("Date" => array("width" => 60), "Proforma Inv no" => array("width" => 70), "Ref no" => array("width" => 80), "Amount" => array("width" => 75, "justification" => "right"), "Balance" => array("width" => 75, "justification" => "right"));
            $info_pos = drawTable(&$pdf, $info_print, 0, $custinfo_pos['y'] + 5, 520, 25, $cols, 1);
            $comments_pos = drawTable(&$pdf, $comments, 0, $info_pos['y'] + 5, 260, 4);
            $banking_pos = drawTable(&$pdf, $banking, $comments_pos['x'], $info_pos['y'] + 5, 260, 4);
            $totals_pos = drawTable(&$pdf, $totals, 0, $comments_pos['y'] + 5, 520, 3);
            $age_pos = drawTable(&$pdf, $age, 0, $totals_pos['y'], 520, 2);
            drawText(&$pdf, "<b>Cubit Accounting</b>", 6, 0, $age_pos['y'] + 20);
        }
        $pdf->ezNewPage();
    }
    $pdf->ezStream();
}
function confirm($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($back);
        return method($_POST);
    }
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    for ($t = 0; $t < $rec_amount; $t++) {
        if (!isset($descript[$t]) or !isset($reference[$t]) or !isset($setamt[$t]) or empty($descript[$t]) or empty($reference[$t]) or empty($setamt[$t])) {
            continue;
        }
        if (!isset($out[$t]) or strlen($out[$t]) < 1) {
            $out[$t] = $amt[$t];
        }
        if (!isset($out1[$t])) {
            $out1[$t] = '';
        }
        if (!isset($out2[$t])) {
            $out2[$t] = '';
        }
        if (!isset($out3[$t])) {
            $out3[$t] = '';
        }
        if (!isset($out4[$t])) {
            $out4[$t] = '';
        }
        if (!isset($out5[$t])) {
            $out5[$t] = '';
        }
        $v->isOk($bankid[$t], "num", 1, 30, "Invalid Bank Account.");
        $v->isOk($date[$t], "date", 1, 14, "Invalid Date.");
        $v->isOk($descript[$t], "string", 0, 255, "Invalid Description.");
        $v->isOk($reference[$t], "string", 0, 50, "Invalid Reference Name/Number.");
        $v->isOk($cheqnum[$t], "num", 0, 30, "Invalid Cheque number.");
        $v->isOk($amt[$t], "float", 1, 40, "Invalid amount.");
        $v->isOk($setamt[$t], "float", 1, 40, "Invalid settlement amount.");
        $v->isOk($setvat[$t], "string", 1, 10, "Invalid Settlement VAT Option.");
        $v->isOk($setvatcode[$t], "string", 1, 40, "Invalid Settlement VAT code");
        $v->isOk($out[$t], "float", 1, 40, "Invalid out amount.");
        $v->isOk($out1[$t], "float", 0, 40, "Invalid paid amount(currant).");
        $v->isOk($out2[$t], "float", 0, 40, "Invalid paid amount(30).");
        $v->isOk($out3[$t], "float", 0, 40, "Invalid paid amount(60).");
        $v->isOk($out4[$t], "float", 0, 40, "Invalid paid amount(90).");
        $v->isOk($out5[$t], "float", 0, 40, "Invalid paid amount(120).");
        $v->isOk($cusid[$t], "num", 1, 10, "Invalid customer number.");
        if (isset($invids[$t])) {
            foreach ($invids[$t] as $key => $value) {
                if ($paidamt[$t][$key] < 0.01) {
                    continue;
                }
                $v->isOk($invids[$t][$key], "num", 1, 50, "Invalid Invoice No. [{$key}]");
                $v->isOk($paidamt[$t][$key], "float", 1, 40, "Invalid amount to be paid. [{$key}]");
            }
        }
    }
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        for ($t = 0; $t < $rec_amount; $t++) {
            //$temp1 = $out1[$t];
            $_POST["out1[{$t}]"] = $out1[$t] + 0;
            $_POST["out2[{$t}]"] = $out2[$t] + 0;
            $_POST["out3[{$t}]"] = $out3[$t] + 0;
            $_POST["out4[{$t}]"] = $out4[$t] + 0;
            $_POST["out5[{$t}]"] = $out5[$t] + 0;
        }
        return $confirm . alloc($_POST);
    }
    $passon = "";
    for ($t = 0; $t < $rec_amount; $t++) {
        if (!isset($descript[$t]) or !isset($reference[$t]) or !isset($setamt[$t]) or empty($descript[$t]) or empty($reference[$t]) or empty($setamt[$t])) {
            continue;
        }
        $tot[$t] = 0;
        if (isset($invids[$t])) {
            foreach ($invids[$t] as $key => $value) {
                if ($paidamt[$t][$key] < 0.01) {
                    continue;
                }
                $tot[$t] += $paidamt[$t][$key];
            }
        }
        if (isset($open_amount[$t])) {
            $tot[$t] += array_sum($open_amount[$t]);
        }
        $passon .= "\n\t\t\t<input type='hidden' name='bankid[{$t}]' value='{$bankid[$t]}'>\n\t\t\t<input type='hidden' name='date[{$t}]' value='{$date[$t]}'>\n\t\t\t<input type='hidden' name='cusid[{$t}]' value='{$cusid[$t]}'>\n\t\t\t<input type='hidden' name='descript[{$t}]' value='{$descript[$t]}'>\n\t\t\t<input type='hidden' name='reference[{$t}]' value='{$reference[$t]}'>\n\t\t\t<input type='hidden' name='cheqnum[{$t}]' value='{$cheqnum[$t]}'>\n\t\t\t<input type='hidden' name='out[{$t}]' value='{$out[$t]}'>\n\t\t\t<input type='hidden' name='date_day[{$t}]' value='{$date_day[$t]}'>\n\t\t\t<input type='hidden' name='date_month[{$t}]' value='{$date_month[$t]}'>\n\t\t\t<input type='hidden' name='date_year[{$t}]' value='{$date_year[$t]}'>\n\t\t\t<input type='hidden' name='out1[{$t}]' value='{$out1[$t]}'>\n\t\t\t<input type='hidden' name='out2[{$t}]' value='{$out2[$t]}'>\n\t\t\t<input type='hidden' name='out3[{$t}]' value='{$out3[$t]}'>\n\t\t\t<input type='hidden' name='out4[{$t}]' value='{$out4[$t]}'>\n\t\t\t<input type='hidden' name='out5[{$t}]' value='{$out5[$t]}'>\n\t\t\t<input type='hidden' name='amt[{$t}]' value='{$amt[$t]}'>\n\t\t\t<input type='hidden' name='setamt[{$t}]' value='{$setamt[$t]}'>\n\t\t\t<input type='hidden' name='setvat[{$t}]' value='{$setvat[$t]}'>\n\t\t\t<input type='hidden' name='setvatcode[{$t}]' value='{$setvatcode[$t]}'>";
    }
    $confirm = "\n\t\t<h3>New Bank Receipt</h3>\n\t\t<h4>Confirm entry (Please check the details)</h4>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='write'>\n\t\t\t<input type='hidden' name='all' value='{$all}'>\n\t\t\t<input type='hidden' name='rec_amount' value='{$rec_amount}'>\n\t\t\t{$passon}\n\t\t<table " . TMPL_tblDflts . ">";
    $passon2 = "";
    for ($t = 0; $t < $rec_amount; $t++) {
        $out[$t] += 0;
        $OUT1[$t] = $out1[$t] + 0;
        $OUT2[$t] = $out2[$t] + 0;
        $OUT3[$t] = $out3[$t] + 0;
        $OUT4[$t] = $out4[$t] + 0;
        $OUT5[$t] = $out5[$t] + 0;
        $tot[$t] = sprint($tot[$t]);
        $amt[$t] = sprint($amt[$t]);
        $out[$t] = sprint($out[$t]);
        if (sprint($tot[$t] + $out[$t] + $out1[$t] + $out2[$t] + $out3[$t] + $out4[$t] + $out5[$t] - $amt[$t]) != sprint(0)) {
            $_POST["out1[{$t}]"] = $out1;
            $_POST["out2[{$t}]"] = $out2;
            $_POST["out3[{$t}]"] = $out3;
            $_POST["out4[{$t}]"] = $out4;
            $_POST["out5[{$t}]"] = $out5;
            //	return "<li class='err'>The total amount for invoices not equal to the amount received.
            //		Please check the details.</li>".alloc($_POST);
        }
        if (isset($bout[$t])) {
            $out[$t] = $bout[$t];
        }
        /* bank account name */
        if (($bank = qryBankAcct($bankid[$t], "accname, bankname")) === false) {
            $bank['accname'] = "Cash";
            $bank['bankname'] = "";
        }
        /* customer name */
        $cus[$t] = qryCustomer($cusid[$t], "cusname, surname");
        $cus1 = $cus[$t]['cusname'];
        $cus2 = $cus[$t]['surname'];
        $setamt[$t] = sprint($setamt[$t]);
        if ($setvat[$t] == "inc") {
            $showsetvat = "VAT Inclusive";
        } else {
            $showsetvat = "No VAT";
        }
        $confirm .= "\n\t\t\t<tr>\n\t\t\t\t<th>Field</th>\n\t\t\t\t<th>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Account</td>\n\t\t\t\t<td>{$bank['accname']} - {$bank['bankname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Date</td>\n\t\t\t\t<td valign='center'>{$date[$t]}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Received from</td>\n\t\t\t\t<td valign='center'>{$cus1} {$cus2}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Description</td>\n\t\t\t\t<td valign='center'>{$descript[$t]}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Reference</td>\n\t\t\t\t<td valign='center'>{$reference[$t]}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Cheque Number</td>\n\t\t\t\t<td valign='center'>{$cheqnum[$t]}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Amount</td>\n\t\t\t\t<td valign='center'>" . CUR . " {$amt[$t]}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Settlement Amount</td>\n\t\t\t\t<td valign='center'>" . CUR . " {$setamt[$t]} {$showsetvat}</td>\n\t\t\t</tr>";
        /* OPTION 1 : AUTO ALLOCATE (confirm) */
        if ($all == 0) {
            // Layout
            $confirm .= "\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><h3>Invoices</h3></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Invoice Number</th>\n\t\t\t\t<th>Outstanding amount</th>\n\t\t\t\t<th>Terms</th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t</tr>";
            $i = 0;
            if (isset($invids[$t])) {
                foreach ($invids[$t] as $key => $value) {
                    if ($paidamt[$t][$invids[$t][$key]] < 0.01) {
                        continue;
                    }
                    db_connect();
                    $ii = $invids[$t][$key];
                    if (!isset($itype[$t][$ii]) && !isset($ptype[$t][$ii])) {
                        # Get all the details
                        $sql = "SELECT invnum,invid,balance,terms,odate FROM invoices\n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                        $invRslt = db_exec($sql) or errDie("Unable to access database.");
                        if (pg_numrows($invRslt) < 1) {
                            return "<li class='err'> - Invalid ord number {$invids[$key]}.</li>";
                        }
                        $inv = pg_fetch_array($invRslt);
                        $invid = $inv['invid'];
                        $pp = $paidamt[$t][$invid];
                        $confirm .= "\n\t\t\t\t\t\t\t<input type='hidden' name='paidamt[{$t}][{$invid}]' size='7' value='{$pp}'>\n\t\t\t\t\t\t\t<input type='hidden' size='20' name='invids[{$t}][{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$pp}</td>\n\t\t\t\t\t\t</tr>";
                    } else {
                        if (!isset($ptype[$t][$ii])) {
                            $sql = "SELECT invnum,invid,balance,sdate as odate FROM nons_invoices\n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                            $invRslt = db_exec($sql) or errDie("Unable to access database.");
                            if (pg_numrows($invRslt) < 1) {
                                return "<li class='err'> - Invalid ord number {$ii}.</li>";
                            }
                            $inv = pg_fetch_array($invRslt);
                            $invid = $inv['invid'];
                            $pp = $paidamt[$t][$invid];
                            $confirm .= "\n\t\t\t\t\t\t<input type='hidden' size='20' name='invids[{$t}][{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t\t<input type='hidden' name='paidamt[{$t}][{$invid}]' size='7' value='{$pp}'>\n\t\t\t\t\t\t<input type='hidden' name='itype[{$t}][{$invid}]' value='y'>\n\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$pp}</td>\n\t\t\t\t\t\t</tr>";
                        } else {
                            $sqls = array();
                            for ($i = 1; $i <= 12; ++$i) {
                                $sqls[] = "SELECT invnum,invid,balance,odate FROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\t\t\tWHERE invid='{$ii}' AND div = '" . USER_DIV . "'";
                            }
                            $sql = implode(" UNION ", $sqls);
                            $prnInvRslt = db_exec($sql);
                            $inv = pg_fetch_array($prnInvRslt);
                            $invid = $inv['invid'];
                            $pp = $paidamt[$t][$invid];
                            $confirm .= "\n\t\t\t\t\t\t<input type='hidden' size='20' name='invids[{$t}][{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t\t<input type='hidden' name='paidamt[{$t}][{$invid}]' size='7' value='{$pp}'>\n\t\t\t\t\t\t<input type='hidden' name='ptype[{$t}][{$invid}]' value='y'>\n\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$pp}</td>\n\t\t\t\t\t\t</tr>";
                        }
                    }
                }
            }
            if ($out[$t] > 0) {
                /* START OPEN ITEMS */
                $ox = "";
                db_conn('cubit');
                $sql = "SELECT * FROM open_stmnt WHERE balance>0 AND cusnum='{$cusid[$t]}' ORDER BY date";
                $rslt = db_exec($sql) or errDie("Unable to get open items.");
                $open_out[$t] = $out[$t];
                $i = 0;
                while ($od = pg_fetch_array($rslt)) {
                    if ($open_out[$t] == 0) {
                        continue;
                    }
                    $oid = $od['id'];
                    $bgColor = bgcolor($i);
                    if ($open_out[$t] >= $od['balance']) {
                        $open_amount[$t][$oid] = $od['balance'];
                        $open_out[$t] = sprint($open_out[$t] - $od['balance']);
                        $ox .= "\n\t\t\t\t\t\t\t<input type='hidden' size='20' name='open[{$t}][{$oid}]' value='{$oid}'>\n\t\t\t\t\t\t\t<input type='hidden' name='open_amount[{$t}][{$oid}]' value='{$open_amount[$t]}[{$oid}]'>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$open_amount[$t]}[{$oid}]</td>\n\t\t\t\t\t\t\t</tr>";
                    } else {
                        if ($open_out[$t] < $od['balance']) {
                            $open_amount[$t][$oid] = $open_out[$t];
                            $open_out[$t] = 0;
                            $ox .= "\n\t\t\t\t\t\t\t<input type='hidden' size='20' name='open[{$t}][{$oid}]' value='{$od['id']}'>\n\t\t\t\t\t\t\t<input type='hidden' name='open_amount[{$t}][{$oid}]' value='{$open_amount[$t]}[{$oid}]'>\n\t\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t\t<td>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$open_amount[$t]}[{$oid}]</td>\n\t\t\t\t\t\t\t</tr>";
                        }
                    }
                }
                if (open()) {
                    $confirm .= "\n\t\t\t\t\t" . TBL_BR . "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='2'><h3>Outstanding Transactions</h3></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t<th>Amount</th>\n\t\t\t\t\t</tr>";
                    $confirm .= $ox;
                    $bout[$t] = $out[$t];
                    $out[$t] = $open_out[$t];
                    $out[$t] = sprint($out[$t]);
                    if ($out[$t] > 0) {
                        $confirm .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan='4'><b>A general transaction will credit the\n\t\t\t\t\t\t\t\tclient's account with " . CUR . " {$out[$t]} </b></td>\n\t\t\t\t\t\t</tr>";
                    }
                    $out[$t] = $bout[$t];
                } else {
                    $out[$t] = sprint($out[$t]);
                    $confirm .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='5'><b>A general transaction will credit the\n\t\t\t\t\t\t\tclient's account with " . CUR . " {$out[$t]} </b></td>\n\t\t\t\t\t</tr>";
                }
            }
            $confirm .= TBL_BR;
        }
        $confirm .= TBL_BR . TBL_BR;
        //		$passon2 .= "
        //	<input type='hidden' name='out1[$t]' value='$out1[$t]'>
        //	<input type='hidden' name='out2[$t]' value='$out2[$t]'>
        //	<input type='hidden' name='out3[$t]' value='$out3[$t]'>
        //	<input type='hidden' name='out4[$t]' value='$out4[$t]'>
        //	<input type='hidden' name='out5[$t]' value='$out5[$t]'>
        //			";
    }
    /*
    	<tr>
    		<td colspan='5' align='right'><input type='submit' name='batch' value='Add To Batch'></td>
    	</tr>
    */
    $confirm .= "\n\t\t\t{$passon2}\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t\t<td align='right' colspan='4'><input type='submit' value='Write &raquo'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>" . mkQuickLinks(ql("trans-new.php", "Journal Transactions"), ql("../customers-view.php", "View Customers"));
    return $confirm;
}
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 gennonspdf($invid)
{
    global $set_mainFont;
    $showvat = TRUE;
    $pdf =& new Cezpdf();
    $pdf->selectFont($set_mainFont);
    // Validate
    require_lib("validate");
    $v = new Validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice 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 nons_invoices WHERE invid='{$invid}' AND DIV='" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice info.");
    //die ($sql);
    if (pg_num_rows($invRslt) == 0) {
        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;
    }
    // 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);
    //	$bnkData = qryBankAcct(getdSetting("BANK_DET"));
    $bnkData = qryBankAcct($inv['bankid']);
    $compinfo = array();
    $compinfo[] = array(pdf_lstr($comp["addr1"], 35), pdf_lstr($comp["paddr1"], 35));
    $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);
    if ($data['value'] == "Yes") {
        $sp = "<b>Sales Person: </b>{$inv['salespn']}";
    } else {
        $sp = "";
    }
    // Customer info ---------------------------------------------------------
    if ($inv["cusid"] != 0) {
        db_conn("cubit");
        $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
        $cusRslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
        $cusData = pg_fetch_array($cusRslt);
    } else {
        $cusData["surname"] = $inv["cusname"];
        $cusData["addr1"] = $inv["cusaddr"];
        $cusData["paddr1"] = $inv["cusaddr"];
        $cusData["del_addr1"] = "";
        $cusData["accno"] = "";
    }
    $docinfo = array(array("<b>Invoice No:</b> {$inv['invnum']}"), array("<b>Proforma Inv No:</b> {$inv['docref']}"), array("<b>Account no: </b>{$cusData['accno']}"), array("{$sp}"));
    $invoice_to = array(array(""));
    $cusinfo = array(array("<b>{$cusData['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>"));
    $cusaddr = explode("\n", $cusData['del_addr1']);
    foreach ($cusaddr as $v) {
        $cusdaddr[] = array(pdf_lstr($v, 40));
    }
    // 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 nons_inv_items WHERE invid='{$invid}' AND DIV='" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        // Check Tax Excempt
        db_conn("cubit");
        $sql = "SELECT zero FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $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['vatex']}'";
        $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;
        }
        $items[] = array("Description" => makewidth($pdf, 305, 12, $ex . strip_tags($stkd["description"])), "Qty" => $stkd['qty'], "Unit Price" => $curr . $stkd['unitcost'], "Amount" => $curr . $stkd['amt']);
    }
    // Comment ---------------------------------------------------------------
    $comment = array(array("<i>VAT Exempt Indicator: #</i>"), array($inv["remarks"]));
    // Box to sign in --------------------------------------------------------
    $sign = array(array("<b>Terms:</b> {$inv['terms']}"), 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>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 * 20 < 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, 18, $heading_pos['y'] / 2 + 6);
        drawText(&$pdf, "<b>Tax Invoice</b>", 18, $heading_pos['x'] - 120, $heading_pos['y'] / 2 + 9);
        // Should we display reprint on the invoice
        if (isset($type) and $type == "nonsreprint") {
            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, 4);
        $pagenr_pos = drawTable(&$pdf, $pagenr, $date_pos['x'], $heading_pos['y'], 100, 4);
        $docinfo_pos = drawTable(&$pdf, $docinfo, $compinfo_pos['x'], $date_pos['y'], 200, 4);
        $invoice_to_pos = drawTable(&$pdf, $invoice_to, 0, $compinfo_pos['y'], 520, 2);
        drawText(&$pdf, "<b>Tax Invoice 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 * 20;
        if ($i) {
            $items_start++;
        }
        if ($items_start >= count($items) - 20) {
            $items_end = count($items) - 1;
        } else {
            $items_end = ($i + 1) * 20;
        }
        $items_print = array();
        for ($j = $items_start; $j <= $items_end; $j++) {
            $items_print[$j] = $items[$j];
        }
        // Adjust the column widths
        $cols = array("Description" => array("width" => 310), "Qty" => array("width" => 50), "Unit Price" => array("width" => 80, "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 write()
{
    extract($_POST);
    if (isset($back)) {
        return add($_POST);
    }
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    $bank = qryBankAcct($bankid);
    $cols = grp(m("type", "Banking Details Account"), m("label", "BANK_DET"), m("value", $bankid), m("descript", "Bank Account: ({$bank['acctype']}) {$bank['accname']} - {$bank['bankname']}"), m("div", USER_DIV));
    $qry = new dbUpdate("set", "cubit", $cols, "label = 'BANK_DET' AND div = '" . USER_DIV . "'");
    $qry->run(DB_REPLACE);
    $write = "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th>Bank Details Account</th>\n\t</tr>\n\t<tr class='text'>\n\t\t<td>Bank Details Account have been set to Bank Account: ({$bank['acctype']}) {$bank['accname']} - {$bank['bankname']}.</td>\n\t</tr>\n\t</table>" . mkQuickLinks();
    return $write;
}
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;
}
function details($_GET)
{
    # Get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid customer 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'>";
        $OUTPUT = $confirm;
        require "../template.php";
    }
    if ($type == "paid") {
        $ex = "AND balance=0";
    } elseif ($type == "unpaid") {
        $ex = "AND balance>0";
    } else {
        $ex = "";
    }
    # Get invoice info
    /* Start PDF Layout */
    include "../pdf-settings.php";
    $get_set = "SELECT filename FROM template_settings WHERE template = 'reprints' LIMIT 1";
    $run_set = db_exec($get_set) or errDie("Unable to get template settings.");
    if (pg_numrows($run_set) < 1) {
        $setting = "default";
    } else {
        $sarr = pg_fetch_array($run_set);
        $setting = $sarr['filename'];
    }
    //	$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);
    //
    //	# just a new line
    //	$pdf->ezText("<b>Tax Invoice</b>", $set_txtSize+3, array('justification'=>'centre'));
    //
    //	$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');
    //	/* /Start PDF Layout */
    //
    ##################################################################
    $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);
    # just a new line
    $pdf->ezText("<b>Tax Invoice</b>", $set_txtSize + 3, array('justification' => 'centre'));
    $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');
    /* /Start PDF Layout */
    ##################################################################
    db_connect();
    $sql = "SELECT * FROM invoices WHERE cusnum = '{$cusnum}' AND printed = 'y' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    $sql = "SELECT * FROM nons_invoices WHERE cusid='{$cusnum}' AND div='" . USER_DIV . "' {$ex}";
    $nonsinvRslt = pg_exec($sql) or errDie("Error reading nons stock invoices.");
    //	$none=true;
    $i = 0;
    /*******************************************************************************
     ****
     ****				STOCK INVOICES
     ****
     ********************************************************************************/
    if ($type == "unpaid" || $type == "all") {
        while ($inv = pg_fetch_array($invRslt)) {
            $invid = $inv['invid'];
            if ($setting == "default") {
                $none = false;
                $products = array();
                $invdet = array();
                $amtdat = array();
                $comments = array();
                $vatdat = array();
                /* --- Start some checks --- */
                # check if stock was selected(yes = put done button)
                db_connect();
                $sql = "SELECT stkid FROM inv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
                $crslt = db_exec($sql);
                if (pg_numrows($crslt) < 1) {
                    continue;
                }
                # Create a new page for customer
                if ($i > 0) {
                    $pdf->newPage();
                }
                /* --- End some checks --- */
                /* --- Start Products Display --- */
                # Products layout
                $products = "";
                $disc = 0;
                # get selected stock in this invoice
                db_connect();
                $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $stkdRslt = db_exec($sql);
                # they product display arrays
                $products = array();
                $prodhead = array('stkcod' => 'ITEM NUMBER', 'stkdes' => 'DESCRIPTION', 'qty' => 'QTY', 'selamt' => 'UNIT PRICE', 'disc' => 'DISCOUNT', 'amt' => 'AMOUNT');
                $taxex = 0;
                while ($stkd = pg_fetch_array($stkdRslt)) {
                    # get warehouse name
                    db_conn("exten");
                    $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
                    $whRslt = db_exec($sql);
                    $wh = pg_fetch_array($whRslt);
                    # get selected stock in this warehouse
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
                    $stkRslt = db_exec($sql);
                    $stk = pg_fetch_array($stkRslt);
                    $sp = "";
                    # Check Tax Excempt
                    if ($stk['exvat'] == 'yes') {
                        $ex = "#";
                    } else {
                        $ex = "";
                    }
                    # keep track of discounts
                    $disc += $stkd['disc'];
                    if ($stkd["account"] > 0) {
                        $description = $stkd["description"];
                    } else {
                        $description = $stk["stkdes"];
                    }
                    # put in product
                    $products[] = array('stkcod' => $stk['stkcod'], 'stkdes' => "{$ex} {$sp}" . pdf_lstr($description), 'qty' => $stkd['qty'], 'selamt' => CUR . " {$stkd['unitcost']}", 'disc' => CUR . " {$stkd['disc']}", 'amt' => CUR . " {$stkd['amt']}");
                }
                /* --- 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;
                $SUBTOT = sprint($inv['subtot']);
                $VAT = sprint($inv['vat']);
                $TOTAL = sprint($inv['total']);
                $inv['delchrg'] = sprint($inv['delchrg']);
                # Update number of prints
                $inv['prints']++;
                db_connect();
                $Sql = "UPDATE invoices SET prints = '{$inv['prints']}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
                /*
                # minus discount
                # $SUBTOT -= $disc; --> already minused
                	
                # duplicate
                $SUBTOTAL = $SUBTOT;
                	
                # minus trade discount
                $SUBTOTAL -= $traddiscm;
                	
                # add del charge
                $SUBTOTAL += $inv['delchrg'];
                	
                	
                # If vat must be charged
                if($inv['chrgvat'] == "yes"){
                	$VATP = TAX_VAT;
                	$VAT = sprintf("%01.2f", (($VATP/100) * ($SUBTOTAL - $taxex)));
                }else{
                	$VATP = 0;
                	$VAT = "0.00";
                }
                	
                # total
                $TOTAL = sprint($SUBTOTAL + $VAT);
                */
                /* --- End Some calculations --- */
                /* -- Final PDF output layout -- */
                # set y so its away from the top
                $pdf->ezSetY($set_tlY);
                # Customer details
                $pdf->addText($set_tlX, $set_tlY, $set_txtSize - 2, "{$inv['surname']}");
                $nl = pdf_addnl($pdf, $set_tlX, $set_tlY, $set_txtSize - 2, $inv['cusaddr']);
                $pdf->addText($set_tlX, $set_tlY - $set_txtSize * $nl, $set_txtSize - 2, "(Vat No. {$inv['cusvatno']})");
                # Company details
                $pdf->addText($set_pgXCenter, $set_tlY, $set_txtSize - 2, COMP_NAME);
                $nl = pdf_addnl($pdf, $set_pgXCenter, $set_tlY, $set_txtSize - 2, COMP_PADDRR);
                $pdf->addText($set_pgXCenter, $set_tlY - ($set_txtSize - 2) * $nl, $set_txtSize - 2, COMP_TEL);
                $pdf->addText($set_pgXCenter, $set_tlY - ($set_txtSize - 2) * ($nl + 1), $set_txtSize - 2, COMP_FAX);
                $pdf->addText($set_pgXCenter, $set_tlY - ($set_txtSize - 2) * ($nl + 2), $set_txtSize - 2, "Reg No. " . COMP_REGNO);
                $pdf->addText($set_pgXCenter, $set_tlY - ($set_txtSize - 2) * ($nl + 3), $set_txtSize - 2, "VAT No. " . COMP_VATNO);
                if ($inv['chrgvat'] == "inc") {
                    $inv['chrgvat'] = "Inclusive";
                } elseif ($inv['chrgvat'] == "exc") {
                    $inv['chrgvat'] = "Exclusive";
                } else {
                    $inv['chrgvat'] = "No vat";
                }
                # Invoice details data
                $invdet[] = array('tit' => 'Invoice No.', 'val' => $inv['invnum']);
                $invdet[] = array('tit' => 'Order No.', 'val' => $inv['ordno']);
                $invdet[] = array('tit' => 'Terms', 'val' => "{$inv['terms']} Days");
                $invdet[] = array('tit' => 'Invoice Date', 'val' => $inv['odate']);
                $invdet[] = array('tit' => 'Vat', 'val' => $inv['chrgvat']);
                # invoice details
                $pdf->ezTable($invdet, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => $set_pgWidth - 42));
                # just a new line
                $pdf->ezText("\n", $set_txtSize);
                # set y so its away from the customer details
                $pdf->ezSetY($set_tlY - $set_txtSize * ($nl + 3));
                # products table
                $pdf->ezTable($products, $prodhead, '', $set_maxTblOpt);
                # Total amounts
                $amtdat[] = array('tit' => 'SUBTOTAL', 'val' => CUR . " {$SUBTOT}");
                $amtdat[] = array('tit' => 'Trade Discount', 'val' => CUR . " {$traddiscm}");
                $amtdat[] = array('tit' => "VAT @ {$VATP}%", 'val' => CUR . " {$VAT}");
                $amtdat[] = array('tit' => "Delivery Charge", 'val' => CUR . " {$inv['delchrg']}");
                $amtdat[] = array('tit' => "GRAND TOTAL", 'val' => CUR . " {$TOTAL}");
                # just a new line
                $pdf->ezText("\n", 7);
                # amounts details table data
                $pdf->ezTable($amtdat, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => $set_pgWidth - 42));
                # just a new line
                $pdf->ezSetDy(100);
                $pdf->ezText("\n", $set_txtSize);
                $comments[] = array('tit' => "Comments", 'val' => wordwrap($inv['comm'], 16));
                # VAT Number Table
                $pdf->ezTable($comments, '', "", array('showLines' => 5, 'showHeadings' => 0, 'xPos' => 79));
                $pdf->ezSetDy(-20);
                $vatdat[] = array('tit' => "VAT Exempt indicator", 'val' => "#");
                // $vatdat[] = array('tit' => "VAT No.", 'val' => COMP_VATNO);
                # VAT Number Table
                $pdf->ezTable($vatdat, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => 79));
                $i++;
            } else {
                // Invoice info
                db_conn("cubit");
                $sql = "SELECT * FROM invoices WHERE invid='{$invid}' AND DIV='" . USER_DIV . "'";
                $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice 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 inv_items WHERE invid='{$invid}' AND DIV='" . USER_DIV . "'";
                $cRslt = db_exec($sql) or errDie("Unable to retrieve invoice info.");
                if (pg_num_rows($cRslt) < 1) {
                    $error = "<li class='err'>Invoice number <b>{$invid}</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"));
                $bnkData = qryBankAcct($inv['bankid']);
                $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>Invoice No:</b> {$inv['invnum']}"), 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>", "<b>Delivery Date:</b>"), array("{$inv['cusvatno']}", "{$inv['cordno']}", "{$inv['deldate']}"));
                // Items display ---------------------------------------------------------
                $items = array();
                db_conn("cubit");
                $sql = "SELECT * FROM inv_items WHERE invid='{$invid}' 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>Tax Invoice</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>Tax Invoice 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);
                }
            }
        }
    }
    if ($type == "paid" || $type == "all") {
        for ($p = 1; $p < 13; $p++) {
            db_conn($p);
            $sql = "SELECT * FROM invoices WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
            $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
            while ($inv = pg_fetch_array($invRslt)) {
                $invid = $inv['invid'];
                $none = false;
                $products = array();
                $invdet = array();
                $amtdat = array();
                $comments = array();
                $vatdat = array();
                /* --- Start some checks --- */
                # check if stock was selected(yes = put done button)
                db_conn($p);
                $sql = "SELECT stkid FROM inv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
                $crslt = db_exec($sql);
                if (pg_numrows($crslt) < 1) {
                    continue;
                }
                # Create a new page for customer
                if ($i > 0) {
                    $pdf->newPage();
                }
                /* --- End some checks --- */
                /* --- Start Products Display --- */
                # Products layout
                $products = "";
                $disc = 0;
                # get selected stock in this invoice
                db_conn($p);
                $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $stkdRslt = db_exec($sql);
                # they product display arrays
                $products = array();
                $prodhead = array('stkcod' => 'ITEM NUMBER', 'stkdes' => 'DESCRIPTION', 'qty' => 'QTY', 'selamt' => 'UNIT PRICE', 'disc' => 'DISCOUNT', 'amt' => 'AMOUNT');
                $taxex = 0;
                while ($stkd = pg_fetch_array($stkdRslt)) {
                    # get warehouse name
                    db_conn("exten");
                    $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
                    $whRslt = db_exec($sql);
                    $wh = pg_fetch_array($whRslt);
                    # get selected stock in this warehouse
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
                    $stkRslt = db_exec($sql);
                    $stk = pg_fetch_array($stkRslt);
                    $sp = "";
                    # Check Tax Excempt
                    if ($stk['exvat'] == 'yes') {
                        $ex = "#";
                    } else {
                        $ex = "";
                    }
                    # keep track of discounts
                    $disc += $stkd['disc'];
                    if ($stkd["account"] > 0) {
                        $description = $stkd["description"];
                    } else {
                        $description = $stk["stkdes"];
                    }
                    # put in product
                    $products[] = array('stkcod' => $stk['stkcod'], 'stkdes' => "{$ex} {$sp}" . pdf_lstr($description), 'qty' => $stkd['qty'], 'selamt' => CUR . " {$stkd['unitcost']}", 'disc' => CUR . " {$stkd['disc']}", 'amt' => CUR . " {$stkd['amt']}");
                }
                /* --- 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;
                $SUBTOT = sprint($inv['subtot']);
                $VAT = sprint($inv['vat']);
                $TOTAL = sprint($inv['total']);
                $inv['delchrg'] = sprint($inv['delchrg']);
                # Update number of prints
                $inv['prints']++;
                db_connect();
                $Sql = "UPDATE invoices SET prints = '{$inv['prints']}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
                /* -- Final PDF output layout -- */
                # set y so its away from the top
                $pdf->ezSetY($set_tlY);
                # Customer details
                $pdf->addText($set_tlX, $set_tlY, $set_txtSize - 2, "{$inv['surname']}");
                $nl = pdf_addnl($pdf, $set_tlX, $set_tlY, $set_txtSize - 2, $inv['cusaddr']);
                $pdf->addText($set_tlX, $set_tlY - $set_txtSize * $nl, $set_txtSize - 2, "(Vat No. {$inv['cusvatno']})");
                # Company details
                $pdf->addText($set_pgXCenter, $set_tlY, $set_txtSize - 2, COMP_NAME);
                $nl = pdf_addnl($pdf, $set_pgXCenter, $set_tlY, $set_txtSize - 2, COMP_PADDRR);
                $pdf->addText($set_pgXCenter, $set_tlY - ($set_txtSize - 2) * $nl, $set_txtSize - 2, COMP_TEL);
                $pdf->addText($set_pgXCenter, $set_tlY - ($set_txtSize - 2) * ($nl + 1), $set_txtSize - 2, COMP_FAX);
                $pdf->addText($set_pgXCenter, $set_tlY - ($set_txtSize - 2) * ($nl + 2), $set_txtSize - 2, "Reg No. " . COMP_REGNO);
                $pdf->addText($set_pgXCenter, $set_tlY - ($set_txtSize - 2) * ($nl + 3), $set_txtSize - 2, "VAT No. " . COMP_VATNO);
                if ($inv['chrgvat'] == "inc") {
                    $inv['chrgvat'] = "Inclusive";
                } elseif ($inv['chrgvat'] == "exc") {
                    $inv['chrgvat'] = "Exclusive";
                } else {
                    $inv['chrgvat'] = "No vat";
                }
                # Invoice details data
                $invdet[] = array('tit' => 'Invoice No.', 'val' => $inv['invnum']);
                $invdet[] = array('tit' => 'Order No.', 'val' => $inv['ordno']);
                $invdet[] = array('tit' => 'Terms', 'val' => "{$inv['terms']} Days");
                $invdet[] = array('tit' => 'Invoice Date', 'val' => $inv['odate']);
                $invdet[] = array('tit' => 'Vat', 'val' => $inv['chrgvat']);
                # invoice details
                $pdf->ezTable($invdet, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => $set_pgWidth - 42));
                # just a new line
                $pdf->ezText("\n", $set_txtSize);
                # set y so its away from the customer details
                $pdf->ezSetY($set_tlY - $set_txtSize * ($nl + 3));
                # products table
                $pdf->ezTable($products, $prodhead, '', $set_maxTblOpt);
                # Total amounts
                $amtdat[] = array('tit' => 'SUBTOTAL', 'val' => CUR . " {$SUBTOT}");
                $amtdat[] = array('tit' => 'Trade Discount', 'val' => CUR . " {$traddiscm}");
                $amtdat[] = array('tit' => "VAT @ {$VATP}%", 'val' => CUR . " {$VAT}");
                $amtdat[] = array('tit' => "Delivery Charge", 'val' => CUR . " {$inv['delchrg']}");
                $amtdat[] = array('tit' => "GRAND TOTAL", 'val' => CUR . " {$TOTAL}");
                # just a new line
                $pdf->ezText("\n", 7);
                # amounts details table data
                $pdf->ezTable($amtdat, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => $set_pgWidth - 42));
                # just a new line
                $pdf->ezSetDy(100);
                $pdf->ezText("\n", $set_txtSize);
                $comments[] = array('tit' => "Comments", 'val' => wordwrap($inv['comm'], 16));
                # VAT Number Table
                $pdf->ezTable($comments, '', "", array('showLines' => 5, 'showHeadings' => 0, 'xPos' => 79));
                $pdf->ezSetDy(-20);
                $vatdat[] = array('tit' => "VAT Exempt indicator", 'val' => "#");
                // $vatdat[] = array('tit' => "VAT No.", 'val' => COMP_VATNO);
                # VAT Number Table
                $pdf->ezTable($vatdat, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => 79));
                $i++;
            }
        }
    }
    /*******************************************************************************
     ****
     ****				NON STOCK INVOICES
     ****
     ********************************************************************************/
    while ($inv = pg_fetch_array($nonsinvRslt)) {
        $none = false;
        $invid = $inv["invid"];
        $products = array();
        $invdet = array();
        $amtdat = array();
        $comments = array();
        $vatdat = array();
        # check if stock was selected(yes = put done button)
        db_connect();
        $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $crslt = db_exec($sql);
        if (pg_numrows($crslt) < 1) {
            continue;
        }
        if ($i > 0) {
            $pdf->newPage();
        }
        # 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);
        # they product display arrays
        $products = array();
        $prodhead = array('stkdes' => 'DESCRIPTION', 'qty' => 'QTY', 'selamt' => 'UNIT PRICE', 'amt' => 'AMOUNT');
        while ($stkd = pg_fetch_array($stkdRslt)) {
            # put in product
            if ($stkd['vatex'] == 'y') {
                $stkd['description'] = "# " . $stkd['description'];
                $ex = "#";
            } else {
                $ex = "&nbsp;&nbsp;";
            }
            $products[] = array('stkdes' => "" . pdf_lstr($stkd['description']), 'qty' => $stkd['qty'], 'selamt' => CUR . " {$stkd['unitcost']}", 'amt' => CUR . " {$stkd['amt']}");
        }
        /* --- Start Some calculations --- */
        # Subtotal
        $VATP = TAX_VAT;
        $SUBTOT = sprint($inv['subtot']);
        $VAT = sprint($inv['vat']);
        $TOTAL = sprint($inv['total']);
        /* -- Final PDF output layout -- */
        # just a new line
        //		$pdf->ezText("<b>Tax Invoice\nReprint<b>", $set_txtSize+3, array('justification'=>'centre'));
        # set y so its away from the top
        $pdf->ezSetY($set_tlY);
        $set_txtSize -= 2;
        # Customer details
        $pdf->addText($set_tlX, $set_tlY, $set_txtSize, "{$inv['cusname']}");
        $nl = pdf_addnl($pdf, $set_tlX, $set_tlY, $set_txtSize, trim($inv['cusaddr']));
        $pdf->addText($set_tlX, $set_tlY - $set_txtSize * $nl, $set_txtSize, "(Vat No. {$inv['cusvatno']})");
        $pdf->addText($set_tlX, $set_tlY - $set_txtSize * ($nl + 1), $set_txtSize, "Customer Order Number: {$inv['cordno']}");
        if ($nl > 7) {
            $geninc = $nl - 7;
        } else {
            $geninc = 0;
        }
        # Company details
        $pdf->addText($set_pgXCenter, $set_tlY, $set_txtSize, COMP_NAME);
        $nl = pdf_addnl($pdf, $set_pgXCenter, $set_tlY, $set_txtSize, COMP_ADDRESS);
        $pdf->addText($set_pgXCenter, $set_tlY - $set_txtSize * $nl, $set_txtSize, COMP_TEL);
        $pdf->addText($set_pgXCenter, $set_tlY - $set_txtSize * ($nl + 1), $set_txtSize, COMP_FAX);
        $pdf->addText($set_pgXCenter, $set_tlY - $set_txtSize * ($nl + 2), $set_txtSize, "Reg No. " . COMP_REGNO);
        $pdf->addText($set_pgXCenter, $set_tlY - $set_txtSize * ($nl + 3), $set_txtSize, "VAT No. " . COMP_VATNO);
        if ($nl - 7 > $geninc) {
            //	$geninc = $nl - 6;
        }
        $set_txtSize += 2;
        # Invoice details data
        $invdet[] = array('tit' => 'Invoice No.', 'val' => $inv['invnum']);
        $invdet[] = array('tit' => 'Invoice Date', 'val' => $inv['sdate']);
        # invoice details
        $pdf->ezTable($invdet, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => $set_pgWidth - 42));
        # just a new line
        $pdf->ezText("\n", $set_txtSize);
        # set y so its away from the customer details
        $pdf->ezSetY($set_tlY - $set_txtSize * ($nl + 4 + $geninc));
        # products table
        $pdf->ezTable($products, $prodhead, '', $set_maxTblOpt);
        # Total amounts
        $amtdat[] = array('tit' => 'SUBTOTAL', 'val' => CUR . " {$SUBTOT}");
        $amtdat[] = array('tit' => "VAT @ {$VATP}%", 'val' => CUR . " {$VAT}");
        $amtdat[] = array('tit' => "GRAND TOTAL", 'val' => CUR . " {$TOTAL}");
        # just a new line
        $pdf->ezText("\n", 7);
        # Amounts details table data
        $pdf->ezTable($amtdat, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => $set_pgWidth - 42));
        # just a new line
        $pdf->ezSetDy(80);
        $pdf->ezText("\n", $set_txtSize);
        $bank = str_replace("<br>", "\n", BNK_BANKDET);
        $comments[] = array('tit' => "Comments", 'val' => wordwrap($inv['remarks'], 16));
        # VAT Number Table
        $pdf->ezTable($comments, '', "", array('showLines' => 5, 'showHeadings' => 0, 'xPos' => 89));
        $pdf->ezSetDy(-20);
        $vatdat[] = array('tit' => "VAT Exempt indicator", 'val' => "#");
        // $vatdat[] = array('tit' => "VAT No.", 'val' => COMP_VATNO);
        # VAT Number Table
        $pdf->ezTable($vatdat, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => 79));
    }
    if (!isset($none)) {
        $none = "";
    }
    if ($none) {
        if ($type == "all") {
            $type = "";
        }
        $OUTPUT = "<li class=err>Selected customer doesn't have any {$type} invoices</li>\n\t\t\t<input type=button value='[X] Close' onClick='javascript:window.close();'>";
        require "../template.php";
    }
    $pdf->ezStream();
    /* -- End Final PDF Layout -- */
}
function viewcash($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($f_day, "num", 1, 2, "Invalid Day for the 'From' date.");
    $v->isOk($f_month, "num", 1, 2, "Invalid month for the 'From' date..");
    $v->isOk($f_year, "num", 1, 4, "Invalid year for the 'From' date..");
    $v->isOk($l_day, "num", 1, 2, "Invalid Day for the 'To' date.");
    $v->isOk($l_month, "num", 1, 2, "Invalid month for the 'To' date..");
    $v->isOk($l_year, "num", 1, 4, "Invalid year for the 'To' date..");
    # lets mix the date
    $from = mkdate($f_year, $f_month, $f_day);
    $to = mkdate($l_year, $l_month, $l_day);
    if ($v->isError()) {
        $err = $v->genErrors();
        return $err;
    }
    if (isset($export)) {
        $pure = true;
    } else {
        $pure = false;
    }
    $bank = qryBankAcct($bankid);
    $curdata = qryCurrency($bank["fcid"]);
    $fc = $curdata['symbol'];
    $s1 = "";
    $s2 = "";
    $s3 = "";
    $s4 = "";
    $s5 = "";
    if (isset($order)) {
        if ($order == "ORDER BY date ASC, cheqnum ASC") {
            $s2 = "selected";
        } elseif ($order == "ORDER BY date DESC, cheqnum DESC") {
            $s3 = "selected";
        } elseif ($order == "ORDER BY cheqnum ASC") {
            $s4 = "selected";
        } elseif ($order == "ORDER BY cheqnum DESC") {
            $s5 = "selected";
        } else {
            $s1 = "selected";
        }
    } else {
        $order = "ORDER BY date DESC, cheqnum ASC";
        $s1 = "selected";
    }
    // Set up table to display in
    # Receipts
    $OUTPUT = "\n\t\t<center>\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t<tr>\n\t\t\t\t<td colspan='8' align='center'><h3>Cash Book<br><br>Account : {$bank['accname']} - {$bank['bankname']}<br>Period : {$from} to {$to}</h3></td>\n\t\t\t</tr>";
    if (!$pure) {
        $OUTPUT .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='8' align='center'>\n\t\t\t\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<input type='hidden' name='key' value='viewcash'>\n\t\t\t\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t\t\t\t\t<input type='hidden' name='f_day' value='{$f_day}'>\n\t\t\t\t\t\t<input type='hidden' name='f_month' value='{$f_month}'>\n\t\t\t\t\t\t<input type='hidden' name='f_year' value='{$f_year}'>\n\t\t\t\t\t\t<input type='hidden' name='l_day' value='{$l_day}'>\n\t\t\t\t\t\t<input type='hidden' name='l_month' value='{$l_month}'>\n\t\t\t\t\t\t<input type='hidden' name='l_year' value='{$l_year}'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Order By</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<select name='order' onChange='javascript:document.form.submit();'>\n\t\t\t\t\t\t\t\t\t<option value='' disabled {$s1} >Select</option>\n\t\t\t\t\t\t\t\t\t<option value='ORDER BY date ASC, cheqnum ASC' {$s2}>Date, Cheque No. Ascending</option>\n\t\t\t\t\t\t\t\t\t<option value='ORDER BY date DESC, cheqnum DESC' {$s3}>Date, Cheque No. Descending</option>\n\t\t\t\t\t\t\t\t\t<option value='ORDER BY cheqnum ASC' {$s4}>Cheque No. Ascending</option>\n\t\t\t\t\t\t\t\t\t<option value='ORDER BY cheqnum DESC' {$s5}>Cheque No. Descending</option>\n\t\t\t\t\t\t\t\t</select>\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 align='center'><input type='submit' name='export' value='Export to Spreadsheet'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</form>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>";
    }
    $OUTPUT .= "\n\t\t<tr>\n\t\t\t<td colspan='7'><h4>Receipts</h4></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th>Date</th>\n\t\t\t<th width='20%'>Bank Account Name</th>\n\t\t\t<th width='5%'>Cheque Number</th>\n\t\t\t<th width='15%'>Received From : </th>\n\t\t\t<th width='20%'>Description</th>\n\t\t\t<th>Reference</th>\n\t\t\t<th width='21%'>Ledger Account</th>\n\t\t\t<th width='23%'>Amount</th>\n\t\t</tr>";
    $rtotal = 0;
    // Received total amount
    // Connect to database
    db_Connect();
    $sql = "SELECT * FROM cashbook WHERE date >= '{$from}' AND date <= '{$to}' AND trantype='deposit' AND bankid='{$bankid}' AND div = '" . USER_DIV . "' {$order}";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank deposits details from database.", SELF);
    $numrows = pg_numrows($accntRslt);
    if ($numrows < 1) {
        $OUTPUT .= "<tr><td colspan='7' align='center'><li class='err'>There are no Payments/cheques received on the selected period.</td></tr>";
    } else {
        # display all bank Deposits
        for ($i = 0; $i < $numrows; $i++) {
            $accnt = pg_fetch_array($accntRslt, $i);
            if (strlen($accnt['accids']) > 0) {
                $acc['accname'] = "<a href=\"javascript: openSmallWindow('multi-acc-popup.php?cashid={$accnt['cashid']}&type=cash')\">Multiple Accounts</a>";
                $acc['accno'] = "";
            } else {
                # Get account name for the account involved
                $AccRslt = get("core", "accname, topacc, accnum", "accounts", "accid", $accnt['accinv']);
                $acc = pg_fetch_array($AccRslt);
                $acc['accno'] = "{$acc['topacc']}/{$acc['accnum']}";
            }
            # Get account name for bank account
            db_connect();
            $sql = "SELECT accname,btype FROM bankacct WHERE bankid= '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
            $bnameRslt = db_exec($sql);
            $bname = pg_fetch_array($bnameRslt);
            $rtotal += $accnt['amount'];
            // add to rtotal
            $accnt['amount'] = sprint($accnt['amount']);
            $accnt['date'] = ext_rdate($accnt['date']);
            if ($bname['btype'] != "loc") {
                $ex = "/ {$fc} {$accnt['famount']}";
            } else {
                $ex = "";
            }
            if (empty($accnt["multicusnum"])) {
                $from_disp = "{$accnt['name']}";
            } else {
                $from_disp = "<a href=\"javascript: openSmallWindow('multi-debtor-popup.php?cashid={$accnt['cashid']}&type=cash')\">Multiple Debtors</a>";
            }
            $OUTPUT .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$accnt['date']}</td>\n\t\t\t\t\t<td align='center'>{$bname['accname']}</td>\n\t\t\t\t\t<td align='center'>{$accnt['cheqnum']}</td>\n\t\t\t\t\t<td align='center'>{$from_disp}</td>\n\t\t\t\t\t<td>{$accnt['descript']}</td>\n\t\t\t\t\t<td>{$accnt['reference']}</td>\n\t\t\t\t\t<td>{$acc['accno']}  {$acc['accname']}</td>\n\t\t\t\t\t<td>" . CUR . " {$accnt['amount']} {$ex}</td>\n\t\t\t\t\t<td><a href='#' onClick=\"printer ('bank/bank-recpt-inv-print.php?recid={$accnt['cashid']}');\">Print</a></td>";
            if (!$pure && $accnt['banked'] == "no" && $accnt['opt'] != 'n') {
                $OUTPUT .= "<td><a href='../bank/cheq-return.php?cashid={$accnt['cashid']}'>Returned/Unpaid</td>";
                // $OUTPUT .= "<td><a href='../bank/cheq-cancel.php?cashid=$accnt[cashid]'>Cancel</td>";
            }
            $OUTPUT .= "</tr>";
        }
        # print the total
        $OUTPUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='6'><b>Total Receipts</b></td>\n\t\t\t\t<td><b>" . CUR . " " . sprintf("%01.2f", $rtotal) . "</b></td>\n\t\t\t</tr>";
    }
    # Seperate the tables with two rows
    $OUTPUT .= "<tr><td colspan='7'><br></td></tr><tr><td colspan='7'><br></td></tr>";
    # Payments
    $OUTPUT .= "\n\t\t<tr>\n\t\t\t<td colspan='7'><h4>Payments</h4></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th>Date</th>\n\t\t\t<th>Bank Account Name</th>\n\t\t\t<th>Cheque Number</th>\n\t\t\t<th>Paid to: </th>\n\t\t\t<th>Description</th>\n\t\t\t<th>Reference</th>\n\t\t\t<th>Ledger Account</th>\n\t\t\t<th>Amount</th>\n\t\t</tr>";
    $ptotal = 0;
    // payments total
    // Connect to database
    db_Connect();
    $sql = "SELECT * FROM cashbook WHERE date >= '{$from}' AND date <= '{$to}' AND trantype='withdrawal' AND bankid='{$bankid}' AND div = '" . USER_DIV . "' {$order}";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank deposits details from database.", SELF);
    if (pg_numrows($accntRslt) < 1) {
        $OUTPUT .= "<tr><td colspan='7' align='center'><li class='err'>There are no Payments made on the selected period.</td></tr>";
    } else {
        # Display all bank Deposits
        for ($i = 0; $accnt = pg_fetch_array($accntRslt); $i++) {
            # alternate bgcolor
            $bgColor = bgcolorc($i);
            if (strlen($accnt['accids']) > 0) {
                $acc['accname'] = "<a href=\"javascript: openSmallWindow('multi-acc-popup.php?cashid={$accnt['cashid']}&type=cash');\">Multiple Accounts</a>";
                $acc['accno'] = "";
            } else {
                # get account name for the account involved
                $AccRslt = get("core", "accname, topacc, accnum", "accounts", "accid", $accnt['accinv']);
                $acc = pg_fetch_array($AccRslt);
                $acc['accno'] = "{$acc['topacc']}/{$acc['accnum']}";
            }
            # get account name for bank account
            db_connect();
            $sql = "SELECT accname,btype FROM bankacct WHERE bankid= '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
            $bnameRslt = db_exec($sql);
            $bname = pg_fetch_array($bnameRslt);
            $ptotal += $accnt['amount'];
            //add to total
            $accnt['amount'] = sprint($accnt['amount']);
            $accnt['date'] = ext_rdate($accnt['date']);
            if ($bname['btype'] != "loc") {
                $ex = "/ {$fc} {$accnt['famount']}";
            } else {
                $ex = "";
            }
            $OUTPUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$accnt['date']}</td>\n\t\t\t\t<td align='center'>{$bname['accname']}</td>\n\t\t\t\t<td align='center'>{$accnt['cheqnum']}</td>\n\t\t\t\t<td align='center'>{$accnt['name']}</td>\n\t\t\t\t<td>{$accnt['descript']}</td>\n\t\t\t\t<td>{$accnt['reference']}</td>\n\t\t\t\t<td>{$acc['accno']}  {$acc['accname']}</td>\n\t\t\t\t<td>" . CUR . " {$accnt['amount']} {$ex}</td>";
            if (!$pure && $accnt['banked'] == "no" && $accnt['opt'] != 'n') {
                $OUTPUT .= "<td><a href='../bank/cheq-return.php?cashid={$accnt['cashid']}'>Returned/Unpaid</td>";
                // $OUTPUT .= "<td><a href='../bank/cheq-cancel.php?cashid=$accnt[cashid]'>Cancel</td>";
            }
            $OUTPUT .= "</tr>";
        }
        # print the total
        $OUTPUT .= "\n\t\t<tr class='" . bg_class() . "''>\n\t\t\t<td colspan='6'><b>Total Payments</b></td>\n\t\t\t<td><b>" . CUR . " " . sprintf("%01.2f", $ptotal) . "</b></td>\n\t\t</tr>";
    }
    if (!$pure) {
        $OUTPUT .= mkQuickLinks(ql("../core/acc-new2.php", "Add New Account"), ql("../core/acc-new2.php", "Add New Account (New Window)", true));
    }
    if (isset($export)) {
        $OUTPUT = clean_html($OUTPUT);
        require_lib("xls");
        StreamXLS("Cashbook", $OUTPUT);
    }
    return $OUTPUT;
}
function invNoteDetails($_GET)
{
    extract($_GET);
    global $set_mainFont;
    $showvat = TRUE;
    $pdf =& new Cezpdf();
    $pdf->selectFont($set_mainFont);
    // Validate
    require_lib("validate");
    $v = new Validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $v->isOk($prd, "num", 1, 9, "Invalid period.");
    // Any errors?
    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'></p>";
        $OUTPUT = $confirm;
        require "../template.php";
    }
    // Invoice info
    db_conn($prd);
    $sql = "SELECT * FROM inv_notes WHERE noteid='{$invid}' AND DIV='" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice 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 inv_items WHERE invid='{$invid}' AND DIV='" . USER_DIV . "'";
    $cRslt = db_exec($sql) or errDie("Unable to retrieve invoice info.");
    if (pg_num_rows($cRslt) < 1) {
        $error = "<li class='err'>Invoice number <b>{$invid}</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"));
    $bnkData = qryBankAcct($inv['bankid']);
    $compinfo = array();
    $compinfo[] = array(pdf_lstr($comp["addr1"], 35), pdf_lstr($comp["paddr1"], 35));
    $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 cubit.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 = "";
    }
    // 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);
    $docinfo = array(array("<b>Credit Note No:</b> {$inv['notenum']}"), array("<b>Invoice No:</b> {$inv['invnum']}"), array("<b>Sales Order No:</b> {$inv['ordno']}"), array("{$sp}"));
    // Customer info ---------------------------------------------------------
    $invoice_to = array(array(""));
    $cusinfo = array(array("<b>{$inv['surname']}</b>"));
    $addr1 = explode("\n", $cusData["addr1"]);
    foreach ($addr1 as $addr) {
        $cusinfo[] = array($addr);
    }
    $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>"));
    // Temp
    //	$inv["branch"] = 0;
    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'];
            $cusData["del_addr1"] = $barr['branch_descrip'];
        }
    }
    $cusdaddr[] = array(pdf_lstr("Branch : {$branchname}", 30));
    $del_addr = explode("\n", $cusData["del_addr1"]);
    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($prd);
    $sql = "SELECT * FROM inv_note_items WHERE noteid='{$invid}' AND DIV='" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $nsub = 0;
    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']}'";
        //	print $sql;
        $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;
        }
        $selamt = sprint($stkd['amt'] / $stkd['qty']);
        $nsub += sprint($stkd["amt"]);
        // keep track of discounts
        //$disc += $stkd['disc'];
        // Stock or non stock description?
        if (!empty($stkd["description"])) {
            $description = $stkd["description"];
        } else {
            $description = $stk["stkdes"];
        }
        $description = explode("\n", $description);
        $description = implode(" ", $description);
        $items[] = array("Stock Code" => makewidth($pdf, 80, 12, $stk["stkcod"]), "Description" => makewidth($pdf, 280, 12, $ex . $description), "Qty Returned" => $stkd['qty'], "Amount" => $stkd['amt']);
    }
    // Comment ---------------------------------------------------------------
    $comment = array(array("<i>VAT Exempt Indicator : #</i>"), array($inv["comm"]));
    // Box to sign in --------------------------------------------------------
    $sign = array(array("<i>Thank you for your support</i>"), 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 . sprint($nsub, 2)), array("1" => "<b>Trade Discount:</b> ", "2" => $curr . "{$inv['traddisc']}"), array("1" => "<b>Delivery Charge:</b> ", "2" => $curr . "{$inv['delchrg']}"), 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 * 20 < 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, 18, $heading_pos['y'] / 2 + 6);
        drawText(&$pdf, "<b>Tax Credit Note</b>", 18, $heading_pos['x'] - 140, $heading_pos['y'] / 2 + 9);
        // Should we display reprint on the invoice
        if ($type == "invnotereprint") {
            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, 4);
        $pagenr_pos = drawTable(&$pdf, $pagenr, $date_pos['x'], $heading_pos['y'], 100, 4);
        $docinfo_pos = drawTable(&$pdf, $docinfo, $compinfo_pos['x'], $date_pos['y'], 200, 4);
        $invoice_to_pos = drawTable(&$pdf, $invoice_to, 0, $compinfo_pos['y'], 520, 2);
        drawText(&$pdf, "<b>Credit Note 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("Stock Code" => array("width" => 80), "Description" => array("width" => 280), "Qty Returned" => array("width" => 80), "Amount" => array("width" => 80, "justification" => "right"));
        $items_pos = drawTable(&$pdf, $items_print, 0, $regnos_pos['y'] + 2, 520, 23, $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);
        $pdf->addText(20, 34, 6, 'Cubit Accounting');
    }
    $pdf->ezStream();
}