function pdfinv($_GET)
{
    # Get vars
    foreach ($_GET as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($invids as $key => $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid recuring invoice number.");
    }
    /* 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);
    # 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 */
    $i = 0;
    foreach ($invids as $key => $invid) {
        # Get recuring invoice info
        db_connect();
        $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $invRslt = db_exec($sql) or errDie("Unable to get recuring invoice information");
        if (pg_numrows($invRslt) < 1) {
            return "<i class=err>Not Found</i>";
        }
        $inv = pg_fetch_array($invRslt);
        $products = array();
        $invdet = array();
        $amtdat = array();
        $comments = array();
        $vatdat = array();
        # Create a new page for invoice
        if ($i > 0) {
            $pdf->newPage();
        }
        /* --- 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) {
            $error = "<li class=err> Error : Invoice number <b>{$invid}</b> has no items.";
            $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            $OUTPUT = $error;
            require "template.php";
        }
        /* --- 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 ($stkd['exvat'] == 'y') {
                $ex = "#";
            } else {
                $ex = "  ";
            }
            # keep track of discounts
            $disc += $stkd['disc'];
            # put in product
            $products[] = array('stkcod' => $stk['stkcod'], 'stkdes' => "{$ex} {$sp} " . pdf_lstr($stk['stkdes']), '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']);
        /*/
        		# 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, "{$inv['surname']}");
        $nl = pdf_addnl($pdf, $set_tlX, $set_tlY, $set_txtSize, $inv['cusaddr']);
        $pdf->addText($set_tlX, $set_tlY - $set_txtSize * $nl, $set_txtSize, "(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);
        $invdet = array();
        # 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']);
        # 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 . " {$inv['discount']}");
        $amtdat[] = array('tit' => "Delivery Charge", 'val' => CUR . " {$inv['delivery']}");
        $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(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++;
    }
    $pdf->ezStream();
    /* -- End Final PDF Layout -- */
}
function printStmnt()
{
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    if (pg_numrows($custRslt) < 1) {
        return "<li class=err>There are no customers found.";
    }
    /* 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);
    # Heading
    $pdf->ezText("<b>Customer Monthly Statement</b>", $set_txtSize + 2, 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');
    /* End PDF Layout */
    $i = 0;
    while ($cust = pg_fetch_array($custRslt)) {
        $cusnum = $cust['cusnum'];
        $stmnt = array();
        $cusdet = array();
        $baldat = array();
        $currs = getSymbol($cust['fcid']);
        $curr = $currs['symbol'];
        # Create a new page for customer
        if ($i > 0) {
            $pdf->newPage();
        }
        # connect to database
        db_connect();
        $fdate = date("Y") . "-" . date("m") . "-" . "01";
        $stmnt = array();
        $totout = 0;
        if (!open()) {
            # Query server
            $sql = "SELECT * FROM stmnt WHERE cusnum = '{$cusnum}' AND date >= '{$fdate}' AND div = '" . USER_DIV . "' ORDER BY date ASC";
            $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
        } else {
            # Query server
            $sql = "SELECT * FROM open_stmnt WHERE cusnum = '{$cusnum}' AND balance != '0' AND div = '" . USER_DIV . "' ORDER BY date ASC";
            $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
        }
        if (pg_numrows($stRslt) < 1) {
            $stmnt[] = array('date' => "No previous invoices/transactions for this month.", 'invid' => " ", 'type' => " ", 'amount' => " ");
        } else {
            while ($st = pg_fetch_array($stRslt)) {
                # 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, 17) == "Non-Stock Invoice") {
                    $ex = "INV";
                } elseif (substr($st['type'], 0, 21) == "Non Stock Credit Note") {
                    $ex = "CR";
                } elseif (substr($st['type'], 0, 11) == "Credit Note") {
                    $ex = "CR";
                } else {
                    $ex = "";
                }
                $stmnt[] = array('date' => $st['date'], 'invid' => $ex . " " . $st['invid'], 'type' => $st['type'], 'amount' => $curr . " {$st['amount']}");
                # keep track of da totals
                $totout += $st['amount'];
            }
        }
        $balbf = $cust['balance'] - $totout;
        $balbf = sprint($balbf);
        $cust['balance'] = sprint($cust['balance']);
        $stmnthead = array('date' => "Date", 'invid' => "Ref No.", 'type' => "Details", 'amount' => "Amount");
        /* start PDF Layout */
        # Heading
        // $pdf->ezText("<b>Customer Monthly Statement</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));
        # customer details data
        $cusdet[] = array('tit' => "Account number : {$cust['accno']}");
        $cusdet[] = array('tit' => "{$cust['surname']}\n{$cust['addr1']}");
        $cusdet[] = array('tit' => "Balance Brought Forward : " . $curr . " {$balbf}");
        # customer details table
        $pdf->ezTable($cusdet, '', "", array('shaded' => 0, 'showLines' => 2, 'showHeadings' => 0, 'xPos' => 94));
        # just a new line
        $pdf->ezText("\n", $set_txtSize);
        # Statement table
        $pdf->ezTable($stmnt, $stmnthead, '', $set_maxTblOptNl);
        # just a new line
        $pdf->ezText("\n", $set_txtSize);
        # balance table data
        $baldat[] = array('tit' => "Total Outstanding Balance : " . $curr . " {$cust['balance']}");
        # balance table
        $pdf->ezTable($baldat, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => $set_pgWidth - 63));
        $i++;
    }
    # Send stream
    $pdf->ezStream();
    exit;
}
function printStmnt($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($supid, "num", 1, 20, "Invalid Supplier number.");
    $v->isOk($fday, "num", 1, 2, "Invalid from Date day.");
    $v->isOk($fmon, "num", 1, 2, "Invalid from Date month.");
    $v->isOk($fyear, "num", 1, 4, "Invalid from Date Year.");
    $v->isOk($today, "num", 1, 2, "Invalid to Date day.");
    $v->isOk($tomon, "num", 1, 2, "Invalid to Date month.");
    $v->isOk($toyear, "num", 1, 4, "Invalid to Date Year.");
    # mix dates
    $fromdate = $fyear . "-" . $fmon . "-" . $fday;
    $todate = $toyear . "-" . $tomon . "-" . $today;
    if (!checkdate($fmon, $fday, $fyear)) {
        $v->isOk($fromdate, "num", 1, 1, "Invalid from date.");
    }
    if (!checkdate($tomon, $today, $toyear)) {
        $v->isOk($todate, "num", 1, 1, "Invalid to date.");
    }
    # isplay errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return $err;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $suppRslt = db_exec($sql) or errDie("Unable to view Supplier");
    if (pg_numrows($suppRslt) < 1) {
        return "<li class=err>Invalid Supplier Number.";
    }
    $supp = pg_fetch_array($suppRslt);
    # Connect to database
    db_connect();
    $fdate = date("Y") . "-" . date("m") . "-" . "01";
    $stmnt = array();
    $totout = 0;
    # Query server
    $sql = "SELECT * FROM sup_stmnt WHERE supid = '{$supid}' AND edate >= '{$fromdate}' AND edate <= '{$todate}' AND div = '" . USER_DIV . "' ORDER BY edate ASC";
    $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
    if (pg_numrows($stRslt) < 1) {
        $stmnt[] = array('date' => "No previous invoices/transactions for this month.", 'ref' => "  ", 'cacc' => "  ", 'descript' => "  ", 'amount' => "  ");
    } else {
        while ($st = pg_fetch_array($stRslt)) {
            # format date
            $st['edate'] = explode("-", $st['edate']);
            $st['edate'] = $st['edate'][2] . "-" . $st['edate'][1] . "-" . $st['edate'][0];
            $st['amount'] = sprint($st['amount']);
            # Accounts details
            if ($st['cacc'] > 0) {
                $accRs = get("core", "*", "accounts", "accid", $st['cacc']);
                $acc = pg_fetch_array($accRs);
                $Dis = "{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}";
            } else {
                $Dis = "Purchase Num: {$st['ex']}";
            }
            $stmnt[] = array('date' => $st['edate'], 'ref' => $st['ref'], 'cacc' => $Dis, 'descript' => "{$st['descript']}", 'amount' => CUR . " {$st['amount']}");
            # keep track of da totals
            $totout += $st['amount'];
        }
    }
    # get overlapping amount
    db_connect();
    $sql = "SELECT sum(amount) as amount FROM sup_stmnt WHERE supid = '{$supid}' AND edate > '{$todate}' AND div = '" . USER_DIV . "' ";
    $balRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
    $bal = pg_fetch_array($balRslt);
    $supp['balance'] = $supp['balance'] - $bal['amount'];
    $balbf = $supp['balance'] - $totout;
    $balbf = sprint($balbf);
    $totout = sprint($totout);
    $supp['balance'] = sprint($supp['balance']);
    $stmnthead = array('date' => "Date", 'ref' => "Ref", 'cacc' => "Contra Acc.", 'descript' => "Description", 'amount' => "Amount");
    /* 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>Supplier Monthly Statement</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));
    # customer details data
    $cusdet[] = array('tit' => "Supplier number : {$supp['supno']}");
    $cusdet[] = array('tit' => "{$supp['supname']}\n\n{$supp['supaddr']}");
    $cusdet[] = array('tit' => "Balance Brought Forward : " . CUR . " {$balbf}");
    # customer details table
    $pdf->ezTable($cusdet, '', "", array('shaded' => 0, 'showLines' => 2, 'showHeadings' => 0, 'xPos' => 94));
    # just a new line
    $pdf->ezText("\n", $set_txtSize);
    # Statement table
    $pdf->ezTable($stmnt, $stmnthead, '', $set_maxTblOptNl);
    # just a new line
    $pdf->ezText("\n", $set_txtSize);
    # balance table data
    $baldat[] = array('tit' => "Total Outstanding Balance : " . CUR . " {$supp['balance']}");
    # balance table
    $pdf->ezTable($baldat, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => $set_pgWidth - 63));
    # Send stream
    $pdf->ezStream();
    exit;
}
function printStmnt($_GET)
{
    # get vars
    foreach ($_GET as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 20, "Invalid Customer number.");
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return $err;
    }
    # 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.";
    }
    $cust = pg_fetch_array($custRslt);
    # connect to database
    db_connect();
    $fdate = date("Y") . "-" . date("m") . "-" . "01";
    $stmnt = array();
    $totout = 0;
    # Query server
    $sql = "SELECT * FROM stmnt WHERE cusnum = '{$cusnum}' AND date >= '{$fdate}' AND div = '" . USER_DIV . "' ";
    $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
    if (pg_numrows($stRslt) < 1) {
        $stmnt[] = array('date' => "No previous invoices/transactions for this month.", 'invid' => " ", 'type' => " ", 'amount' => " ");
    } else {
        while ($st = pg_fetch_array($stRslt)) {
            # format date
            $st['date'] = explode("-", $st['date']);
            $st['date'] = $st['date'][2] . "-" . $st['date'][1] . "-" . $st['date'][0];
            $st['amount'] = sprint($st['amount']);
            $stmnt[] = array('date' => $st['date'], 'invid' => $st['invid'], 'type' => $st['type'], 'amount' => CUR . " {$st['amount']}");
            # keep track of da totals
            $totout += $st['amount'];
        }
    }
    $balbf = $cust['balance'] - $totout;
    $balbf = sprint($balbf);
    $cust['balance'] = sprint($cust['balance']);
    $stmnthead = array('date' => "Date", 'invid' => "Invoice No.", 'type' => "Details", 'amount' => "Amount");
    /* 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 Monthly Statement</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));
    # customer details data
    $cusdet[] = array('tit' => "Account number : {$cust['accno']}");
    $cusdet[] = array('tit' => "{$cust['cusname']}  {$cust['surname']}\n\n{$cust['addr1']}");
    $cusdet[] = array('tit' => "Balance Brought Forward : " . CUR . " {$balbf}");
    # customer details table
    $pdf->ezTable($cusdet, '', "", array('shaded' => 0, 'showLines' => 2, 'showHeadings' => 0, 'xPos' => 94));
    # just a new line
    $pdf->ezText("\n", $set_txtSize);
    # Statement table
    $pdf->ezTable($stmnt, $stmnthead, '', $set_maxTblOptNl);
    # just a new line
    $pdf->ezText("\n", $set_txtSize);
    # balance table data
    $baldat[] = array('tit' => "Total Outstanding Balance : " . CUR . " {$cust['balance']}");
    # balance table
    $pdf->ezTable($baldat, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => $set_pgWidth - 63));
    # Send stream
    $pdf->ezStream();
    exit;
}
function details($_GET)
{
    # get vars
    foreach ($_GET as $key => $value) {
        ${$key} = $value;
    }
    # 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"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        $OUTPUT = $confirm;
        require "../template.php";
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class=err>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    /* --- Start some checks --- */
    # 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) {
        $error = "<li class=err> Error : Invoice number <b>{$inv['invnum']}</b> has no items.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        $OUTPUT = $error;
        require "../template.php";
    }
    /* --- End some checks --- */
    /* 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');
    /* /Start PDF Layout */
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # 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
        $products[] = array('stkdes' => "" . pdf_lstr($stkd['description']), 'qty' => $stkd['qty'], 'selamt' => $inv['currency'] . " {$stkd['unitcost']}", 'amt' => $inv['currency'] . " {$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);
    # Customer details
    $pdf->addText($set_tlX, $set_tlY, $set_txtSize, "{$inv['cusname']}");
    $nl = pdf_addnl($pdf, $set_tlX, $set_tlY, $set_txtSize, $inv['cusaddr']);
    $pdf->addText($set_tlX, $set_tlY - $set_txtSize * $nl, $set_txtSize, "(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_ADDRESS);
    $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);
    # 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 + 3));
    # products table
    $pdf->ezTable($products, $prodhead, '', $set_maxTblOpt);
    # Total amounts
    $amtdat[] = array('tit' => 'SUBTOTAL', 'val' => $inv['currency'] . " {$SUBTOT}");
    $amtdat[] = array('tit' => "VAT @ {$VATP}%", 'val' => $inv['currency'] . " {$VAT}");
    $amtdat[] = array('tit' => "GRAND TOTAL", 'val' => $inv['currency'] . " {$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);
    $pdf->ezSetDy(-20);
    $pdf->ezStream();
    /* -- End Final PDF Layout -- */
}
function details($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($quoid, "num", 1, 20, "Invalid quote 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";
    }
    # Get quote info
    db_connect();
    $sql = "SELECT * FROM pos_quotes WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
    $quoRslt = db_exec($sql) or errDie("Unable to get quote information");
    if (pg_numrows($quoRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $quo = pg_fetch_array($quoRslt);
    # format date
    $quo['odate'] = explode("-", $quo['odate']);
    $quo['odate'] = $quo['odate'][2] . "-" . $quo['odate'][1] . "-" . $quo['odate'][0];
    /* --- Start some checks --- */
    # check if stock was selected(yes = put done button)
    db_connect();
    $sql = "SELECT stkid FROM pos_quote_items WHERE quoid = '{$quo['quoid']}' AND div = '" . USER_DIV . "'";
    $crslt = db_exec($sql);
    if (pg_numrows($crslt) < 1) {
        $error = "<li class='err'> Error : Quote number <b>{$quoid}</b> has no items.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        $OUTPUT = $error;
        require "../template.php";
    }
    /* --- End some checks --- */
    /* 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');
    /* /Start PDF Layout */
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this quote
    db_connect();
    $sql = "SELECT * FROM pos_quote_items  WHERE quoid = '{$quoid}' 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', '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'];
        // Stock or non stock description?
        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']}", 'amt' => CUR . " {$stkd['amt']}");
    }
    /* --- Start Some calculations --- */
    # subtotal
    $SUBTOT = sprint($quo['subtot']);
    # Calculate tradediscm
    if (strlen($quo['traddisc']) > 0) {
        $traddiscm = sprint($quo['traddisc'] / 100 * $SUBTOT);
    } else {
        $traddiscm = "0.00";
    }
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOT = sprint($quo['subtot']);
    $VAT = sprint($quo['vat']);
    $TOTAL = sprint($quo['total']);
    $quo['delchrg'] = sprint($quo['delchrg']);
    /* --- End Some calculations --- */
    /* -- Final PDF output layout -- */
    # just a new line
    $pdf->ezText("<b>Quote<b>", $set_txtSize + 3, array('justification' => 'centre'));
    # set y so its away from the top
    $pdf->ezSetY($set_tlY);
    # Customer details
    $pdf->addText($set_tlX, $set_tlY, $set_txtSize, "{$quo['cusname']}");
    $nl = pdf_addnl($pdf, $set_tlX, $set_tlY, $set_txtSize, $quo['cusaddr']);
    $pdf->addText($set_tlX, $set_tlY - $set_txtSize * $nl, $set_txtSize, "");
    # 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_ADDRESS);
    $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, "VAT No. " . COMP_VATNO);
    # Quote details data
    $quodet[] = array('tit' => 'Quote No.', 'val' => $quo['quoid']);
    $quodet[] = array('tit' => 'Order No.', 'val' => $quo['ordno']);
    $quodet[] = array('tit' => 'Terms', 'val' => "{$quo['terms']} Days");
    if ($quo['salespn'] != "General") {
        $quodet[] = array('tit' => 'Sales Person', 'val' => $quo['salespn']);
    }
    $quodet[] = array('tit' => 'Quote Date', 'val' => $quo['odate']);
    # quote details
    $pdf->ezTable($quodet, '', "", 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 . " {$quo['discount']}");
    $amtdat[] = array('tit' => "Delivery Charge", 'val' => CUR . " {$quo['delivery']}");
    $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(100);
    $pdf->ezText("\n", $set_txtSize);
    $comments[] = array('tit' => "Comments", 'val' => "{$quo['comm']}");
    # 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));
    $pdf->ezStream();
    /* -- End Final PDF Layout -- */
}
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 state($id, $fromdate, $todate, $type)
{
    $fdate = $fromdate;
    global $set_mainFont, $set_codeFont, $set_pgWidth, $set_pgHeight, $set_pgXCenter, $set_pgYCenter, $set_tlX, $set_tlY, $set_txtSize, $set_ttlY, $set_maxTblOpt, $set_maxTblOptNl, $set_repTblOpt, $set_repTblOptSm, $set_tubTblOpt, $set_tubTblOpt2, $set_tubTblOpt3;
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$id}' 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;
    if ($type == "Monthly") {
        $fdate = date("Y") . "-" . date("m") . "-" . "01";
        $whe = "";
    } else {
        $whe = "AND date<='{$todate}'";
    }
    if (!open()) {
        # Query server
        $sql = "SELECT * FROM stmnt WHERE cusnum = '{$id}' AND date >= '{$fdate}' AND div = '" . USER_DIV . "' {$whe} ORDER BY date";
        $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
    } else {
        # Query server
        $sql = "SELECT * FROM open_stmnt WHERE cusnum = '{$id}' AND balance != '0' AND div = '" . USER_DIV . "' {$whe} ORDER BY date";
        $stRslt = db_exec($sql) or errDie("Unable to retrieve invoices statement from database.");
    }
    if (pg_numrows($stRslt) < 1) {
        $stmnt[] = array('date' => "No invoices/transactions for this month.", 'invid' => " ", 'type' => " ", 'amount' => " ");
    } else {
        while ($st = pg_fetch_array($stRslt)) {
            # 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[] = array('date' => $st['date'], 'invid' => $ex . " " . $st['invid'], 'type' => $st['type'], 'amount' => "{$cust['currency']} {$st['amount']}");
            # keep track of da totals
            $totout += $st['amount'];
        }
    }
    if ($cust['location'] == 'int') {
        $cust['balance'] = $cust['fbalance'];
    }
    $balbf = $cust['balance'] - $totout;
    $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']);
    }
    $stmnthead = array('date' => "Date", 'invid' => "Ref No.", 'type' => "Details", 'amount' => "Amount");
    $agehead = array('cur' => "Current", '30' => "30 days", '60' => "60 days", '90' => "90 days", '120' => "120 days +");
    $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 Monthly Statement</b>", $set_txtSize + 2, array('justification' => 'centre'));
    if ($type == "Monthly") {
        $pdf->ezText(date("Y-m-") . "01 - " . date("Y-m-d", mktime(0, 0, 0, date("m") + 1, -0, date("Y"))), $set_txtSize, array('justification' => 'centre'));
    } else {
        $pdf->ezText("{$fromdate} - {$todate}", $set_txtSize, 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));
    # customer details data
    $cusdet[] = array('tit' => "Account number : {$cust['accno']}");
    $cusdet[] = array('tit' => "{$cust['surname']}\n{$cust['addr1']}");
    $cusdet[] = array('tit' => "Balance Brought Forward : {$cust['currency']} {$balbf}");
    # customer details table
    $pdf->ezTable($cusdet, '', "", array('shaded' => 0, 'showLines' => 2, 'showHeadings' => 0, 'xPos' => 94));
    # just a new line
    $pdf->ezText("\n", $set_txtSize);
    # Statement table
    $pdf->ezTable($stmnt, $stmnthead, '', $set_maxTblOptNl);
    # just a new line
    $pdf->ezText("\n", $set_txtSize);
    # balance table data
    $baldat[] = array('tit' => "Total Outstanding Balance : {$cust['currency']} {$cust['balance']}");
    //$pdf->ezSetY($set_tlY -200);
    # balance table
    $pdf->ezTable($baldat, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => $set_pgWidth - 63));
    $pdf->ezText("\n", $set_txtSize);
    if ($type == "Monthly") {
        $pdf->ezTable($age, $agehead, '', $set_maxTblOptNl);
    }
    return $pdf->output();
    exit;
    # Send stream
    $pdf->ezStream();
    exit;
}
function details($_GET)
{
    # get vars
    foreach ($_GET as $key => $value) {
        ${$key} = $value;
    }
    $showvat = TRUE;
    # 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"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        $OUTPUT = $confirm;
        require "../template.php";
    }
    # Get invoice info
    db_connect();
    $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);
    # check if invoice has been printed
    if ($inv['printed'] != "y") {
        $error = "<li class=err> Error : Invoice number <b>{$invid}</b> has not been printed yet.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        $OUTPUT = $error;
        require "../template.php";
    }
    /* --- 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) {
        $error = "<li class=err> Error : Invoice number <b>{$invid}</b> has no items.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        $OUTPUT = $error;
        require "../template.php";
    }
    /* --- End some checks --- */
    /* 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');
    /* /Start PDF Layout */
    /* --- 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)) {
        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);
        } else {
            $wh['whname'] = "";
            $stk['stkcod'] = "";
            $stk['stkdes'] = $stkd['description'];
        }
        $stkd['vatcode'] += 0;
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        $vd = pg_fetch_array($Ri);
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        if (pg_num_rows($Ri) > 0) {
            if ($vd['zero'] == "Yes") {
                $stk['exvat'] = "yes";
            }
        } else {
            $stk['exvat'] = "";
        }
        $sp = "";
        # Check Tax Excempt
        if ($stk['exvat'] == 'yes') {
            $ex = "#";
        } else {
            $ex = "";
        }
        # keep track of discounts
        $disc += $stkd['disc'];
        // Are we working with stock or non stock?
        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']}");
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    /* --- 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']);
    # 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");
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='SALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    $data = pg_fetch_array($Ri);
    /* -- Final PDF output layout -- */
    # just a new line
    $pdf->ezText("<b>Tax Invoice\nReprint {$inv['prints']}<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['surname']}");
    $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);
    $set_txtSize += 2;
    # Invoice details data
    $invdet[] = array('tit' => 'Invoice No.', 'val' => $inv['invnum']);
    $invdet[] = array('tit' => 'Proforma Inv No.', 'val' => $inv['docref']);
    $invdet[] = array('tit' => 'Order No.', 'val' => $inv['ordno']);
    $invdet[] = array('tit' => 'Terms', 'val' => "{$inv['terms']} Days");
    if ($data['value'] == "Yes") {
        $invdet[] = array('tit' => 'Sales Person', 'val' => "{$inv['salespn']}");
    }
    $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));
    # set x away from customer details AND invoice details
    //$pdf->ezText("\n", $set_txtSize);
    $pdf->ezSetDy($set_txtSize * ($geninc + 1) * -1);
    # products table
    $ypos_products = $pdf->ezTable($products, $prodhead, '', $set_maxTblOpt);
    # Total amounts
    $amtdat[] = array('tit' => 'SUBTOTAL', 'val' => CUR . " {$SUBTOT}");
    $amtdat[] = array('tit' => 'Trade Discount', 'val' => CUR . " {$inv['discount']}");
    $amtdat[] = array('tit' => "Delivery Charge", 'val' => CUR . " {$inv['delivery']}");
    $amtdat[] = array('tit' => "VAT {$vat14}", 'val' => CUR . " {$VAT}");
    $amtdat[] = array('tit' => "GRAND TOTAL", 'val' => CUR . " {$TOTAL}");
    # just a new line
    $pdf->ezSetDy($set_txtSize * -1);
    # 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);
    $bank = str_replace("<br>", "\n", BNK_BANKDET);
    $comments[] = array('tit' => "Comments", 'val' => wordwrap($inv['comm'], 16));
    $banks[] = array('tit' => "Bank Details");
    $banks[] = array('tit' => "{$bank}");
    $pdf->ezSetY($ypos_products - $set_txtSize);
    $ypos_comments = $pdf->ezTable($comments, '', "", array('showLines' => 5, 'showHeadings' => 0, 'xPos' => 18, 'xOrientation' => 'right'));
    $pdf->ezSetY($ypos_products - $set_txtSize);
    $ypos_bank = $pdf->ezTable($banks, '', "", array('showLines' => 3, 'showHeadings' => 0, 'xPos' => 250));
    $vatdat[] = array('tit' => "VAT Exempt indicator", 'val' => "#");
    // $vatdat[] = array('tit' => "VAT No.", 'val' => COMP_VATNO);
    # VAT Number Table
    $pdf->ezSetY(($ypos_comments < $ypos_bank ? $ypos_comments : $ypos_bank) - $set_txtSize);
    $pdf->ezTable($vatdat, '', "", array('showLines' => 2, 'showHeadings' => 0, 'xPos' => 18, 'xOrientation' => 'right'));
    $pdf->ezStream();
    /* -- End Final PDF Layout -- */
}
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 -- */
}