function printOrd($_POST, $pure = false)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $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.");
    }
    require_lib("docman");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li>";
        }
        return $confirm;
    }
    # Set up table to display in
    $printOrd = "";
    if (!$pure) {
        $printOrd .= "\n\t\t\t\t\t\t<center>\n\t\t\t\t\t\t<h3>View International Stock Purchases</h3>";
    }
    $printOrd .= "\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Purchase No.</th>\n\t\t\t\t\t\t\t<th>Purchase Date</th>\n\t\t\t\t\t\t\t<th>Received Date</th>\n\t\t\t\t\t\t\t<th>Supplier</th>\n\t\t\t\t\t\t\t<th>Sub Total</th>\n\t\t\t\t\t\t\t<th>Shipping Charges</th>\n\t\t\t\t\t\t\t<th>Tax</th>\n\t\t\t\t\t\t\t<th colspan='2'>Total Cost Amount</th>\n\t\t\t\t\t\t\t<th>Documents</th>\n\t\t\t\t\t\t\t<th colspan='5'>Options</th>\n\t\t\t\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $sql = "SELECT * FROM purch_int WHERE pdate >= '{$fromdate}' AND pdate <= '{$todate}' AND div = '" . USER_DIV . "' ORDER BY pdate DESC";
    $stkpRslt = db_exec($sql) or errDie("Unable to retrieve stock purchases from database.");
    if (pg_numrows($stkpRslt) < 1) {
        return "\n\t\t\t\t<li class='err'> There are no previous stock purchases.</li>" . mkQuickLinks(ql("purch-int-new.php", "New International Order"), ql("purch-int-view.php", "View International Orders"), ql("stock-view.php", "View Stock"));
    }
    while ($stkp = pg_fetch_array($stkpRslt)) {
        # Date format
        $date = explode("-", $stkp['pdate']);
        $date = $date[2] . "-" . $date[1] . "-" . $date[0];
        $ddate = explode("-", $stkp["ddate"]);
        $ddate = "{$ddate['2']}-{$ddate['1']}-{$ddate['0']}";
        # Get supplier
        db_connect();
        $sql = "SELECT supname,currency FROM suppliers WHERE supid = '{$stkp['supid']}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql);
        if (pg_numrows($supRslt) < 1) {
            $sup['supname'] = "<li class='err'>Supplier not found";
            $sup['currency'] = "";
        } else {
            $sup = pg_fetch_array($supRslt);
        }
        # Calculate the Sub-Total
        $subtot = sprint($stkp['total'] - $stkp['shipchrg']);
        $stkp['tax'] = sprint($stkp['tax']);
        $stkp['shipchrg'] = sprint($stkp['shipchrg']);
        # Get documents
        $docs = doclib_getdocs("ipur", $stkp['purnum']);
        $sp4 = "&nbsp;&nbsp;&nbsp;&nbsp;";
        $printOrd .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$stkp['purnum']}</td>\n\t\t\t\t\t<td>{$date}</td>\n\t\t\t\t\t<td>{$ddate}</td>\n\t\t\t\t\t<td>{$sup['supname']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$stkp['curr']} {$subtot}</td>\n\t\t\t\t\t<td align='right' nowrap>{$stkp['curr']} {$stkp['shipchrg']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$stkp['curr']} {$stkp['tax']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$sp4} {$stkp['curr']} {$stkp['total']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$sp4} " . CUR . " {$stkp['fbalance']}</td>\n\t\t\t\t\t<td>{$docs}</td>\n\t\t\t\t\t<td><a href='javascript: printer(\"purch-int-det.php?purid={$stkp['purid']}\");'>Print</a></td>";
        if ($stkp['received'] != "y" && $subtot == 0) {
            $printOrd .= "\n\t\t\t\t\t<td colspan='2' align='center'><a href='purch-int-new.php?purid={$stkp['purid']}&cont=1&letters=&done='>Edit</a></td>\n\t\t\t\t\t<td><br></td>\n\t\t\t\t\t<td><a href='purch-int-cancel.php?purid={$stkp['purid']}'>Cancel</a></td>\n\t\t\t\t</tr>";
        } elseif ($stkp['received'] != 'y') {
            $recinv = "<br>";
            if ($stkp['invcd'] != 'y') {
                $recinv = "<a href='purch-int-recinvcd.php?purid={$stkp['purid']}'>Record Invoice</a>";
            }
            $printOrd .= "\n\t\t\t\t\t<td><a href='purch-int-new.php?purid={$stkp['purid']}&cont=1&letters=&done='>Edit</a></td>\n\t\t\t\t\t<td><a href='purch-int-recv.php?purid={$stkp['purid']}'>Received</a></td>\n\t\t\t\t\t<td>{$recinv}</td>\n\t\t\t\t\t<td><a href='purch-int-cancel.php?purid={$stkp['purid']}'>Cancel</a></td>\n\t\t\t\t</tr>";
        } else {
            $recinv = "<br>";
            if ($stkp['invcd'] != 'y') {
                $recinv = "<a href='purch-int-recinvcd.php?purid={$stkp['purid']}'>Record Invoice</a>";
            }
            $printOrd .= "\n\t\t\t\t\t<td colspan='2'>Received</td>\n\t\t\t\t\t<td>{$recinv}</td>\n\t\t\t\t\t<td><br></td>\n\t\t\t\t</tr>";
        }
        $i++;
    }
    if (!$pure) {
        $printOrd .= "\n\t\t" . TBL_BR . "\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='export'>\n\t\t\t<input type='hidden' name='from_day' value='{$from_day}'>\n\t\t\t<input type='hidden' name='from_month' value='{$from_month}'>\n\t\t\t<input type='hidden' name='from_year' value='{$from_year}'>\n\t\t\t<input type='hidden' name='to_day' value='{$to_day}'>\n\t\t\t<input type='hidden' name='to_month' value='{$to_month}'>\n\t\t\t<input type='hidden' name='to_year' value='{$to_year}'>\n\t\t\t<tr>\n\t\t\t\t<td colspan='3'><input type='submit' value='Export to Spreadsheet'></td>\n\t\t\t</tr>\n\t\t</form>";
    }
    if (!$pure) {
        $printOrd .= "\n\t\t</table>";
    }
    if (!$pure) {
        $printOrd .= mkQuickLinks(ql("purch-int-new.php", "New International Purchase"), ql("stock-report.php", "Stock Control Reports"), ql("stock-view.php", "View Stock"));
    }
    return $printOrd;
}
function printInvoice($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $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.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return $confirm;
    }
    # Set up table to display in
    $printOrd = "\r\n\t\t<center>\r\n\t\t<h3>View Non-Stock Invoices</h3>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t<form action='invoice-proc.php' method='GET'>\r\n\t\t\t<input type='hidden' name='t' value='i'>\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Invoice Num</th>\r\n\t\t\t\t<th>Proforma Inv No.</th>\r\n\t\t\t\t<th>Invoice Date</th>\r\n\t\t\t\t<th>Customer</th>\r\n\t\t\t\t<th>Total</th>\r\n\t\t\t\t<th>Documents</th>\r\n\t\t\t\t<th colspan='6'>Options</th>\r\n\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot_subtot = 0;
    $tot_total = 0;
    $sql = "SELECT * FROM nons_invoices WHERE typ = 'inv' AND sdate >= '{$fromdate}' \tAND sdate <= '{$todate}' \tAND div = '" . USER_DIV . "' AND balance = 0 AND done = 'y' ORDER BY invnum";
    $nonstksRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($nonstksRslt) < 1) {
        return "<li> There are no non stock invoices found.</li>";
    }
    // Retrieve the PDF reprints
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='reprints' AND div='" . USER_DIV . "'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    while ($nonstks = pg_fetch_array($nonstksRslt)) {
        # date format
        $date = explode("-", $nonstks['odate']);
        $date = $date[2] . "-" . $date[1] . "-" . $date[0];
        // compute the totals
        if ($nonstks["xrate"] == 0.0) {
            $tot_subtot += $nonstks["subtot"];
            $tot_total += $nonstks["total"];
        } else {
            $tot_subtot += $nonstks["subtot"] * $nonstks["xrate"];
            $tot_total += $nonstks["total"] * $nonstks["xrate"];
        }
        if ($nonstks['invnum'] == 0) {
            $nonstks['invnum'] = $nonstks['invid'];
        }
        $det = "nons-invoice-det.php";
        $edit = "nons-invoice-new.php";
        $print = "nons-invoice-print.php";
        $reprint = "nons-invoice-reprint.php";
        $note = "nons-invoice-note.php";
        if ($template == "default") {
            $template = "nons-invoice-pdf-reprint.php";
        } elseif ($template == "new") {
            $template = "pdf-tax-invoice.php";
        }
        $reprpdf = $template;
        $cur = CUR;
        if ($nonstks['location'] == 'int') {
            $det = "nons-intinvoice-det.php";
            $edit = "nons-intinvoice-new.php";
            $print = "nons-intinvoice-print.php";
            $note = "nons-intinvoice-note.php";
            if ($template == "default") {
                $template = "nons-intinvoice-pdf-reprint.php";
            } elseif ($template == "new") {
                $template = "pdf-tax-invoice.php";
            }
            $reprpdf = $template;
            $note = "nons-intinvoice-note.php";
            $cur = $nonstks['currency'];
        }
        # Get documents
        $docs = doclib_getdocs("ninv", $nonstks['invnum']);
        if ($nonstks['accepted'] == " " && $nonstks['done'] != "y") {
            $chbox = "<input type=checkbox name='evs[{$nonstks['invid']}]' value='{$nonstks['invid']}' checked=yes>";
        } else {
            $chbox = "";
        }
        $printOrd .= "\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>{$nonstks['invnum']}</td>\r\n\t\t\t\t<td>{$nonstks['docref']}</td>\r\n\t\t\t\t<td>{$date}</td>\r\n\t\t\t\t<td>{$nonstks['cusname']}</td>\r\n\t\t\t\t<td align=right>{$cur} {$nonstks['total']}</td>\r\n\t\t\t\t<td>{$docs}</td>\r\n\t\t\t\t<td>{$chbox}</td>\r\n\t\t\t\t<td><a href='{$det}?invid={$nonstks['invid']}'>Details</a></td>";
        if ($nonstks['done'] != "y" && $nonstks["subtot"] == 0) {
            $printOrd .= "\r\n\t\t\t\t\t<td><a href='{$edit}?invid={$nonstks['invid']}&cont=1'>Edit</a></td>\r\n\t\t\t\t\t<td><a href='?key=delete_confirm&invid={$nonstks['invid']}'>Delete</a></td>\r\n\t\t\t\t</tr>";
        } elseif ($nonstks['done'] != "y") {
            $printOrd .= "\r\n\t\t\t\t\t<td><a href='{$edit}?invid={$nonstks['invid']}&cont=1'>Edit</a></td>\r\n\t\t\t\t\t<td><a href='?key=delete_confirm&invid={$nonstks['invid']}'>Delete</a></td>\r\n\t\t\t\t\t<td><a href=# onClick=printer('{$print}?invid={$nonstks['invid']}&type=nons')>Process</a></td>\r\n\t\t\t\t</tr>";
        } else {
            $cn = "";
            $printOrd .= "\r\n\t\t\t\t\t<td>{$cn}</td>\r\n\t\t\t\t\t<td><a target='_blank' href='{$reprint}?invid={$nonstks['invid']}&type=nonsreprint'>Reprint</a></td>\r\n\t\t\t\t\t<td><a href='pdf/{$reprpdf}?invid={$nonstks['invid']}&type=nonsreprint' target=_blank>Reprint in PDF</a></td>\r\n\t\t\t\t\t<td><input type=checkbox name='evs[{$nonstks['invid']}]'></td>\r\n\t\t\t\t</tr>";
        }
        $i++;
    }
    $tot_total = sprint($tot_total);
    $printOrd .= "\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td colspan='4'>Totals</td>\r\n\t\t\t\t<td align='right'>" . CUR . " {$tot_total}</td>\r\n\t\t\t\t<td colspan='4' align='right'><input type='submit' value='Process Selected' name='print'></td>\r\n\t\t\t\t<td colspan='3' align='right'><input type='submit' value='Email Selected' name='email'></td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t    <p>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t        <tr><td><br></td></tr>\r\n\t        <tr>\r\n\t        \t<th>Quick Links</th>\r\n\t        </tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='nons-invoice-new.php'>New Non-Stock Invoices</a></td>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\r\n\t\t\t</tr>\r\n\t\t</table>";
    return $printOrd;
}
function printNote($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $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.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "<br>";
        }
        return $confirm;
    }
    # Set up table to display in
    $printNote = "\n\t\t\t\t\t<h3>Non Stock Credit notes</h3>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Credit Note No.</th>\n\t\t\t\t\t\t\t<th>Invoice No.</th>\n\t\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t\t<th>Customer Name</th>\n\t\t\t\t\t\t\t<th>Grand Total</th>\n\t\t\t\t\t\t\t<th>Documents</th>\n\t\t\t\t\t\t\t<th colspan='3'>Options</th>\n\t\t\t\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot1 = 0;
    $sql = "SELECT * FROM nons_inv_notes WHERE date >= '{$fromdate}' AND date <= '{$todate}' AND div = '" . USER_DIV . "' ORDER BY noteid DESC";
    $noteRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($noteRslt) < 1) {
        $printNote = "<li>No previous credit notes.";
    } else {
        while ($note = pg_fetch_array($noteRslt)) {
            $note['total'] = sprint($note['total']);
            $tot1 = $tot1 + $note['total'];
            # Format date
            $note['date'] = explode("-", $note['date']);
            $note['date'] = $note['date'][2] . "-" . $note['date'][1] . "-" . $note['date'][0];
            $cur = CUR;
            if ($note['location'] == 'int') {
                $cur = $note['currency'];
            }
            # Get documents
            $docs = doclib_getdocs("note", $note['notenum']);
            $printNote .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>{$note['notenum']}</td>\n\t\t\t\t\t\t\t\t<td>{$note['invnum']}</td>\n\t\t\t\t\t\t\t\t<td align='center'>{$note['date']}</td>\n\t\t\t\t\t\t\t\t<td>{$note['cusname']}</td>\n\t\t\t\t\t\t\t\t<td align='right'>{$cur} {$note['total']}</td>\n\t\t\t\t\t\t\t\t<td>{$docs}</td>\n\t\t\t\t\t\t\t\t<td><a href='nons-invoice-note-det.php?noteid={$note['noteid']}'>Details</a></td>\n\t\t\t\t\t\t\t\t<td><a href='nons-invoice-note-reprint.php?noteid={$note['noteid']}' target=_blank>Reprint</a></td>\n\t\t\t\t\t\t\t</tr>";
            $i++;
        }
    }
    $tot1 = sprint($tot1);
    // Layout
    if ($tot1 > 0) {
        $printNote .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan='4'>Totals:{$i}</td>\n\t\t\t\t\t\t\t<td align='right'>{$cur} {$tot1}</td>\n\t\t\t\t\t\t\t<td align='right'></td>\n\t\t\t\t\t\t</tr>";
    }
    $printNote .= "\n\t\t\t\t\t</table>\n\t\t\t\t<p>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t</table>";
    return $printNote;
}
function printInv($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $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.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return $confirm;
    }
    $accnum = remval($accnum);
    if (strlen($accnum) > 0) {
        db_conn('cubit');
        $Sl = "SELECT * FROM customers WHERE lower(accno)=lower('{$accnum}')";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>Invalid account number</li>" . slct();
        }
        $cd = pg_fetch_array($Ri);
        $cusnum = $cd['cusnum'];
    }
    # Set up table to display in
    $printInv = "\n\t\t<h3>Paid Invoices</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Department</th>\n\t\t\t\t<th>Invoice No.</th>\n\t\t\t\t<th>Proforma Inv No.</th>\n\t\t\t\t<th>Invoice Date</th>\n\t\t\t\t<th>Customer Name</th>\n\t\t\t\t<th>Order No</th>\n\t\t\t\t<th>Customer Order No</th>\n\t\t\t\t<th>Grand Total</th>\n\t\t\t\t<th>Documents</th>\n\t\t\t\t<th colspan='5'>Options</th>\n\t\t\t</tr>";
    // Retrieve template setting
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        $repr = "invoice-reprint-prd.php";
    } else {
        $repr = $template;
    }
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='reprints'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "new") {
        $pdf_repr = "pdf/pdf-tax-invoice.php";
    } else {
        $pdf_repr = "pdf/invoice-pdf-reprint-prd.php";
    }
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    if (isset($all)) {
        # Connect to database
        db_connect();
        $queries = array();
        for ($i = 1; $i <= 12; $i++) {
            $schema = (int) $i;
            $queries[] = "SELECT *,'{$schema}' AS query_schema FROM \"{$schema}\".invoices WHERE done = 'y' AND odate >= '{$fromdate}' AND odate <= '{$todate}' AND div = '" . USER_DIV . "'";
        }
        $query = implode(" UNION ", $queries);
        $query .= " ORDER BY invid DESC";
    } else {
        # Connect to database
        db_connect();
        $queries = array();
        for ($i = 1; $i <= 12; $i++) {
            $schema = (int) $i;
            $queries[] = "SELECT *,'{$schema}' AS query_schema FROM \"{$schema}\".invoices WHERE done = 'y' AND cusnum = '{$cusnum}' AND odate >= '{$fromdate}' AND odate <= '{$todate}' AND div = '" . USER_DIV . "'";
        }
        $query = implode(" UNION ", $queries);
        $query .= " ORDER BY invid DESC";
    }
    $invRslt = db_exec($query) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($invRslt) < 1) {
        $printInv = "<li class='err'>No previous finished invoices found.</li>";
    } else {
        while ($inv = pg_fetch_array($invRslt)) {
            $prd = $inv["query_schema"];
            $inv['total'] = sprint($inv['total']);
            $inv['balance'] = sprint($inv['balance']);
            $tot1 = $tot1 + $inv['total'];
            $tot2 = $tot2 + $inv['balance'];
            # format date
            $inv['odate'] = explode("-", $inv['odate']);
            $inv['odate'] = $inv['odate'][2] . "-" . $inv['odate'][1] . "-" . $inv['odate'][0];
            # Get documents
            $docs = doclib_getdocs("inv", $inv['invnum']);
            $sp4 = "&nbsp;&nbsp;&nbsp;&nbsp;";
            $bcurr = CUR;
            $det = "invoice-details-prd.php";
            $reprint = "<td><a target=_blank href='{$repr}?type=invpaidreprint&invid={$inv['invid']}&prd={$prd}'>Reprint</a></td>";
            $note = "<td><a target=_blank href='invoice-note-prd.php?invid={$inv['invid']}&prd={$prd}'>Credit Note</a></td>";
            if ($inv['location'] == 'int') {
                $bcurr = $inv['currency'];
                $det = "intinvoice-details-prd.php";
                $reprint = "<td><a target='_blank' href='intinvoice-reprint-prd.php?invid={$inv['invid']}&prd={$prd}'>Reprint</a></td>";
                $note = "";
            }
            $delnote = "<td><a target='_blank' href='invoice-delnote-prd.php?invid={$inv['invid']}&prd={$prd}'>Delivery Note</a></td>";
            $printInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$inv['deptname']}</td>\n\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t<td>{$inv['docref']}</td>\n\t\t\t\t\t<td align='center'>{$inv['odate']}</td>\n\t\t\t\t\t<td>{$inv['cusname']} {$inv['surname']}</td>\n\t\t\t\t\t<td align='right'>{$inv['ordno']}</td>\n\t\t\t\t\t<td align='right'>{$inv['cordno']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$bcurr} {$inv['total']}</td>\n\t\t\t\t\t<td>{$docs}</td>\n\t\t\t\t\t<td><a href='{$det}?invid={$inv['invid']}&prd={$prd}'>Details</a></td>\n\t\t\t\t\t</td>{$reprint}</td>\n\t\t\t\t\t<td><a href='{$pdf_repr}?invid={$inv['invid']}&prd={$prd}&type=invpaidreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t\t{$note}\n\t\t\t\t\t{$delnote}\n\t\t\t\t</tr>";
            $i++;
        }
    }
    $tot1 = sprint($tot1);
    $tot2 = sprint($tot2);
    // Layout
    if ($tot1 > 0) {
        $printInv .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='7'>Totals:{$i}</td>\n\t\t\t\t<td align='right'>{$tot1}</td>\n\t\t\t\t<td align='right' colspan='6'></td>\n\t\t\t</tr>";
    }
    $printInv .= "\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='invoice-canc-view.php'>View Cancelled Invoices</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='invoice-unf-view.php'>View Incomplete Invoices</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='cust-credit-stockinv.php'>New Invoice</td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $printInv;
}
function printPurch($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    # mix dates
    $fromdate = $from_year . "-" . $from_month . "-" . $from_day;
    $todate = $to_year . "-" . $to_month . "-" . $to_day;
    $v->isOk($fromdate, "date", 1, 1, "Invalid From Date.");
    $v->isOk($todate, "date", 1, 1, "Invalid To Date.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return $confirm;
    }
    $check1 = "";
    $check2 = "";
    if (!isset($filter) or $filter == "summary") {
        $check1 = "checked='yes'";
    } else {
        $check2 = "checked='yes'";
    }
    $ocheck1 = "";
    $ocheck2 = "";
    if (!isset($order) or $order == "date") {
        $ocheck1 = "checked='yes'";
    } else {
        $ocheck2 = "checked='yes'";
    }
    # Set up table to display in
    $printOrd = "\n\t\t<center>\n\t\t<form action='" . SELF . "' method='POST' name='form1'>\n\t\t\t<input type='hidden' name='key' value='export'>\n\t\t\t<input type='hidden' name='fday' value='{$from_day}'>\n\t\t\t<input type='hidden' name='fmon' value='{$from_month}'>\n\t\t\t<input type='hidden' name='fyear' value='{$from_year}'>\n\t\t\t<input type='hidden' name='today' value='{$to_day}'>\n\t\t\t<input type='hidden' name='tomon' value='{$to_month}'>\n\t\t\t<input type='hidden' name='toyear' value='{$to_year}'>\n\n\t\t\t<input type='hidden' name='from_day' value='{$from_day}'>\n\t\t\t<input type='hidden' name='from_month' value='{$from_month}'>\n\t\t\t<input type='hidden' name='from_year' value='{$from_year}'>\n\t\t\t<input type='hidden' name='to_day' value='{$to_day}'>\n\t\t\t<input type='hidden' name='to_month' value='{$to_month}'>\n\t\t\t<input type='hidden' name='to_year' value='{$to_year}'>\n\n\t\t<h3>View Stock Orders</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Filter</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><input type='radio' name='filter' value='summary' {$check1} onClick=\"document.form1.submit();\"> Summary</td>\n\t\t\t\t<td><input type='radio' name='filter' value='detailed' {$check2} onClick=\"document.form1.submit();\"> Detailed</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<br>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Order</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><input type='radio' name='order' value='date' {$ocheck1} onClick=\"document.form1.submit();\"> Date</td>\n\t\t\t\t<td><input type='radio' name='order' value='numeric' {$ocheck2} onClick=\"document.form1.submit();\"> Numeric</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<br>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>No.</th>\n\t\t\t\t<th>Order No.</th>\n\t\t\t\t<th>Supp Inv No.</th>\n\t\t\t\t<th>Order Date</th>\n\t\t\t\t<th>Supplier</th>\n\t\t\t\t<th>Sub Total</th>\n\t\t\t\t<th>Delivery Charges</th>\n\t\t\t\t<th>Vat</th>\n\t\t\t\t<th>Total</th>\n\t\t\t\t<th>Documents</th>\n\t\t\t\t<th colspan='8'>Options</th>\n\t\t\t</tr>";
    # connect to database
    db_connect();
    $supsql = "";
    if (isset($supplier) and $supplier != 0) {
        $supsql = " AND supid = '{$supplier}'";
    }
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    $tot3 = 0;
    $tot4 = 0;
    if (isset($order) and $order == "numeric") {
        $orderby = "purnum::integer";
    } else {
        $orderby = "pdate";
    }
    $sql = "SELECT * FROM purchases WHERE pdate >= '{$fromdate}' AND pdate <= '{$todate}' AND div = '" . USER_DIV . "' {$supsql} ORDER BY {$orderby} DESC";
    $stkpRslt = db_exec($sql) or errDie("Unable to retrieve stock purchases from database.");
    if (pg_numrows($stkpRslt) < 1) {
        return "\n\t\t\t<li class='err'> No Stock Orders Could be Found.</li><br>" . mkQuickLinks(ql("purchase-new.php", "New Order"), ql("stock-view.php", "View Stock"));
    } else {
        while ($stkp = pg_fetch_array($stkpRslt)) {
            # Date format
            $date = explode("-", $stkp['pdate']);
            $date = $date[2] . "-" . $date[1] . "-" . $date[0];
            # Calculate the Sub-Total
            $stkp['total'] = sprint($stkp['total']);
            $stkp['shipchrg'] = sprint($stkp['shipping']);
            $subtot = $stkp['subtot'];
            $subtot = sprint($subtot);
            $vat = sprint($stkp['vat']);
            $tot1 = sprint($tot1 + $subtot);
            $tot2 = sprint($tot2 + $stkp['shipchrg']);
            $tot3 = sprint($tot3 + $stkp['total']);
            $tot4 = sprint($tot4 + $vat);
            # Get documents
            $docs = doclib_getdocs("pur", $stkp['purnum']);
            # Alternate bgcolor
            $printOrd .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$stkp['purnum']}</td>\n\t\t\t\t\t<td>{$stkp['ordernum']}</td>\n\t\t\t\t\t<td>{$stkp['supinv']}</td>\n\t\t\t\t\t<td>{$date}</td>\n\t\t\t\t\t<td>{$stkp['supname']}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$subtot}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$stkp['shipchrg']}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$vat}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$stkp['total']}</td>\n\t\t\t\t\t<td>{$docs}</td>\n\t\t\t\t\t<td><a href='purch-det.php?purid={$stkp['purid']}'>Details</a></td>\n\t\t\t\t\t<td><a href='purch-cancel.php?purid={$stkp['purid']}'>Delete</td>\n\t\t\t\t\t<td><a href='javascript: printer(\"purch-print.php?purid={$stkp['purid']}\");'>Print</a></td>";
            $edit = "purchase-new.php";
            $recv = "purch-recv.php";
            $complt = "<a href='purch-complete.php?purid={$stkp['purid']}'>Complete</a>";
            $recinv = "<a href='purch-recinvcd.php?purid={$stkp['purid']}'>Record Invoice</a>";
            if ($stkp['invcd'] == 'y') {
                $recinv = "Invoice Recorded";
            }
            if ($stkp['cash'] == 'y') {
                $edit = "purchase-new-cash.php";
                $recv = "purch-recv-cash.php";
                $complt = "<br>";
                $recinv = "";
            }
            //			<td><input type='checkbox' name='email_sel[$stkp[purid]]' value='$stkp[supid]'></td>
            if ($stkp['received'] != "y" && $subtot == 0) {
                $printOrd .= "\n\t\t\t\t\t\t<td><a href='{$edit}?purid={$stkp['purid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t\t<td>&nbsp</td>\n\t\t\t\t\t\t<td><a href='purch-cancel.php?purid={$stkp['purid']}'>Cancel</a></td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t</tr>";
            } elseif ($stkp['received'] != "y") {
                if ($stkp['edit'] != 1 && $stkp['apprv'] != 'y' && $stkp['invcd'] != 'y') {
                    $printOrd .= "\n\t\t\t\t\t\t\t<td><a href='{$edit}?purid={$stkp['purid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t\t\t<td><a href='purch-apprv.php?purid={$stkp['purid']}'>Approve</a></td>\n\t\t\t\t\t\t\t<td><a href='purch-cancel.php?purid={$stkp['purid']}'>Cancel</a></td>\n\t\t\t\t\t\t</tr>";
                } elseif ($stkp['edit'] != 1 && $stkp['apprv'] == 'y') {
                    if (getSetting("PURCH_APPRV") == 'napprv' && $stkp['invcd'] != 'y') {
                        $printOrd .= "\n\t\t\t\t\t\t<td><a href='{$edit}?purid={$stkp['purid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t\t<td><a href='purch-cancel.php?purid={$stkp['purid']}'>Cancel</a></td>";
                    } else {
                        $printOrd .= "<td> <a href='{$edit}?purid={$stkp['purid']}&cont=1'>Edit</a></td>";
                    }
                    if ($stkp['rsubtot'] > 0) {
                        $rec = "";
                    } elseif ($stkp['iamount'] > 0) {
                        $rec = "";
                    } else {
                        $rec = "<a href='{$recv}?purid={$stkp['purid']}&invoice=no'>Receive & Record Invoice</a>";
                    }
                    $printOrd .= "\n\t\t\t\t\t\t\t<td><a href='{$recv}?purid={$stkp['purid']}'>Received</a></td>\n\t\t\t\t\t\t\t<td>{$recinv}</td>\n\t\t\t\t\t\t\t<td>{$rec}</td>\n\t\t\t\t\t\t</tr>";
                } else {
                    $printOrd .= "\n\t\t\t\t\t\t\t<td><a href='{$recv}?purid={$stkp['purid']}'>Received</a></td>\n\t\t\t\t\t\t\t<td>{$recinv}</td>\n\t\t\t\t\t\t\t<td>{$complt}</td>\n\t\t\t\t\t\t</tr>";
                }
            } else {
                if ($stkp['invcd'] != 'y') {
                    $printOrd .= "<td colspan='3'>{$recinv}</td></tr>";
                } else {
                    $printOrd .= "<td colspan='3'><br></td></tr>";
                }
            }
            db_connect();
            if (isset($filter) and $filter == "detailed") {
                $stockcodes = array();
                $get_codes = "SELECT * FROM suppstock WHERE suppid = '{$stkp['supid']}' ORDER BY stkid";
                $run_codes = db_exec($get_codes) or errDie("Unable to get supplier stock code information");
                if (pg_numrows($run_codes) > 0) {
                    while ($codarr = pg_fetch_array($run_codes)) {
                        if (strlen($codarr['stkcod']) > 0) {
                            $stockcodes[$codarr['stkid']]['stkcod'] = $codarr['stkcod'];
                        }
                        if (strlen($codarr['stkdes']) > 0) {
                            $stockcodes[$codarr['stkid']]['stkdes'] = $codarr['stkdes'];
                        }
                    }
                }
                $get_items = "SELECT * FROM pur_items WHERE purid = '{$stkp['purid']}'";
                $run_items = db_exec($get_items) or errDie("Unable to get stock items information.");
                if (pg_numrows($run_items) > 0) {
                    $printOrd .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<th colspan='4'></th>\n\t\t\t\t\t\t\t<th>Code</th>\n\t\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t\t<th>Quantity</th>\n\t\t\t\t\t\t\t<th>Unit Cost</th>\n\t\t\t\t\t\t\t<th>Total</th>\n\t\t\t\t\t\t</tr>";
                    while ($piarr = pg_fetch_array($run_items)) {
                        $get_stock = "SELECT * FROM stock WHERE stkid = '{$piarr['stkid']}' LIMIT 1";
                        $run_stock = db_exec($get_stock) or errDie("Unable to get stock informarion.");
                        if (pg_numrows($run_stock) > 0) {
                            $stk = pg_fetch_array($run_stock);
                            if (isset($stockcodes[$stk['stkid']]['stkcod'])) {
                                $stk['stkcod'] = $stockcodes[$stk['stkid']]['stkcod'];
                            }
                            if (isset($stockcodes[$stk['stkid']]['stkdes'])) {
                                $stk['stkdes'] = $stockcodes[$stk['stkid']]['stkdes'];
                            }
                        }
                        $printOrd .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td colspan='4'></td>\n\t\t\t\t\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t\t\t\t<td>{$piarr['qty']}</td>\n\t\t\t\t\t\t\t\t<td>{$piarr['unitcost']}</td>\n\t\t\t\t\t\t\t\t<td>{$piarr['amt']}</td>\n\t\t\t\t\t\t\t</tr>";
                    }
                    $printOrd .= "\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>No.</th>\n\t\t\t\t\t\t\t<th>Order No.</th>\n\t\t\t\t\t\t\t<th>Supp Inv No.</th>\n\t\t\t\t\t\t\t<th>Order Date</th>\n\t\t\t\t\t\t\t<th>Supplier</th>\n\t\t\t\t\t\t\t<th>Sub Total</th>\n\t\t\t\t\t\t\t<th>Delivery Charges</th>\n\t\t\t\t\t\t\t<th>Vat</th>\n\t\t\t\t\t\t\t<th>Total</th>\n\t\t\t\t\t\t</tr>";
                }
            }
            $i++;
        }
    }
    $printOrd .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='5'>Totals</td>\n\t\t\t\t<td align='right' nowrap='t'>" . CUR . " {$tot1}</td>\n\t\t\t\t<td align='right' nowrap='t'>" . CUR . " {$tot2}</td>\n\t\t\t\t<td align='right' nowrap='t'>" . CUR . " {$tot4}</td>\n\t\t\t\t<td align='right' nowrap='t'>" . CUR . " {$tot3}</td>\n\t\t\t\t<td colspan='8'>&nbsp</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='17' align='right'><input type='submit' name='export' value='Export to Spreadsheet'></td>\n\t\t\t</tr>\n\t\t</table>" . mkQuickLinks(ql("purchase-new.php", "New Order"), ql("stock-view.php", "View Stock"));
    return $printOrd;
}
function printNote($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $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.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li>";
        }
        return $confirm;
    }
    # Set up table to display in
    $printNote = "\n\t\t<h3>Credit notes</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Department</th>\n\t\t\t\t<th>Sales Person</th>\n\t\t\t\t<th>Credit Note No.</th>\n\t\t\t\t<th>Invoice No.</th>\n\t\t\t\t<th>Invoice Date</th>\n\t\t\t\t<th>Customer Name</th>\n\t\t\t\t<th>Order No</th>\n\t\t\t\t<th>Grand Total</th>\n\t\t\t\t<th>Documents</th>\n\t\t\t\t<th colspan='3'>Options</th>\n\t\t\t</tr>";
    # Connect to database
    db_connect();
    $month = (int) $from_month;
    $yearcheck = $from_year;
    $date_arr = array();
    $flag = TRUE;
    while ($flag) {
        if ($month == 13) {
            $month = 1;
            $yearcheck++;
        }
        #add month to array
        $date_arr[] = $month;
        if ($month == $to_month && $yearcheck == $to_year) {
            $flag = FALSE;
        }
        $month++;
    }
    $date_arr = array_unique($date_arr);
    $queries = array();
    #	this is no good ... to_month CAN be less than from_month
    #	for ($i = $from_month; $i <= $to_month; $i++) {
    foreach ($date_arr as $i) {
        $schema = (int) $i;
        $queries[] = "SELECT *,'{$schema}' AS query_schema FROM \"{$schema}\".inv_notes WHERE odate >= '{$fromdate}' AND odate <= '{$todate}' AND div = '" . USER_DIV . "'";
    }
    $query = implode(" UNION ", $queries);
    $query .= " ORDER BY noteid DESC";
    # Query server
    $i = 0;
    $tot1 = 0;
    $sql = " ORDER BY noteid DESC";
    $noteRslt = db_exec($query) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($noteRslt) < 1) {
        $printNote = "<li class='err'>No previous credit notes found.</li>";
    } else {
        while ($note = pg_fetch_array($noteRslt)) {
            $prd = $note["query_schema"];
            $note['total'] = sprint($note['total']);
            $tot1 = $tot1 + $note['total'];
            # Format date
            $note['odate'] = explode("-", $note['odate']);
            $note['odate'] = $note['odate'][2] . "-" . $note['odate'][1] . "-" . $note['odate'][0];
            # Get documents
            $docs = doclib_getdocs("note", $note['notenum']);
            $rep = "invoice-note-reprint.php";
            $curr = CUR;
            if ($note['location'] == 'int') {
                $rep = "intinvoice-note-reprint.php";
                $curr = $note['currency'];
            }
            $printNote .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$note['deptname']}</td>\n\t\t\t\t\t<td>{$note['salespn']}</td>\n\t\t\t\t\t<td>{$note['notenum']}</td>\n\t\t\t\t\t<td>{$note['invnum']}</td>\n\t\t\t\t\t<td align='center'>{$note['odate']}</td>\n\t\t\t\t\t<td>{$note['surname']}</td>\n\t\t\t\t\t<td align='right'>{$note['ordno']}</td>\n\t\t\t\t\t<td align='right'>{$curr} {$note['total']}</td>\n\t\t\t\t\t<td>{$docs}</td>\n\t\t\t\t\t<td><a href='{$rep}?noteid={$note['noteid']}&prd={$prd}&reprint=yes' target='_blank'>Details</a></td>\n\t\t\t\t</tr>";
            $i++;
        }
    }
    $tot1 = sprint($tot1);
    // Layout
    if ($tot1 > 0) {
        $printNote .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='7'>Totals:{$i}</td>\n\t\t\t\t<td align='right'>" . CUR . " {$tot1}</td>\n\t\t\t\t<td colspan='2'>&nbsp;</td>\n\t\t\t</tr>";
    }
    $printNote .= "\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $printNote;
}
function printPurch($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $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.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>-" . $e["msg"] . "<br>";
        }
        return $confirm;
    }
    # Set up table to display in
    $printOrd = "<center>\r\n\t<h3>Received Non-Stock Orders</h3>\r\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t<tr><th>Purchase No.</th><th>Purchase Date</th><th>Supplier</th><th>Sub Total</th><th>Delivery Charges</th><th>Vat</th><th>Total</th><th>Delevery Reference No.</th><th>Documents</th><th colspan=5>Options</th></tr>";
    # connect to database
    db_conn($prd);
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    $tot3 = 0;
    $tot4 = 0;
    $sql = "SELECT * FROM nons_purchases WHERE pdate >= '{$fromdate}' AND pdate <= '{$todate}' AND done = 'y' AND div = '" . USER_DIV . "' ORDER BY pdate DESC";
    $stkpRslt = db_exec($sql) or errDie("Unable to retrieve stock Non-Stock Orders from database.");
    if (pg_numrows($stkpRslt) < 1) {
        return "<li> There are no stock Non-Stock Orders found.\r\n\t\t<p>\r\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n\t\t\t<tr><td><br></td></tr>\r\n\t\t\t<tr><th>Quick Links</th></tr>\r\n\t\t\t<tr class='bg-odd'><td><a href='nons-purchase-new.php'>New Non-Stock Order</a></td></tr>\r\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t<tr class='bg-odd'><td><a href='stock-report.php'>Stock Control Reports</a></td></tr>\r\n\t\t\t<tr class='bg-even'><td><a href='stock-view.php'>View Stock</a></td></tr>\r\n\t\t\t<tr class='bg-odd'><td><a href='main.php'>Main Menu</a></td></tr>\r\n\t\t</table>";
    }
    while ($stkp = pg_fetch_array($stkpRslt)) {
        # date format
        $date = explode("-", $stkp['pdate']);
        $date = $date[2] . "-" . $date[1] . "-" . $date[0];
        # calculate the Sub-Total
        $stkp['total'] = sprint($stkp['total']);
        $stkp['shipchrg'] = sprint($stkp['shipping']);
        $subtot = $stkp['subtot'];
        $subtot = sprint($subtot);
        $tot1 = sprint($tot1 + $subtot);
        $tot2 = sprint($tot2 + $stkp['shipchrg']);
        $tot3 = sprint($tot3 + $stkp['total']);
        $vat = $stkp['vat'];
        $tot4 = sprint($tot4 + $vat);
        # Get documents
        $docs = doclib_getdocs("npur", $stkp['purnum']);
        $printOrd .= "<tr class='" . bg_class() . "'><td>{$stkp['purnum']}</td><td>{$date}</td><td>{$stkp['supplier']}</td><td align=right>" . CUR . " {$subtot}</td><td align=right>" . CUR . " {$stkp['shipchrg']}</td><td align=right>" . CUR . " {$vat}</td><td align=right>" . CUR . " {$stkp['total']}</td><td>{$stkp['refno']}</td><td>{$docs}</td>";
        if ($stkp['returned'] != 'y') {
            $printOrd .= "<td><a href='nons-purch-return.php?purid={$stkp['purid']}&prd={$prd}'>Return</a></td><td><a href='nons-purch-det-prd.php?purid={$stkp['purid']}&prd={$prd}'>Details</a></td></tr>";
        } else {
            $printOrd .= "<td><br></td><td><a href='nons-purch-det-prd.php?purid={$stkp['purid']}&prd={$prd}'>Details</a></td></tr>";
        }
        $i++;
    }
    $printOrd .= "<tr class='" . bg_class() . "'><td colspan=3>Totals</td><td align=right>" . CUR . " {$tot1}</td><td align=right>" . CUR . " {$tot2}</td><td align=right>" . CUR . " {$tot4}</td><td align=right>" . CUR . " {$tot3}</td></tr>\r\n\t</table>\r\n    <p>\r\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\r\n        <tr><td><br></td></tr>\r\n        <tr><th>Quick Links</th></tr>\r\n\t\t<tr class='bg-odd'><td><a href='nons-purchase-new.php'>New Non-Stock Order</a></td></tr>\r\n\t\t<tr class='bg-odd'><td><a href='main.php'>Main Menu</a></td></tr>\r\n\t</table>";
    return $printOrd;
}
function printPurch($_POST, $pure = false)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $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.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "<br>";
        }
        return $confirm;
    }
    require_lib("docman");
    # Set up table to display in
    $printOrd = "";
    if (!$pure) {
        $printOrd = "\n\t\t<center>\n\t\t<h3>View Non-Stock Orders</h3>";
    }
    $printOrd .= "\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Purchase No.</th>\n\t\t\t\t\t\t\t<th>Supplier Inv</th>\n\t\t\t\t\t\t\t<th>Purchase Date</th>\n\t\t\t\t\t\t\t<th>Supplier</th>\n\t\t\t\t\t\t\t<th>Sub Total</th>\n\t\t\t\t\t\t\t<th>Delivery Charges</th>\n\t\t\t\t\t\t\t<th>Vat</th><th>Total</th>\n\t\t\t\t\t\t\t<th>Documents</th>\n\t\t\t\t\t\t\t<th colspan='5'>Options</th>\n\t\t\t\t\t\t</tr>";
    # connect to database
    db_connect();
    $Sl = "SELECT supid,supname FROM suppliers";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    while ($data = pg_fetch_array($Ri)) {
        $sn[$data['supid']] = $data['supname'];
    }
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    $tot3 = 0;
    $tot4 = 0;
    $sql = "SELECT * FROM nons_purchases WHERE pdate >= '{$fromdate}' AND pdate <= '{$todate}' AND div = '" . USER_DIV . "' ORDER BY pdate DESC";
    $stkpRslt = db_exec($sql) or errDie("Unable to retrieve Orders from database.");
    if (pg_numrows($stkpRslt) < 1) {
        return "<li class='err'> No Non Stock Purchases Could Be Found For The Selected Period.</li>";
    }
    while ($stkp = pg_fetch_array($stkpRslt)) {
        # date format
        $date = explode("-", $stkp['pdate']);
        $date = $date[2] . "-" . $date[1] . "-" . $date[0];
        # calculate the Sub-Total
        $stkp['total'] = sprint($stkp['total']);
        $stkp['shipchrg'] = sprint($stkp['shipping']);
        $subtot = $stkp['subtot'];
        $subtot = sprint($subtot);
        $vat = sprint($stkp['vat']);
        $tot1 = sprint($tot1 + $subtot);
        $tot2 = sprint($tot2 + $stkp['shipchrg']);
        $tot3 = sprint($tot3 + $stkp['total']);
        $tot4 = sprint($tot4 + $vat);
        # Get documents
        $docs = doclib_getdocs("npur", $stkp['purnum']);
        $edit = "nons-purchase-new.php";
        $det = "nons-purch-det.php";
        $recv = "nons-purch-recv.php";
        if ($stkp['spurnum'] > 0) {
            $edit = "lnons-purch-new.php";
            $det = "lnons-purch-det.php";
            $recv = "lnons-purch-recv.php";
        }
        if ($stkp['assid'] > 0) {
            $edit = "nonsa-purchase-new.php";
            $det = "nonsa-purch-det.php";
            $recv = "nonsa-purch-recv.php";
        }
        if ($stkp['ctyp'] == "s" && isset($sn[$stkp['supplier']])) {
            $stkp['supplier'] = $sn[$stkp['supplier']];
        }
        $printOrd .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$stkp['purnum']}</td>\n\t\t\t\t\t<td>{$stkp['supinv']}</td>\n\t\t\t\t\t<td>{$date}</td>\n\t\t\t\t\t<td>{$stkp['supplier']}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$subtot}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$stkp['shipchrg']}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$vat}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$stkp['total']}</td>\n\t\t\t\t\t<td>{$docs}</td>\n\t\t\t\t\t<td><a href='{$det}?purid={$stkp['purid']}'>Details</a></td>\n\t\t\t\t\t<td><a href='javascript: printer(\"nons-purch-print.php?purid={$stkp['purid']}\");'>Print</a></td>";
        if ($stkp['received'] != "y" && $subtot == 0) {
            $printOrd .= "\n\t\t\t\t\t<td><a href='{$edit}?purid={$stkp['purid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td><a href='nons-purch-cancel.php?purid={$stkp['purid']}'>Cancel</a></td>\n\t\t\t\t</tr>";
        } elseif ($stkp['received'] != "y") {
            $printOrd .= "\n\t\t\t\t\t<td><a href='{$edit}?purid={$stkp['purid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t<td><a href='{$recv}?purid={$stkp['purid']}'>Received</a></td>\n\t\t\t\t\t<td><a href='nons-purch-cancel.php?purid={$stkp['purid']}'>Cancel</a></td>\n\t\t\t\t</tr>";
        } else {
            $printOrd .= "\n\t\t\t\t\t<td colspan='3'><br></td>\n\t\t\t\t</tr>";
        }
        $i++;
    }
    $printOrd .= "\n\t<tr class='" . bg_class() . "'>\n\t\t<td colspan='4'>Totals</td>\n\t\t<td align='right'>" . CUR . " {$tot1}</td>\n\t\t<td align='right'>" . CUR . " {$tot2}</td>\n\t\t<td align='right'>" . CUR . " {$tot4}</td>\n\t\t<td align='right'>" . CUR . " {$tot3}</td>\n\t</tr>";
    if (!$pure) {
        $printOrd .= "\n\t\t" . TBL_BR . "\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='export'>\n\t\t\t<input type='hidden' name='from_day' value='{$from_day}'>\n\t\t\t<input type='hidden' name='from_month' value='{$from_month}'>\n\t\t\t<input type='hidden' name='from_year' value='{$from_year}'>\n\t\t\t<input type='hidden' name='to_day' value='{$to_day}'>\n\t\t\t<input type='hidden' name='to_month' value='{$to_month}'>\n\t\t\t<input type='hidden' name='to_year' value='{$to_year}'>\n\t\t\t<tr>\n\t\t\t\t<td colspan='4'><input type='submit' value='Export to Spreadsheet'></td>\n\t\t\t</tr>\n\t\t</form>";
    }
    $printOrd .= "\n\t</table>";
    return $printOrd;
}
function printPurch($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $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.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>-" . $e["msg"] . "<br>";
        }
        return $confirm;
    }
    # Set up table to display in
    $printOrd = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h3>Received Non-Stock Orders</h3>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Purchase No.</th>\n\t\t\t\t\t\t<th>Purchase Date</th>\n\t\t\t\t\t\t<th>Supplier</th>\n\t\t\t\t\t\t<th>Sub Total</th>\n\t\t\t\t\t\t<th>Delivery Charges</th>\n\t\t\t\t\t\t<th>Vat</th>\n\t\t\t\t\t\t<th>Total</th>\n\t\t\t\t\t\t<th>Delivery Reference No.</th>\n\t\t\t\t\t\t<th>Documents</th>\n\t\t\t\t\t\t<th colspan='5'>Options</th>\n\t\t\t\t\t</tr>";
    # Connect to database
    db_connect();
    $queries = array();
    for ($i = 1; $i <= 12; $i++) {
        $schema = (int) $i;
        $queries[] = "SELECT *,'{$schema}' AS query_schema FROM \"{$schema}\".nons_purchases WHERE pdate >= '{$fromdate}' AND pdate <= '{$todate}' AND done = 'y' AND div = '" . USER_DIV . "'";
    }
    $query = implode(" UNION ", $queries);
    $query .= " ORDER BY pdate DESC";
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    $tot3 = 0;
    $tot4 = 0;
    $stkpRslt = db_exec($query) or errDie("Unable to retrieve stock Non-Stock Orders from database.");
    if (pg_numrows($stkpRslt) < 1) {
        return "\n\t\t\t\t\t<li class='err'> No Non-Stock Orders found.</li>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='nons-purchase-new.php'>New Non-Stock Order</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='stock-report.php'>Stock Control Reports</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='stock-view.php'>View Stock</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t</table>";
    }
    while ($stkp = pg_fetch_array($stkpRslt)) {
        $prd = $stkp["query_schema"];
        # date format
        $date = explode("-", $stkp['pdate']);
        $date = $date[2] . "-" . $date[1] . "-" . $date[0];
        # calculate the Sub-Total
        $stkp['total'] = sprint($stkp['total']);
        $stkp['shipchrg'] = sprint($stkp['shipping']);
        $subtot = $stkp['subtot'];
        $subtot = sprint($subtot);
        $tot1 = sprint($tot1 + $subtot);
        $tot2 = sprint($tot2 + $stkp['shipchrg']);
        $tot3 = sprint($tot3 + $stkp['total']);
        $vat = $stkp['vat'];
        $tot4 = sprint($tot4 + $vat);
        # Get documents
        $docs = doclib_getdocs("npur", $stkp['purnum']);
        $printOrd .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>{$stkp['purnum']}</td>\n\t\t\t\t\t\t\t<td>{$date}</td>\n\t\t\t\t\t\t\t<td>{$stkp['supplier']}</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$subtot}</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$stkp['shipchrg']}</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$vat}</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$stkp['total']}</td>\n\t\t\t\t\t\t\t<td>{$stkp['refno']}</td>\n\t\t\t\t\t\t\t<td>{$docs}</td>";
        if ($stkp['returned'] != 'y' and $stkp['is_asset'] != "yes") {
            $printOrd .= "\n\t\t\t\t\t\t\t<td><a href='nons-purch-return.php?purid={$stkp['purid']}&prd={$prd}'>Return</a></td>\n\t\t\t\t\t\t\t<td><a href='nons-purch-det-prd.php?purid={$stkp['purid']}&prd={$prd}'>Details</a></td>\n\t\t\t\t\t\t\t<td><a target='_blank' href='nons-purch-recv-print.php?purid={$stkp['purid']}&prd={$prd}'>Print</a></td>\n\t\t\t\t\t\t</tr>";
        } else {
            $printOrd .= "\n\t\t\t\t\t\t\t<td><br></td>\n\t\t\t\t\t\t\t<td><a href='nons-purch-det-prd.php?purid={$stkp['purid']}&prd={$prd}'>Details</a></td>\n\t\t\t\t\t\t</tr>";
        }
        $i++;
    }
    $printOrd .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan=3>Totals</td>\n\t\t\t\t\t\t\t<td align=right>" . CUR . " {$tot1}</td>\n\t\t\t\t\t\t\t<td align=right>" . CUR . " {$tot2}</td>\n\t\t\t\t\t\t\t<td align=right>" . CUR . " {$tot4}</td>\n\t\t\t\t\t\t\t<td align=right>" . CUR . " {$tot3}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t\t\t<input type='hidden' name='key' value='export'>\n\t\t\t\t\t\t<input type='hidden' name='prd' value='{$prd}'>\n\t\t\t\t\t\t<input type='hidden' name='fday' value='{$from_day}'>\n\t\t\t\t\t\t<input type='hidden' name='fmon' value='{$from_month}'>\n\t\t\t\t\t\t<input type='hidden' name='fyear' value='{$from_year}'>\n\t\t\t\t\t\t<input type='hidden' name='today' value='{$to_day}'>\n\t\t\t\t\t\t<input type='hidden' name='tomon' value='{$to_month}'>\n\t\t\t\t\t\t<input type='hidden' name='toyear' value='{$to_year}'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='4'><input type=submit value='Export to Spreadsheet'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t    <p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t        <tr><td><br></td></tr>\n\t\t\t\t        <tr>\n\t\t\t\t        \t<th>Quick Links</th>\n\t\t\t\t        </tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='nons-purchase-new.php'>New Non-Stock Order</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>";
    return $printOrd;
}
function printPurch($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $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.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li>";
        }
        return $confirm;
    }
    # Set up table to display in
    $printOrd = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h3>View International Non-Stock Orders</h3>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Purchase No.</th>\n\t\t\t\t\t\t\t<th>Purchase Date</th>\n\t\t\t\t\t\t\t<th>Supplier</th>\n\t\t\t\t\t\t\t<th>Sub Total</th>\n\t\t\t\t\t\t\t<th>Delivery Charges</th>\n\t\t\t\t\t\t\t<th>Vat</th>\n\t\t\t\t\t\t\t<th>Total</th>\n\t\t\t\t\t\t\t<th>Documents</th>\n\t\t\t\t\t\t\t<th colspan='5'>Options</th>\n\t\t\t\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    $tot3 = 0;
    $tot4 = 0;
    $sql = "SELECT * FROM nons_purch_int WHERE pdate >= '{$fromdate}' AND pdate <= '{$todate}' AND div = '" . USER_DIV . "' ORDER BY pdate DESC";
    $stkpRslt = db_exec($sql) or errDie("Unable to retrieve Orders from database.");
    if (pg_numrows($stkpRslt) < 1) {
        return "\n\t\t\t\t\t<li> There are no Orders found.</li><p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='nons-purch-int-new.php'>New International Non-Stock Orders</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t</table>";
    }
    while ($stkp = pg_fetch_array($stkpRslt)) {
        # date format
        $date = explode("-", $stkp['pdate']);
        $date = $date[2] . "-" . $date[1] . "-" . $date[0];
        # Get documents
        $docs = doclib_getdocs("npur", $stkp['purnum']);
        $edit = "nons-purch-int-new.php";
        $det = "nons-purch-int-print.php";
        $recv = "nons-purch-int-recv.php";
        $printOrd .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>{$stkp['purnum']}</td>\n\t\t\t\t\t\t\t\t<td>{$date}</td>\n\t\t\t\t\t\t\t\t<td>{$stkp['supplier']}</td>\n\t\t\t\t\t\t\t\t<td align='right'>{$stkp['curr']} {$stkp['subtot']}</td>\n\t\t\t\t\t\t\t\t<td align='right'>{$stkp['curr']} {$stkp['shipchrg']}</td>\n\t\t\t\t\t\t\t\t<td align='right'>{$stkp['curr']} {$stkp['tax']}</td>\n\t\t\t\t\t\t\t\t<td align='right'>{$stkp['curr']} {$stkp['total']}</td><td>{$docs}</td>\n\t\t\t\t\t\t\t\t<td><a href='{$det}?purid={$stkp['purid']}'>Details</a></td>\n\t\t\t\t\t\t\t\t<td><a target='_blank' href='{$det}?purid={$stkp['purid']}'>Print</a></td>";
        if ($stkp['received'] != "y" && $stkp['subtot'] == 0) {
            $printOrd .= "\n\t\t\t\t\t\t\t\t<td><a href='{$edit}?purid={$stkp['purid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t\t\t\t<td><a href='nons-purch-int-cancel.php?purid={$stkp['purid']}'>Cancel</a></td>\n\t\t\t\t\t\t\t</tr>";
        } elseif ($stkp['received'] != "y") {
            $printOrd .= "\n\t\t\t\t\t\t\t\t<td><a href='{$edit}?purid={$stkp['purid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t\t\t\t<td><a href='{$recv}?purid={$stkp['purid']}'>Received</a></td>\n\t\t\t\t\t\t\t\t<td><a href='nons-purch-int-cancel.php?purid={$stkp['purid']}'>Cancel</a></td>\n\t\t\t\t\t\t\t</tr>";
        } else {
            $printOrd .= "\n\t\t\t\t\t\t\t\t<td colspan='3'><br></td>\n\t\t\t\t\t\t\t</tr>";
        }
        $i++;
    }
    $printOrd .= "\n\t\t\t\t\t\t</table>\n\t\t\t\t\t    <p>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t        <tr><td><br></td></tr>\n\t\t\t\t\t        <tr>\n\t\t\t\t\t        \t<th>Quick Links</th>\n\t\t\t\t\t        </tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><a href='nons-purch-int-new.php'>New International Non-Stock Order</a></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</table>";
    return $printOrd;
}
function printInvoice($_POST)
{
    extract($_POST);
    require_lib("validate");
    $v = new validate();
    $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.");
    $fromdate = mkdate($from_year, $from_month, $from_day);
    $todate = mkdate($to_year, $to_month, $to_day);
    $v->isOk($fromdate, "date", 1, 1, "Invalid from date.");
    $v->isOk($todate, "date", 1, 1, "Invalid to date.");
    if ($v->isError()) {
        $err = $v->genErrors();
        return $err;
    }
    # Set up table to display in
    $printOrd = "\n\t\t<center>\n\t\t<h3>View Non-Stock Invoices</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<form action='invoice-proc.php' method='POST'>\n\t\t\t<input type='hidden' name='t' value='i'>\n\t\t\t<tr>\n\t\t\t\t<th>Invoice Num</th>\n\t\t\t\t<th>Proforma Inv No.</th>\n\t\t\t\t<th>Invoice Date</th>\n\t\t\t\t<th>Customer</th>\n\t\t\t\t<th>Total</th>\n\t\t\t\t<th>Documents</th>\n\t\t\t\t<th colspan=6>Options</th>\n\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot_subtot = 0;
    $tot_total = 0;
    $cust_search = "";
    if (isset($customer) and $customer != "0") {
        $cust_search = "AND cusname = '{$customer}'";
    }
    $sql = "SELECT * FROM nons_invoices WHERE typ = 'inv' AND sdate >= '{$fromdate}' \tAND sdate <= '{$todate}' AND div = '" . USER_DIV . "' AND balance > 0 {$cust_search} ORDER BY invnum";
    $nonstksRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($nonstksRslt) < 1) {
        return "\n\t\t\t<li class='err'> No Non Stock Invoices Could Be Found.</li>\n\t\t\t<p>\n\t\t\t<table border='0' cellpadding='2' cellspacing='1'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='nons-invoice-new.php'>New Non Stock Invoice</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='nons-invoice-view.php'>View Non Stock Invoices</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    // Retrieve the PDF reprints
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='reprints' AND div='" . USER_DIV . "'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    while ($nonstks = pg_fetch_array($nonstksRslt)) {
        // compute the totals
        if ($nonstks["xrate"] == 0.0) {
            $tot_subtot += $nonstks["subtot"];
            $tot_total += $nonstks["total"];
        } else {
            $tot_subtot += $nonstks["subtot"] * $nonstks["xrate"];
            $tot_total += $nonstks["total"] * $nonstks["xrate"];
        }
        # calculate the Sub-Total
        if ($nonstks['invnum'] == 0) {
            $nonstks['invnum'] = $nonstks['invid'];
        }
        $det = "nons-invoice-det.php";
        $edit = "nons-invoice-new.php";
        $print = "nons-invoice-print.php";
        $reprint = "nons-invoice-reprint.php";
        $note = "nons-invoice-note.php";
        if ($template == "default") {
            $template = "nons-invoice-pdf-reprint.php";
        } elseif ($template == "new") {
            $template = "pdf-tax-invoice.php";
        }
        $reprpdf = $template;
        $cur = CUR;
        if ($nonstks['location'] == 'int') {
            $det = "nons-intinvoice-det.php";
            $edit = "nons-intinvoice-new.php";
            $print = "nons-intinvoice-print.php";
            $note = "nons-intinvoice-note.php";
            if ($template == "default") {
                $template = "nons-intinvoice-pdf-reprint.php";
            } elseif ($template == "new") {
                $template = "pdf-tax-invoice.php";
            }
            $reprpdf = $template;
            $note = "nons-intinvoice-note.php";
            $cur = $nonstks['currency'];
        }
        # Get documents
        $docs = doclib_getdocs("ninv", $nonstks['invnum']);
        if ($nonstks['accepted'] == " " && $nonstks['done'] != "y") {
            $chbox = "<input type=checkbox name='evs[{$nonstks['invid']}]' value='{$nonstks['invid']}' checked=yes>";
        } else {
            $chbox = "";
        }
        $printOrd .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$nonstks['invnum']}</td>\n\t\t\t\t<td>{$nonstks['docref']}</td>\n\t\t\t\t<td>{$nonstks['odate']}</td>\n\t\t\t\t<td>{$nonstks['cusname']}</td>\n\t\t\t\t<td align='right'>{$cur} {$nonstks['total']}</td>\n\t\t\t\t<td>{$docs}</td>\n\t\t\t\t<td>{$chbox}</td>\n\t\t\t\t<td><a href='{$det}?invid={$nonstks['invid']}'>Details</a></td>";
        if ($nonstks['done'] != "y" && $nonstks["subtot"] == 0) {
            $printOrd .= "\n\t\t\t\t\t<td><a href='{$edit}?invid={$nonstks['invid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t<td><a href='?key=delete_confirm&invid={$nonstks['invid']}'>Delete</a></td>\n\t\t\t\t</tr>";
        } elseif ($nonstks['done'] != "y") {
            $printOrd .= "\n\t\t\t\t\t<td><a href='{$edit}?invid={$nonstks['invid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t<td><a href='?key=delete_confirm&invid={$nonstks['invid']}'>Delete</a></td>\n\t\t\t\t\t<td><a href=# onClick=printer('{$print}?invid={$nonstks['invid']}&type=nons')>Process</a></td>\n\t\t\t\t</tr>";
        } else {
            $cn = "";
            if ($nonstks['accepted'] != "note") {
                if (isset($mode) && $mode == "creditnote") {
                    $cn = "<input type='button' onClick=\"printer('{$note}?invid={$nonstks['invid']}&type=nonsnote');\" value='Credit Note'>";
                } else {
                    $cn = "<a href='#' onClick=printer('{$note}?invid={$nonstks['invid']}&type=nonsnote')>Credit Note</a>";
                }
            }
            $printOrd .= "\n\t\t\t\t\t<td>{$cn}</td>\n\t\t\t\t\t<td><a href='#' onClick=printer('{$reprint}?invid={$nonstks['invid']}&type=nonsreprint')>Reprint</a></td>\n\t\t\t\t\t<td><a href='pdf/{$reprpdf}?invid={$nonstks['invid']}&type=nonsreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t\t<td><input type='checkbox' name='evs[{$nonstks['invid']}]'></td>\n\t\t\t\t</tr>";
        }
    }
    $tot_total = sprint($tot_total);
    $printOrd .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='4'>Totals</td>\n\t\t\t\t<td align='right'>" . CUR . " {$tot_total}</td>\n\t\t\t\t<td colspan='4' align='right'>\n\t\t\t\t\t<input type='submit' value='Delete Batch' name='btndelete' />\n\t\t\t\t\t<input type='submit' value='Process Selected' name='print' />\n\t\t\t\t</td>\n\t\t\t\t<td colspan='3' align='right'><input type='submit' value='Email Selected' name='email'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form><p>" . mkQuickLinks(ql("nons-invoice-new.php", "New Non-Stock Invoice"));
    return $printOrd;
}
function printOrd($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $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.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li";
        }
        return $confirm;
    }
    # Set up table to display in
    $printOrd = "\r\n\t\t\t\t\t<center>\r\n\t\t\t        <h3>Received International Stock Orders</h3>\r\n\t\t\t        <table " . TMPL_tblDflts . ">\r\n\t\t\t       \t <tr>\r\n\t\t\t       \t \t<th>Order No.</th>\r\n\t\t\t       \t \t<th>Order Date</th>\r\n\t\t\t       \t \t<th>Supplier</th>\r\n\t\t\t       \t \t<th>Sub Total</th>\r\n\t\t\t       \t \t<th>Shipping Charges</th>\r\n\t\t\t       \t \t<th>Tax</th>\r\n\t\t\t       \t \t<th colspan='2'>Total</th>\r\n\t\t\t       \t \t<th>Delivery Reference No.</th>\r\n\t\t\t       \t \t<th>Documents</th>\r\n\t\t\t       \t \t<th colspan='5'>Options</th>\r\n\t\t\t       \t </tr>";
    # Connect to database
    db_connect();
    $queries = array();
    for ($i = $from_month; $i <= $to_month; $i++) {
        $schema = (int) $i;
        $queries[] = "SELECT *,'{$schema}' AS query_schema FROM \"{$schema}\".purch_int WHERE pdate >= '{$fromdate}' AND pdate <= '{$todate}' AND done = 'y' AND div = '" . USER_DIV . "'";
    }
    $query = implode(" UNION ", $queries);
    $query .= " ORDER BY pdate DESC";
    # Query server
    $i = 0;
    $stkpRslt = db_exec($query) or errDie("Unable to retrieve stock Orders from database.");
    if (pg_numrows($stkpRslt) < 1) {
        return "<li> There are no stock Orders found.</li>" . mkQuickLinks(ql("purch-int-new.php", "New International Order"), ql("stock-view.php", "View Stock"));
    }
    while ($stkp = pg_fetch_array($stkpRslt)) {
        # date format
        $date = explode("-", $stkp['pdate']);
        $prd = $stkp["query_schema"];
        $date = $date[2] . "-" . $date[1] . "-" . $date[0];
        # Get supplier
        db_connect();
        $sql = "SELECT supname FROM suppliers WHERE supid = '{$stkp['supid']}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql);
        if (pg_numrows($supRslt) < 1) {
            $sup['supname'] = "<li class='err'>Supplier not found.</li>";
        } else {
            $sup = pg_fetch_array($supRslt);
        }
        # Calculate the Sub-Total
        $subtot = sprint($stkp['total'] - $stkp['shipchrg']);
        $stkp['tax'] = sprint($stkp['tax']);
        $stkp['shipchrg'] = sprint($stkp['shipchrg']);
        # Get documents
        $docs = doclib_getdocs("ipur", $stkp['purnum']);
        $sp4 = "&nbsp;&nbsp;&nbsp;&nbsp;";
        #clear var
        $stkp['fbalance'] = sprint($stkp['fbalance']);
        $stkp['total'] = sprint(sprint($stkp['total']));
        $printOrd .= "\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>{$stkp['purnum']}</td>\r\n\t\t\t\t\t\t\t<td>{$date}</td>\r\n\t\t\t\t\t\t\t<td>{$sup['supname']}</td>\r\n\t\t\t\t\t\t\t<td align='right'>{$stkp['curr']} {$subtot}</td>\r\n\t\t\t\t\t\t\t<td align='right'>{$stkp['curr']} {$stkp['shipchrg']}</td>\r\n\t\t\t\t\t\t\t<td align='right'>{$stkp['curr']} {$stkp['tax']}</td>\r\n\t\t\t\t\t\t\t<td align='right'>{$stkp['curr']} {$stkp['total']}</td>\r\n\t\t\t\t\t\t\t<td align='right'>{$sp4} " . CUR . " {$stkp['fbalance']}</td>\r\n\t\t\t\t\t\t\t<td>{$stkp['refno']}</td>\r\n\t\t\t\t\t\t\t<td>{$docs}</td>";
        if ($stkp['returned'] != 'y' && returnable($stkp['purnum'])) {
            $printOrd .= "<td><a href='purch-int-return.php?purid={$stkp['purid']}&prd={$prd}'>Return</a></td>";
        } else {
            $printOrd .= "<td><br></td>";
        }
        if ($stkp['rsubtot'] > 0) {
            $printOrd .= "<td><a href='purch-int-recnote.php?purid={$stkp['purid']}&prd={$prd}'>Record Credit Note</a></td>";
        } else {
            $printOrd .= "<td><br></td>";
        }
        $printOrd .= "<td><a href='purch-int-det-prd.php?purid={$stkp['purid']}&prd={$prd}'>Details</a></td></tr>";
        $i++;
    }
    $printOrd .= "\r\n\t\t\t\t\t<tr><td><br></td></tr>\r\n\t\t\t\t\t<form action='" . SELF . "' method='POST'>\r\n\t\t\t\t\t\t<input type='hidden' name='key' value='export'>\r\n\t\t\t\t\t\t<input type='hidden' name='prd' value='{$prd}'>\r\n\t\t\t\t\t\t<input type='hidden' name='fday' value='{$from_day}'>\r\n\t\t\t\t\t\t<input type='hidden' name='fmon' value='{$from_month}'>\r\n\t\t\t\t\t\t<input type='hidden' name='fyear' value='{$from_year}'>\r\n\t\t\t\t\t\t<input type='hidden' name='today' value='{$to_day}'>\r\n\t\t\t\t\t\t<input type='hidden' name='tomon' value='{$to_month}'>\r\n\t\t\t\t\t\t<input type='hidden' name='toyear' value='{$to_year}'>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td colspan='3'><input type='submit' value='Export to Spreadsheet'></td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</form>\r\n\t\t\t\t\t</table>" . mkQuickLinks(ql("purch-int-new.php", "New International Order"), ql("stock-view.php", "View Stock"));
    return $printOrd;
}
function printPurch($_POST, $pure = false)
{
    extract($_POST);
    require_lib("validate");
    $v = new validate();
    $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.");
    $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.");
    }
    if ($v->isError()) {
        return $v->genErrors();
    }
    require_lib("docman");
    $OUT = "";
    if (!$pure) {
        $OUT .= "\n\t\t<center>\n\t\t<h3>Received Stock Orders</h3>";
    }
    $OUT .= "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Purchase No.</th>\n\t\t\t\t<th>Order No.</th>\n\t\t\t\t<th>Supp Inv No.</th>\n\t\t\t\t<th>Order Date</th>\n\t\t\t\t<th>Received Date</th>\n\t\t\t\t<th>Supplier</th>\n\t\t\t\t<th>Sub Total</th>\n\t\t\t\t<th>Delivery Charges</th>\n\t\t\t\t<th>VAT</th>\n\t\t\t\t<th>Total</th>\n\t\t\t\t<th>Delivery Reference No.</th>\n\t\t\t\t<th>Documents</th>\n\t\t\t\t<th colspan='5'>Options</th>\n\t\t\t</tr>";
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    $tot3 = 0;
    $tot4 = 0;
    $supsql = "";
    if (isset($supplier) and $supplier != 0) {
        $supsql = " AND supid = '{$supplier}'";
    }
    /* build the sql */
    $queries = array();
    for ($i = 1; $i <= 12; $i++) {
        $schema = (int) $i;
        $queries[] = "SELECT *,'{$schema}' AS query_schema FROM \"{$schema}\".purchases WHERE pdate >= '{$fromdate}' AND pdate <= '{$todate}' AND done = 'y' AND div = '" . USER_DIV . "' {$supsql}";
    }
    $sql = implode(" UNION ", $queries) . " ORDER BY pdate DESC";
    $qry = new dbQuery(DB_SQL, $sql);
    $qry->run();
    if ($qry->num_rows() < 1) {
        return "<li class='err'> No Received Stock Orders found.</li><br>";
    }
    while ($stkp = $qry->fetch_array()) {
        $prd = $stkp["query_schema"];
        /* calculate the subtotal */
        $stkp['total'] = sprint($stkp['total']);
        $stkp['shipchrg'] = sprint($stkp['shipping']);
        $subtot = $stkp['subtot'];
        $subtot = sprint($subtot);
        /* add the totals */
        $tot1 = sprint($tot1 + $subtot);
        $tot2 = sprint($tot2 + $stkp['shipchrg']);
        $tot3 = sprint($tot3 + $stkp['total']);
        $tot4 = sprint($tot4 + $stkp["vat"]);
        $docs = doclib_getdocs("pur", $stkp['purnum']);
        $docs .= "&nbsp;<a href='#' onClick=\"printer('purch-recv.php?key=recv_print&purid={$stkp['purid']}');\">GRN</a>";
        $OUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$stkp['purnum']}</td>\n\t\t\t\t<td>{$stkp['ordernum']}</td>\n\t\t\t\t<td>{$stkp['supinv']}</td>\n\t\t\t\t<td>{$stkp['pdate']}</td>\n\t\t\t\t<td>{$stkp['ddate']}</td>\n\t\t\t\t<td>{$stkp['supname']}</td>\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$subtot}</td>\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$stkp['shipchrg']}</td>\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$stkp['vat']}</td>\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$stkp['total']}</td>\n\t\t\t\t<td>{$stkp['refno']}</td>\n\t\t\t\t<td>{$docs}</td>";
        if ($stkp['returned'] != 'y') {
            $OUT .= "<td><a href='purch-return.php?purid={$stkp['purid']}&prd={$prd}'>Return</a></td>";
        } else {
            $OUT .= "<td>&nbsp;</td>";
        }
        if ($stkp['rsubtot'] > 0) {
            $OUT .= "<td><a href='purch-recnote.php?purid={$stkp['purid']}&prd={$prd}'>Record Credit Note</a></td>";
        } else {
            $OUT .= "<td>&nbsp;</td>";
        }
        $OUT .= "\n\t\t\t\t<td><a href='purch-det-prd.php?purid={$stkp['purid']}&prd={$prd}'>Details</a></td>\n\t\t\t\t<td><a target='_blank' href='purch-recv-print.php?purid={$stkp['purid']}&prd={$prd}'>Print</a></td>\n\t\t\t</tr>";
    }
    $OUT .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='6'>Totals</td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$tot1}</td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$tot2}</td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$tot4}</td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$tot3}</td>\n\t\t</tr>";
    if (!$pure) {
        $OUT .= "\n\t\t\t" . TBL_BR . "\n\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t<input type='hidden' name='key' value='export' />\n\t\t\t\t<input type='hidden' name='prd' value='{$prd}' />\n\t\t\t\t<input type='hidden' name='from_day' value='{$from_day}' />\n\t\t\t\t<input type='hidden' name='from_month' value='{$from_month}' />\n\t\t\t\t<input type='hidden' name='from_year' value='{$from_year}' />\n\t\t\t\t<input type='hidden' name='to_day' value='{$to_day}' />\n\t\t\t\t<input type='hidden' name='to_month' value='{$to_month}' />\n\t\t\t\t<input type='hidden' name='to_year' value='{$to_year}' />\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='4'><input type='submit' value='Export to Spreadsheet'></td>\n\t\t\t\t</tr>\n\t\t\t</form>";
    }
    $OUT .= "</table>";
    return $OUT;
}
function printPurch($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $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.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li>";
        }
        return $confirm;
    }
    # Set up table to display in
    $printOrd = "\n\t\t<center>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='export'>\n\t\t\t<input type='hidden' name='fday' value='{$from_day}'>\n\t\t\t<input type='hidden' name='fmon' value='{$from_month}'>\n\t\t\t<input type='hidden' name='fyear' value='{$from_year}'>\n\t\t\t<input type='hidden' name='today' value='{$to_day}'>\n\t\t\t<input type='hidden' name='tomon' value='{$to_month}'>\n\t\t\t<input type='hidden' name='toyear' value='{$to_year}'>\n\t\t<h3>View Stock Orders</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>No.</th>\n\t\t\t\t<th>Order No.</th>\n\t\t\t\t<th>Supp Inv No.</th>\n\t\t\t\t<th>Order Date</th>\n\t\t\t\t<th>Supplier</th>\n\t\t\t\t<th>Sub Total</th>\n\t\t\t\t<th>Delivery Charges</th>\n\t\t\t\t<th>Vat</th>\n\t\t\t\t<th>Total</th>\n\t\t\t\t<th>Documents</th>\n\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    $tot3 = 0;
    $tot4 = 0;
    $supsql = "";
    if (isset($supplier) and $supplier != 0) {
        $supsql = " AND supid = '{$supplier}'";
    }
    $sql = "SELECT * FROM cancelled_purch WHERE pdate >= '{$fromdate}' AND pdate <= '{$todate}' AND div = '" . USER_DIV . "' {$supsql} ORDER BY pdate DESC";
    $stkpRslt = db_exec($sql) or errDie("Unable to retrieve stock purchases from database.");
    if (pg_numrows($stkpRslt) < 1) {
        return "\n\t\t\t<li class='err'> No stock Orders found</li><br>\n\t\t\t<table border='0' cellpadding='2' cellspacing='1'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='purchase-new.php'>New Order</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='purchase-view.php'>View Purchases</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
    } else {
        while ($stkp = pg_fetch_array($stkpRslt)) {
            # Date format
            $date = explode("-", $stkp['pdate']);
            $date = $date[2] . "-" . $date[1] . "-" . $date[0];
            # Calculate the Sub-Total
            $stkp['total'] = sprint($stkp['total']);
            $stkp['shipchrg'] = sprint($stkp['shipping']);
            $subtot = $stkp['subtot'];
            $subtot = sprint($subtot);
            $vat = sprint($stkp['vat']);
            $tot1 = sprint($tot1 + $subtot);
            $tot2 = sprint($tot2 + $stkp['shipchrg']);
            $tot3 = sprint($tot3 + $stkp['total']);
            $tot4 = sprint($tot4 + $vat);
            # Get documents
            $docs = doclib_getdocs("pur", $stkp['purnum']);
            $printOrd .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$stkp['purnum']}</td>\n\t\t\t\t\t<td>{$stkp['ordernum']}</td>\n\t\t\t\t\t<td>{$stkp['supinv']}</td>\n\t\t\t\t\t<td>{$date}</td>\n\t\t\t\t\t<td>{$stkp['supname']}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$subtot}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$stkp['shipchrg']}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$vat}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$stkp['total']}</td>\n\t\t\t\t\t<td>{$docs}</td>\n\t\t\t\t\t<td><a href='purch-canc-print.php?purid={$stkp['purid']}'>Print</a></td>";
            $i++;
        }
    }
    $printOrd .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='5'>Totals</td>\n\t\t\t\t<td align='right'>" . CUR . " {$tot1}</td>\n\t\t\t\t<td align='right'>" . CUR . " {$tot2}</td>\n\t\t\t\t<td align='right'>" . CUR . " {$tot4}</td>\n\t\t\t\t<td align='right'>" . CUR . " {$tot3}</td>\n\t\t\t\t<td colspan='8'>&nbsp</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='17' align='right'><input type='submit' value='Export to Spreadsheet'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='purchase-new.php'>New Order</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='stock-report.php'>Stock Control Reports</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='stock-view.php'>View Stock</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $printOrd;
}
function printInv($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $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.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li>";
        }
        return $confirm;
    }
    $accnum = remval($accnum);
    if (strlen($accnum) > 0) {
        db_conn('cubit');
        $Sl = "SELECT * FROM customers WHERE lower(accno)=lower('{$accnum}')";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>Invalid account number</li>" . slct();
        }
        $cd = pg_fetch_array($Ri);
        $cusnum = $cd['cusnum'];
    }
    /* make named r2s snapshop */
    r2sListSet("invoice_stk_view");
    # Set up table to display in
    $printInv = "\n\t\t<h3>View invoices. Date Range {$fromdate} to {$todate}</h3>\n\t\t<form action='invoice-proc.php' method='GET'>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Department</th>\n\t\t\t\t<th>No.</th>\n\t\t\t\t<th>Invoice Date</th>\n\t\t\t\t<th>Customer Name</th>\n\t\t\t\t<th>Order No</th>\n\t\t\t\t<th>Customer Order No</th>\n\t\t\t\t<th>Grand Total</th>\n\t\t\t\t<th colspan='2'>Balance</th>\n\t\t\t\t<th>Documents</th>\n\t\t\t\t<th colspan='6'>Options</th>\n\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    if (isset($all)) {
        $sql = "SELECT * FROM invoices WHERE done = 'y' AND odate>='{$fromdate}' AND odate <= '{$todate}' AND div = '" . USER_DIV . "' ORDER BY invid DESC";
    } else {
        $sql = "SELECT * FROM invoices WHERE done = 'y' AND odate>='{$fromdate}' AND odate <= '{$todate}' AND cusnum = {$cusnum} AND div = '" . USER_DIV . "' ORDER BY invid DESC";
    }
    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    // Retrieve the reprint setting
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='reprints' AND div='" . USER_DIV . "'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if (pg_numrows($invRslt) < 1) {
        $printInv = "<li class='err'> No Outstanding Invoices found for the selected customer.</li><br>";
    } else {
        while ($inv = pg_fetch_array($invRslt)) {
            $inv['total'] = sprint($inv['total']);
            $inv['balance'] = sprint($inv['balance']);
            $tot1 = $tot1 + $inv['total'];
            $tot2 = $tot2 + $inv['balance'];
            # Get documents
            $docs = doclib_getdocs("inv", $inv['invnum']);
            # Format date
            $inv['odate'] = explode("-", $inv['odate']);
            $inv['odate'] = $inv['odate'][2] . "-" . $inv['odate'][1] . "-" . $inv['odate'][0];
            if ($inv['printed'] == "n") {
                $Dis = "TI {$inv['invid']}";
            } else {
                $Dis = "{$inv['invnum']}";
            }
            $det = "invoice-details.php";
            $print = "invoice-print.php";
            $edit = "cust-credit-stockinv.php";
            $reprint = "invoice-reprint.php";
            if (isset($mode) && $mode == "creditnote") {
                $note = "<input type='button' onClick='document.location.href=\"invoice-note.php?invid={$inv['invid']}\";' value='Credit Note'>";
            } else {
                $note = "<a href='invoice-note.php?invid={$inv['invid']}'>Credit Note</a>";
            }
            if ($template == "default") {
                $template = "invoice-pdf-reprint.php";
            } elseif ($template == "new") {
                $template = "pdf-tax-invoice.php";
            }
            $pdfreprint = $template;
            $chbox = "<input type=checkbox name='invids[]' value='{$inv['invid']}' checked=yes>";
            if ($inv['location'] == 'int') {
                $det = "intinvoice-details.php";
                $print = "intinvoice-print.php";
                $edit = "intinvoice-new.php";
                $reprint = "intinvoice-reprint.php";
                if (isset($mode) && $mode == "creditnote") {
                    $note = "<input type='button' onClick='document.location.href=\"intinvoice-note.php?invid={$inv['invid']}\";' value='Credit Note'>";
                } else {
                    $note = "<a href='intinvoice-note.php?invid={$inv['invid']}'>Credit Note</a>";
                }
                if ($template == "default") {
                    $template = "intinvoice-pdf-reprint.php";
                } elseif ($template == "new") {
                    $template = "pdf-tax-invoice.php";
                }
                $pdfreprint = $template;
                $chbox = "<br>";
            }
            if ($inv['serd'] == 'n') {
                $chbox = "";
            }
            $sp4 = "&nbsp;&nbsp;&nbsp;&nbsp;";
            $fbal = "{$sp4}--{$sp4}";
            $bcurr = CUR;
            if ($inv['location'] == 'int') {
                $fbal = "{$sp4} {$inv['currency']} {$inv['fbalance']}";
                $bcurr = $inv['currency'];
            }
            //<a href='invoice-email.php?invid=$inv[invid]'>Email</a>
            $printInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$inv['deptname']}</td>\n\t\t\t\t\t<td>{$Dis}</td>\n\t\t\t\t\t<td align='center'>{$inv['odate']}</td>\n\t\t\t\t\t<td>{$inv['cusname']} {$inv['surname']}</td>\n\t\t\t\t\t<td align='right'>{$inv['ordno']}</td>\n\t\t\t\t\t<td align='right'>{$inv['cordno']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$bcurr} {$inv['total']}</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t<td align='right' nowrap> {$fbal}</td>\n\t\t\t\t\t<td>{$docs}</td>\n\t\t\t\t\t<td><a href='{$det}?invid={$inv['invid']}'>Details</a></td>\n\t\t\t\t\t<td><input type='checkbox' name='evs[{$inv['invid']}]'></td>";
            if ($inv['printed'] == "n") {
                $printInv .= "\n\t\t\t\t\t\t<td><a href='{$edit}?invid={$inv['invid']}&cont=1&letters='>Edit</a></td>\n\t\t\t\t\t\t<td><a target='_blank' href='{$print}?invid={$inv['invid']}'>Process</a></td>\n\t\t\t\t\t\t<td align='center'>{$chbox}</td>\n\t\t\t\t\t\t<td>&nbsp</td>\n\t\t\t\t\t</tr>";
            } else {
                db_conn($inv["prd"]);
                $sql = "SELECT * FROM inv_notes WHERE invid='{$inv['invid']}'";
                $note_rslt = db_exec($sql) or errDie("Unable to retrieve credit notes from Cubit.");
                if (!pg_num_rows($note_rslt)) {
                    $delnote = "<td><a target='_blank' href='invoice-delnote.php?invid={$inv['invid']}'>Delivery Note</a></td>";
                } else {
                    $delnote = "<td>&nbsp;</td>";
                }
                if (round($inv['total'], 0) != round($inv['nbal'], 0)) {
                    $printInv .= "\n\t\t\t\t\t\t\t<td>{$note}</td>\n\t\t\t\t\t\t\t<td><a target='_blank' href='{$reprint}?invid={$inv['invid']}&type=invreprint'>Reprint</a></td>\n\t\t\t\t\t\t\t<td><a href='pdf/{$pdfreprint}?invid={$inv['invid']}&type=invreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t\t\t\t{$delnote}\n\t\t\t\t\t\t</tr>";
                } else {
                    $printInv .= "\n\t\t\t\t\t\t\t<td>Settled</td>\n\t\t\t\t\t\t\t<td><a target='_blank' href='{$reprint}?invid={$inv['invid']}&type=invreprint'>Reprint</a></td>\n\t\t\t\t\t\t\t<td><a href='pdf/{$pdfreprint}?invid={$inv['invid']}&type=invreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t\t\t\t{$delnote}\n\t\t\t\t\t\t</tr>";
                }
            }
            $i++;
        }
    }
    $tot1 = sprint($tot1);
    $tot2 = sprint($tot2);
    //	$bgColor = bgcolor($i);
    // Layout
    if ($i > 0) {
        $printInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='6'>Totals:{$i}</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$tot1}</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$tot2}</td>\n\t\t\t\t\t<td colspan='3'><br></td>\n\t\t\t\t\t<td colspan='3' align='right'><input type='submit' value='Email Selected' name='email'>\n\t\t\t\t\t</td><td colspan='10' align='right'><input type='submit' value='Process Selected' name='proc'></td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    $printInv .= "\n\t\t</table>\n\t\t</form>";
    return $printInv;
}
function find_invoice($invnum)
{
    if (!isset($invnum) or strlen($invnum) < 1) {
        $invnum = 0;
    } else {
        $invnum = trim($invnum);
    }
    ###############################################[ NORMAL INVOICES ]#############################################
    $normalInv = "\n\t\t<h3>Invoices</h3>\n\t\t<tr>\n\t\t\t<th>Department</th>\n\t\t\t<th>No.</th>\n\t\t\t<th>Invoice Date</th>\n\t\t\t<th>Customer Name</th>\n\t\t\t<th>Order No</th>\n\t\t\t<th>Customer Order No</th>\n\t\t\t<th>Grand Total</th>\n\t\t\t<th colspan='2'>Balance</th>\n\t\t\t<th>Documents</th>\n\t\t\t<th colspan='6'>Options</th>\n\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    $sql = "SELECT * FROM invoices WHERE done = 'y' AND invnum = '{$invnum}' AND div = '" . USER_DIV . "' ORDER BY invid DESC";
    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    // Retrieve the reprint setting
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='reprints' AND div='" . USER_DIV . "'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if (pg_numrows($invRslt) < 1) {
        $normalInv = "<li class='err'> No Outstanding Invoices found for the selected customer.</li><br>";
    } else {
        while ($inv = pg_fetch_array($invRslt)) {
            $inv['total'] = sprint($inv['total']);
            $inv['balance'] = sprint($inv['balance']);
            $tot1 = $tot1 + $inv['total'];
            $tot2 = $tot2 + $inv['balance'];
            # Get documents
            $docs = doclib_getdocs("inv", $inv['invnum']);
            # Format date
            $inv['odate'] = explode("-", $inv['odate']);
            $inv['odate'] = $inv['odate'][2] . "-" . $inv['odate'][1] . "-" . $inv['odate'][0];
            if ($inv['printed'] == "n") {
                $Dis = "TI {$inv['invid']}";
            } else {
                $Dis = "{$inv['invnum']}";
            }
            $det = "invoice-details.php";
            $print = "invoice-print.php";
            $edit = "cust-credit-stockinv.php";
            $reprint = "invoice-reprint.php";
            if (isset($mode) && $mode == "creditnote") {
                $note = "<input type='button' onClick='document.location.href=\"invoice-note.php?invid={$inv['invid']}\";' value='Credit Note'>";
            } else {
                $note = "<a href='invoice-note.php?invid={$inv['invid']}'>Credit Note</a>";
            }
            if ($template == "default") {
                $template = "invoice-pdf-reprint.php";
            } elseif ($template == "new") {
                $template = "pdf-tax-invoice.php";
            }
            $pdfreprint = $template;
            $chbox = "<input type=checkbox name='invids[]' value='{$inv['invid']}' checked=yes>";
            if ($inv['location'] == 'int') {
                $det = "intinvoice-details.php";
                $print = "intinvoice-print.php";
                $edit = "intinvoice-new.php";
                $reprint = "intinvoice-reprint.php";
                if (isset($mode) && $mode == "creditnote") {
                    $note = "<input type='button' onClick='document.location.href=\"intinvoice-note.php?invid={$inv['invid']}\";' value='Credit Note'>";
                } else {
                    $note = "<a href='intinvoice-note.php?invid={$inv['invid']}'>Credit Note</a>";
                }
                if ($template == "default") {
                    $template = "intinvoice-pdf-reprint.php";
                } elseif ($template == "new") {
                    $template = "pdf-tax-invoice.php";
                }
                $pdfreprint = $template;
                $chbox = "<br>";
            }
            if ($inv['serd'] == 'n') {
                $chbox = "";
            }
            $sp4 = "&nbsp;&nbsp;&nbsp;&nbsp;";
            $fbal = "{$sp4}--{$sp4}";
            $bcurr = CUR;
            if ($inv['location'] == 'int') {
                $fbal = "{$sp4} {$inv['currency']} {$inv['fbalance']}";
                $bcurr = $inv['currency'];
            }
            //<a href='invoice-email.php?invid=$inv[invid]'>Email</a>
            $normalInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$inv['deptname']}</td>\n\t\t\t\t\t<td>{$Dis}</td>\n\t\t\t\t\t<td align='center'>{$inv['odate']}</td>\n\t\t\t\t\t<td>{$inv['cusname']} {$inv['surname']}</td>\n\t\t\t\t\t<td align='right'>{$inv['ordno']}</td>\n\t\t\t\t\t<td align='right'>{$inv['cordno']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$bcurr} {$inv['total']}</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t<td align='right' nowrap> {$fbal}</td>\n\t\t\t\t\t<td>{$docs}</td>\n\t\t\t\t\t<td><a target='_blank' href='{$det}?invid={$inv['invid']}'>Details</a></td>";
            if ($inv['printed'] == "n") {
                $normalInv .= "\n\t\t\t\t\t\t<td><a href='{$edit}?invid={$inv['invid']}&cont=1&letters='>Edit</a></td>\n\t\t\t\t\t\t<td><a target='_blank' href='{$print}?invid={$inv['invid']}'>Process</a></td>\n\t\t\t\t\t\t<td align='center'>{$chbox}</td>\n\t\t\t\t\t\t<td>&nbsp</td>\n\t\t\t\t\t</tr>";
            } else {
                db_conn($inv["prd"]);
                $sql = "SELECT * FROM inv_notes WHERE invid='{$inv['invid']}'";
                $note_rslt = db_exec($sql) or errDie("Unable to retrieve credit notes from Cubit.");
                if (!pg_num_rows($note_rslt)) {
                    $delnote = "<td><a target='_blank' href='invoice-delnote.php?invid={$inv['invid']}'>Delivery Note</a></td>";
                } else {
                    $delnote = "<td>&nbsp;</td>";
                }
                if (round($inv['total'], 0) != round($inv['nbal'], 0)) {
                    $normalInv .= "\n\t\t\t\t\t\t\t<td>{$note}</td>\n\t\t\t\t\t\t\t<td><a target='_blank' href='{$reprint}?invid={$inv['invid']}&type=invreprint'>Reprint</a></td>\n\t\t\t\t\t\t\t<td><a href='pdf/{$pdfreprint}?invid={$inv['invid']}&type=invreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t\t\t\t{$delnote}\n\t\t\t\t\t\t</tr>";
                } else {
                    $normalInv .= "\n\t\t\t\t\t\t\t<td>Settled</td>\n\t\t\t\t\t\t\t<td><a target='_blank' href='{$reprint}?invid={$inv['invid']}&type=invreprint'>Reprint</a></td>\n\t\t\t\t\t\t\t<td><a href='pdf/{$pdfreprint}?invid={$inv['invid']}&type=invreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t\t\t\t{$delnote}\n\t\t\t\t\t\t</tr>";
                }
            }
            $i++;
        }
        return $normalInv;
    }
    ##############################################[ /NORMAL INVOICES ]####################################################
    ################################################[ PAID INVOICES ]#####################################################
    # Set up table to display in
    $paidInv = "\n\t\t<h3>Paid Invoices</h3>\n\t\t<tr>\n\t\t\t<th>Department</th>\n\t\t\t<th>Invoice No.</th>\n\t\t\t<th>Proforma Inv No.</th>\n\t\t\t<th>Invoice Date</th>\n\t\t\t<th>Customer Name</th>\n\t\t\t<th>Order No</th>\n\t\t\t<th>Customer Order No</th>\n\t\t\t<th>Grand Total</th>\n\t\t\t<th>Documents</th>\n\t\t\t<th colspan='5'>Options</th>\n\t\t</tr>";
    // Retrieve template setting
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        $repr = "invoice-reprint-prd.php";
    } else {
        $repr = $template;
    }
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='reprints'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "new") {
        $pdf_repr = "pdf/pdf-tax-invoice.php";
    } else {
        $pdf_repr = "pdf/invoice-pdf-reprint-prd.php";
    }
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    # Connect to database
    db_connect();
    $queries = array();
    for ($i = 1; $i <= 12; $i++) {
        $schema = (int) $i;
        $queries[] = "SELECT *,'{$schema}' AS query_schema FROM \"{$schema}\".invoices WHERE done = 'y' AND invnum = '{$invnum}' AND div = '" . USER_DIV . "'";
    }
    $query = implode(" UNION ", $queries);
    $query .= " ORDER BY invid DESC";
    $invRslt = db_exec($query) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($invRslt) < 1) {
        $paidInv = "<li class='err'>No previous finished invoices found.</li>";
    } else {
        while ($inv = pg_fetch_array($invRslt)) {
            $prd = $inv["query_schema"];
            $inv['total'] = sprint($inv['total']);
            $inv['balance'] = sprint($inv['balance']);
            $tot1 = $tot1 + $inv['total'];
            $tot2 = $tot2 + $inv['balance'];
            # format date
            $inv['odate'] = explode("-", $inv['odate']);
            $inv['odate'] = $inv['odate'][2] . "-" . $inv['odate'][1] . "-" . $inv['odate'][0];
            # Get documents
            $docs = doclib_getdocs("inv", $inv['invnum']);
            $sp4 = "&nbsp;&nbsp;&nbsp;&nbsp;";
            $bcurr = CUR;
            $det = "invoice-details-prd.php";
            $reprint = "<td><a target='_blank' href='{$repr}?type=invpaidreprint&invid={$inv['invid']}&prd={$prd}'>Reprint</a></td>";
            $note = "<td><a target='_blank' href='invoice-note-prd.php?invid={$inv['invid']}&prd={$prd}'>Credit Note</a></td>";
            if ($inv['location'] == 'int') {
                $bcurr = $inv['currency'];
                $det = "intinvoice-details-prd.php";
                $reprint = "<td><a target='_blank' href='intinvoice-reprint-prd.php?invid={$inv['invid']}&prd={$prd}'>Reprint</a></td>";
                $note = "";
            }
            $delnote = "<td><a target='_blank' href='invoice-delnote-prd.php?invid={$inv['invid']}&prd={$prd}'>Delivery Note</a></td>";
            $paidInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$inv['deptname']}</td>\n\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t<td>{$inv['docref']}</td>\n\t\t\t\t\t<td align='center'>{$inv['odate']}</td>\n\t\t\t\t\t<td>{$inv['cusname']} {$inv['surname']}</td>\n\t\t\t\t\t<td align='right'>{$inv['ordno']}</td>\n\t\t\t\t\t<td align='right'>{$inv['cordno']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$bcurr} {$inv['total']}</td>\n\t\t\t\t\t<td>{$docs}</td>\n\t\t\t\t\t<td><a target='_blank' href='{$det}?invid={$inv['invid']}&prd={$prd}'>Details</a></td>\n\t\t\t\t\t</td>{$reprint}</td>\n\t\t\t\t\t<td><a href='{$pdf_repr}?invid={$inv['invid']}&prd={$prd}&type=invpaidreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t\t{$note}\n\t\t\t\t\t{$delnote}\n\t\t\t\t</tr>";
            $i++;
        }
        return $paidInv;
    }
    ################################################[ /PAID INVOICES ]####################################################
    #############################################[ INCOMPLETE INVOICES ]##################################################
    # Set up table to display in
    $unfInv = "\n\t\t<h3>Incomplete Invoices</h3>\n\t\t<tr>\n\t\t\t<th>Username</th>\n\t\t\t<th>Department</th>\n\t\t\t<th>Sales Person</th>\n\t\t\t<th>Invoice No.</th>\n\t\t\t<th>Invoice Date</th>\n\t\t\t<th>Customer Name</th>\n\t\t\t<th>Order No</th>\n\t\t\t<th>Grand Total</th>\n\t\t\t<th colspan='4'>Options</th>\n\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $totgrd = 0;
    $sql = "SELECT * FROM invoices WHERE done = 'n' AND printed ='n' AND invnum = '{$invnum}' AND div = '" . USER_DIV . "' ORDER BY invid DESC";
    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($invRslt) < 1) {
        $unfInv = "<li>No Incomplete Invoices Found.</li>";
    } else {
        while ($inv = pg_fetch_array($invRslt)) {
            # format date
            $inv['odate'] = explode("-", $inv['odate']);
            $inv['odate'] = $inv['odate'][2] . "-" . $inv['odate'][1] . "-" . $inv['odate'][0];
            $cont = "cust-credit-stockinv.php";
            if ($inv['location'] == 'int') {
                $cont = "intinvoice-new.php";
            }
            $sp4 = "&nbsp;&nbsp;&nbsp;&nbsp;";
            $bcurr = CUR;
            if ($inv['location'] == 'int') {
                $bcurr = $inv['currency'];
            }
            if (isset($button) && $button == "selall") {
                $checked = "checked='checked'";
            } else {
                $checked = "";
            }
            $inv['total'] = sprint($inv['total']);
            $unfInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$inv['username']}</td>\n\t\t\t\t\t<td>{$inv['deptname']}</td>\n\t\t\t\t\t<td>{$inv['salespn']}</td>\n\t\t\t\t\t<td>TI {$inv['invid']}</td>\n\t\t\t\t\t<td align='center'>{$inv['odate']}</td>\n\t\t\t\t\t<td>{$inv['cusname']} {$inv['surname']}</td>\n\t\t\t\t\t<td align='right'>{$inv['ordno']}</td>\n\t\t\t\t\t<td>{$bcurr} {$inv['total']}</td>\n\t\t\t\t\t<td><a href='{$cont}?invid={$inv['invid']}&cont=true&letters=&done='>Continue</a></td>\n\t\t\t\t\t<td><a href='invoice-unf-cancel.php?invid={$inv['invid']}'>Cancel</a></td>\n\t\t\t\t</tr>";
            $totgrd += $inv['total'];
            $i++;
        }
        return $unfInv;
    }
    ############################################[ /INCOMPLETE INVOICES ]##################################################
    #############################################[ UNPROCESSED POS INVOICES ]###################################################
    # Set up table to display in
    $unposInv = "\n\t\t<h3>Unprocessed Point of Sale Invoices</h3>\n\t\t<tr>\n\t\t\t<th>Department</th>\n\t\t\t<th>Sales Person</th>\n\t\t\t<th>Inv No.</th>\n\t\t\t<th>Invoice Date</th>\n\t\t\t<th>Customer</th>\n\t\t\t<th>Grand Total</th>\n\t\t\t<th colspan='4'>Options</th>\n\t\t\t<th>&nbsp;</th>\t\n\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot1 = 0;
    $sql = "SELECT invid, total, odate, deptname, salespn, cusname, printed, balance,cusnum FROM pinvoices WHERE invnum = '{$invnum}' OR invid = '{$invnum}' AND div = '" . USER_DIV . "' ORDER BY invid DESC";
    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($invRslt) < 1) {
        $unposInv = "<li class='err'>No Point of Sale Invoices found for the selected date range.</li>" . slct();
    } else {
        while ($inv = pg_fetch_array($invRslt)) {
            $inv['total'] = sprint($inv['total']);
            $tot1 = $tot1 + $inv['total'];
            # format date
            $inv['odate'] = explode("-", $inv['odate']);
            $inv['odate'] = $inv['odate'][2] . "-" . $inv['odate'][1] . "-" . $inv['odate'][0];
            if ($inv['cusnum'] != "0") {
                #overwrite the default cusname
                $get_cust = "SELECT surname FROM customers WHERE cusnum = '{$inv['cusnum']}' LIMIT 1";
                $run_cust = db_exec($get_cust) or errDie("Unable to get customer information.");
                if (pg_numrows($run_cust) == 1) {
                    $arr = pg_fetch_array($run_cust);
                    $inv['cusname'] = $arr['surname'];
                }
            }
            $unposInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$inv['deptname']}</td>\n\t\t\t\t\t<td>{$inv['salespn']}</td>\n\t\t\t\t\t<td>TP {$inv['invid']}</td>\n\t\t\t\t\t<td align='center'>{$inv['odate']}</td>\n\t\t\t\t\t<td>{$inv['cusname']}</td>\n\t\t\t\t\t<td align=right>" . CUR . " {$inv['total']}</td>\n\t\t\t\t\t<td><a target='_blank' href='pos-invoice-details.php?invid={$inv['invid']}'>Details</a></td>";
            if ($inv['printed'] == "n") {
                $unposInv .= "\n\t\t\t\t\t<td><a href='pos-invoice-new.php?invid={$inv['invid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t<td><a href='?invid={$inv['invid']}&key=delete_confirm'>Delete</a></td>\n\t\t\t\t\t<td><a target='_blank' href='pos-invoice-print.php?invid={$inv['invid']}'>Process</a></td>";
            } else {
                $unposInv .= "\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<a target='_blank' href='pos-invoice-reprint.php?invid={$inv['invid']}'>Reprint</a>\n\t\t\t\t\t</td>";
            }
            if (isset($button) && $button == "allsel") {
                $checked = "checked='checked'";
            } else {
                $checked = "";
            }
            $unposInv .= "\n\t\t\t\t</tr>";
            $i++;
        }
        return $unposInv;
    }
    #############################################[ /UNPROCESSED POS INVOICES ]###################################################
    #############################################[ PROCESSED POS INVOICES ]###################################################
    # Set up table to display in
    $posInv = "\n\t\t<h3>Processed Point of Sale Invoices</h3>\n    \t<tr>\n    \t\t<th>Department</th>\n    \t\t<th>Sales Person</th>\n    \t\t<th>Invoice No.</th>\n    \t\t<th>Invoice Date</th>\n    \t\t<th>Customer Name</th>\n    \t\t<th>Grand Total</th>\n    \t\t<th colspan='4'>Options</th>\n    \t</tr>";
    # Connect to database
    db_connect();
    $queries = array();
    for ($i = 1; $i <= 12; $i++) {
        $schema = (int) $i;
        $queries[] = "SELECT *,'{$schema}' AS query_schema FROM \"{$schema}\".pinvoices WHERE done = 'y' AND invnum = '{$invnum}' OR invid = '{$invnum}' AND div = '" . USER_DIV . "'";
    }
    $query = implode(" UNION ", $queries);
    $query .= " ORDER BY invnum DESC";
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    $invRslt = db_exec($query) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($invRslt) < 1) {
        $posInv = "<li>No previous finished invoices.</li>";
    } else {
        while ($inv = pg_fetch_array($invRslt)) {
            $prd = $inv["query_schema"];
            $inv['total'] = sprint($inv['total']);
            $inv['balance'] = sprint($inv['balance']);
            $tot1 = $tot1 + ($inv['total'] - $inv['rounding']);
            $tot2 = $tot2 + $inv['balance'];
            # format date
            $inv['odate'] = explode("-", $inv['odate']);
            $inv['odate'] = $inv['odate'][2] . "-" . $inv['odate'][1] . "-" . $inv['odate'][0];
            if ($inv['cusnum'] != "0") {
                #then get the actual customer
                db_connect();
                $get_cus = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' LIMIT 1";
                $run_cus = db_exec($get_cus) or errDie("Unable to get customer information");
                if (pg_numrows($run_cus) < 1) {
                    #do nothing
                } else {
                    $carr = pg_fetch_array($run_cus);
                    $inv['cusname'] = "{$carr['cusname']} {$carr['surname']}";
                }
            }
            $total = sprint($inv['total'] - $inv['rounding']);
            $posInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$inv['deptname']}</td>\n\t\t\t\t\t<td>{$inv['salespn']}</td>\n\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t<td align='center'>{$inv['odate']}</td>\n\t\t\t\t\t<td>{$inv['cusname']} {$inv['surname']}</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$total}</td>";
            if (round($inv['total'], 0) != round($inv['nbal'], 0)) {
                $posInv .= "\n\t\t\t\t\t<td><a href='pos-invoice-note.php?invid={$inv['invid']}&prd={$prd}'>Credit Note</a></td>";
            } else {
                $posInv .= "\n\t\t\t\t\t<td><br></td>";
            }
            $posInv .= "\n\t\t\t\t\t<td><a target='_blank' href='pos-invoice-details-prd.php?invid={$inv['invid']}&prd={$prd}'>Details</a></td>\n\t\t\t\t\t<td><a target='_blank' href='pos-invoice-reprint-prd.php?invid={$inv['invid']}&prd={$prd}'>Reprint</a></td>\n\t\t\t\t\t<td><a target='_blank' href='pos-slip.php?invid={$inv['invid']}&prd={$prd}'>Slip</a></td>\n\t\t\t\t</tr>";
            $i++;
        }
        return $posInv;
    }
    #############################################[ /PROCESSED POS INVOICES ]###################################################
    #############################################[ /NON STOCK INVOICES ]###################################################
    # Set up table to display in
    $nonsOrd = "\n\t\t<h3>Non-Stock Invoices</h3>\n\t\t<tr>\n\t\t\t<th>Invoice Num</th>\n\t\t\t<th>Proforma Inv No.</th>\n\t\t\t<th>Invoice Date</th>\n\t\t\t<th>Customer</th>\n\t\t\t<th>Total</th>\n\t\t\t<th>Documents</th>\n\t\t\t<th colspan=6>Options</th>\n\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot_subtot = 0;
    $tot_total = 0;
    $sql = "SELECT * FROM nons_invoices WHERE typ = 'inv' AND invnum = '{$invnum}' OR invid = '{$invnum}' AND div = '" . USER_DIV . "' AND balance > 0 ORDER BY invnum";
    $nonstksRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($nonstksRslt) < 1) {
        $nonsOrd = "<li class='err'> No Non Stock Invoices Found.</li>";
    }
    // Retrieve the PDF reprints
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='reprints' AND div='" . USER_DIV . "'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    while ($nonstks = pg_fetch_array($nonstksRslt)) {
        // compute the totals
        if ($nonstks["xrate"] == 0.0) {
            $tot_subtot += $nonstks["subtot"];
            $tot_total += $nonstks["total"];
        } else {
            $tot_subtot += $nonstks["subtot"] * $nonstks["xrate"];
            $tot_total += $nonstks["total"] * $nonstks["xrate"];
        }
        # calculate the Sub-Total
        if ($nonstks['invnum'] == 0) {
            $nonstks['invnum'] = $nonstks['invid'];
        }
        $det = "nons-invoice-det.php";
        $edit = "nons-invoice-new.php";
        $print = "nons-invoice-print.php";
        $reprint = "nons-invoice-reprint.php";
        $note = "nons-invoice-note.php";
        if ($template == "default") {
            $template = "nons-invoice-pdf-reprint.php";
        } elseif ($template == "new") {
            $template = "pdf-tax-invoice.php";
        }
        $reprpdf = $template;
        $cur = CUR;
        if ($nonstks['location'] == 'int') {
            $det = "nons-intinvoice-det.php";
            $edit = "nons-intinvoice-new.php";
            $print = "nons-intinvoice-print.php";
            $note = "nons-intinvoice-note.php";
            if ($template == "default") {
                $template = "nons-intinvoice-pdf-reprint.php";
            } elseif ($template == "new") {
                $template = "pdf-tax-invoice.php";
            }
            $reprpdf = $template;
            $note = "nons-intinvoice-note.php";
            $cur = $nonstks['currency'];
        }
        # Get documents
        $docs = doclib_getdocs("ninv", $nonstks['invnum']);
        if ($nonstks['accepted'] == " " && $nonstks['done'] != "y") {
            $chbox = "<input type='checkbox' name='evs[{$nonstks['invid']}]' value='{$nonstks['invid']}' checked='yes'>";
        } else {
            $chbox = "";
        }
        $nonsOrd .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$nonstks['invnum']}</td>\n\t\t\t\t<td>{$nonstks['docref']}</td>\n\t\t\t\t<td>{$nonstks['odate']}</td>\n\t\t\t\t<td>{$nonstks['cusname']}</td>\n\t\t\t\t<td align='right'>{$cur} {$nonstks['total']}</td>\n\t\t\t\t<td>{$docs}</td>\n\t\t\t\t<td>{$chbox}</td>\n\t\t\t\t<td><a href='{$det}?invid={$nonstks['invid']}'>Details</a></td>";
        if ($nonstks['done'] != "y" && $nonstks["subtot"] == 0) {
            $nonsOrd .= "\n\t\t\t\t\t<td><a href='{$edit}?invid={$nonstks['invid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t<td><a href='?key=delete_confirm&invid={$nonstks['invid']}'>Delete</a></td>\n\t\t\t\t</tr>";
        } elseif ($nonstks['done'] != "y") {
            $nonsOrd .= "\n\t\t\t\t\t<td><a href='{$edit}?invid={$nonstks['invid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t<td><a href='?key=delete_confirm&invid={$nonstks['invid']}'>Delete</a></td>\n\t\t\t\t\t<td><a href=# onClick=printer('{$print}?invid={$nonstks['invid']}&type=nons')>Process</a></td>\n\t\t\t\t</tr>";
        } else {
            $cn = "";
            if ($nonstks['accepted'] != "note") {
                if (isset($mode) && $mode == "creditnote") {
                    $cn = "<input type='button' onClick=\"printer('{$note}?invid={$nonstks['invid']}&type=nonsnote');\" value='Credit Note'>";
                } else {
                    $cn = "<a href='#' onClick=printer('{$note}?invid={$nonstks['invid']}&type=nonsnote')>Credit Note</a>";
                }
            }
            $nonsOrd .= "\n\t\t\t\t\t<td>{$cn}</td>\n\t\t\t\t\t<td><a href='#' onClick=printer('{$reprint}?invid={$nonstks['invid']}&type=nonsreprint')>Reprint</a></td>\n\t\t\t\t\t<td><a href='pdf/{$reprpdf}?invid={$nonstks['invid']}&type=nonsreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t</tr>";
        }
        return $nonsOrd;
    }
    #############################################[ /NON STOCK INVOICES ]###################################################
    ############################################[ PAID NON STOCK INVOICES ]################################################
    $paidnonsOrd = "\n\t\t<h3>Paid Non-Stock Invoices</h3>\n\t\t<tr>\n\t\t\t<th>Invoice Num</th>\n\t\t\t<th>Proforma Inv No.</th>\n\t\t\t<th>Invoice Date</th>\n\t\t\t<th>Customer</th>\n\t\t\t<th>Total</th>\n\t\t\t<th>Documents</th>\n\t\t\t<th colspan='6'>Options</th>\n\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot_subtot = 0;
    $tot_total = 0;
    $sql = "SELECT * FROM nons_invoices WHERE typ = 'inv' AND invnum = '{$invnum}' OR invid = '{$invnum}' AND div = '" . USER_DIV . "' AND balance = 0 AND done = 'y' ORDER BY invnum";
    $nonstksRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($nonstksRslt) < 1) {
        $paidnonsOrd = "<li> There are no non stock invoices found.</li>";
    }
    // Retrieve the PDF reprints
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='reprints' AND div='" . USER_DIV . "'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    while ($nonstks = pg_fetch_array($nonstksRslt)) {
        # date format
        $date = explode("-", $nonstks['odate']);
        $date = $date[2] . "-" . $date[1] . "-" . $date[0];
        // compute the totals
        if ($nonstks["xrate"] == 0.0) {
            $tot_subtot += $nonstks["subtot"];
            $tot_total += $nonstks["total"];
        } else {
            $tot_subtot += $nonstks["subtot"] * $nonstks["xrate"];
            $tot_total += $nonstks["total"] * $nonstks["xrate"];
        }
        if ($nonstks['invnum'] == 0) {
            $nonstks['invnum'] = $nonstks['invid'];
        }
        $det = "nons-invoice-det.php";
        $edit = "nons-invoice-new.php";
        $print = "nons-invoice-print.php";
        $reprint = "nons-invoice-reprint.php";
        $note = "nons-invoice-note.php";
        if ($template == "default") {
            $template = "nons-invoice-pdf-reprint.php";
        } elseif ($template == "new") {
            $template = "pdf-tax-invoice.php";
        }
        $reprpdf = $template;
        $cur = CUR;
        if ($nonstks['location'] == 'int') {
            $det = "nons-intinvoice-det.php";
            $edit = "nons-intinvoice-new.php";
            $print = "nons-intinvoice-print.php";
            $note = "nons-intinvoice-note.php";
            if ($template == "default") {
                $template = "nons-intinvoice-pdf-reprint.php";
            } elseif ($template == "new") {
                $template = "pdf-tax-invoice.php";
            }
            $reprpdf = $template;
            $note = "nons-intinvoice-note.php";
            $cur = $nonstks['currency'];
        }
        # Get documents
        $docs = doclib_getdocs("ninv", $nonstks['invnum']);
        if ($nonstks['accepted'] == " " && $nonstks['done'] != "y") {
            $chbox = "<input type=checkbox name='evs[{$nonstks['invid']}]' value='{$nonstks['invid']}' checked=yes>";
        } else {
            $chbox = "";
        }
        $paidnonsOrd .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$nonstks['invnum']}</td>\n\t\t\t\t<td>{$nonstks['docref']}</td>\n\t\t\t\t<td>{$date}</td>\n\t\t\t\t<td>{$nonstks['cusname']}</td>\n\t\t\t\t<td align=right>{$cur} {$nonstks['total']}</td>\n\t\t\t\t<td>{$docs}</td>\n\t\t\t\t<td>{$chbox}</td>\n\t\t\t\t<td><a href='{$det}?invid={$nonstks['invid']}'>Details</a></td>";
        if ($nonstks['done'] != "y" && $nonstks["subtot"] == 0) {
            $paidnonsOrd .= "\n\t\t\t\t\t<td><a href='{$edit}?invid={$nonstks['invid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t<td><a href='?key=delete_confirm&invid={$nonstks['invid']}'>Delete</a></td>\n\t\t\t\t</tr>";
        } elseif ($nonstks['done'] != "y") {
            $paidnonsOrd .= "\n\t\t\t\t\t<td><a href='{$edit}?invid={$nonstks['invid']}&cont=1'>Edit</a></td>\n\t\t\t\t\t<td><a href='?key=delete_confirm&invid={$nonstks['invid']}'>Delete</a></td>\n\t\t\t\t\t<td><a href=# onClick=printer('{$print}?invid={$nonstks['invid']}&type=nons')>Process</a></td>\n\t\t\t\t</tr>";
        } else {
            $cn = "";
            $paidnonsOrd .= "\n\t\t\t\t\t<td>{$cn}</td>\n\t\t\t\t\t<td><a target='_blank' href='{$reprint}?invid={$nonstks['invid']}&type=nonsreprint'>Reprint</a></td>\n\t\t\t\t\t<td><a href='pdf/{$reprpdf}?invid={$nonstks['invid']}&type=nonsreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t\t<td><input type='checkbox' name='evs[{$nonstks['invid']}]'></td>\n\t\t\t\t</tr>";
        }
        return $paidnonsOrd;
    }
    ############################################[ /PAID NON STOCK INVOICES ]################################################
    ##########################################[ INCOMPLETE NON STOCK INVOICES ]#############################################
    $unfnonsOrd = "\n\t\t<h3>Incomplete Non-Stock Invoices</h3>\n\t\t<tr>\n\t\t\t<th>Invoice Num</th>\n\t\t\t<th>Proforma Inv No.</th>\n\t\t\t<th>Invoice Date</th>\n\t\t\t<th>Customer</th>\n\t\t\t<th>Total</th>\n\t\t\t<th colspan='2'>Options</th>\n\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot_subtot = 0;
    $tot_total = 0;
    $sql = "SELECT * FROM nons_invoices WHERE typ = 'inv' AND div = '" . USER_DIV . "' AND invnum = '{$invnum}' OR invid = '{$invnum}' AND done = 'n' ORDER BY invnum";
    $nonstksRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    if (pg_numrows($nonstksRslt) < 1) {
        $unfnonsOrd = "<li> There are no incomplete non stock invoices found.</li>";
    }
    while ($nonstks = pg_fetch_array($nonstksRslt)) {
        # date format
        $date = explode("-", $nonstks['sdate']);
        $date = $date[2] . "-" . $date[1] . "-" . $date[0];
        // compute the totals
        if ($nonstks["xrate"] == 0.0) {
            $tot_subtot += $nonstks["subtot"];
            $tot_total += $nonstks["total"];
        } else {
            $tot_subtot += $nonstks["subtot"] * $nonstks["xrate"];
            $tot_total += $nonstks["total"] * $nonstks["xrate"];
        }
        # calculate the Sub-Total
        if ($nonstks['invnum'] == 0) {
            $nonstks['invnum'] = $nonstks['invid'];
        }
        if (isset($nonstks['multiline']) and $nonstks['multiline'] == "yes") {
            $edit = "nons-multiline-invoice-new.php";
        } else {
            $edit = "nons-invoice-new.php";
        }
        $cur = CUR;
        $unfnonsOrd .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$nonstks['invnum']}</td>\n\t\t\t\t<td>{$nonstks['docref']}</td>\n\t\t\t\t<td>{$date}</td>\n\t\t\t\t<td>{$nonstks['cusname']}</td>\n\t\t\t\t<td align='right'>{$cur} {$nonstks['total']}</td>\n\t\t\t\t<td><a href='{$edit}?invid={$nonstks['invid']}&cont=1'>Continue</a></td>\n\t\t\t</tr>";
        return $unfnonsOrd;
    }
    ##########################################[ /INCOMPLETE NON STOCK INVOICES ]############################################
}