function display()
{
    extract($_REQUEST);
    $fields = array();
    $fields["from_year"] = date("Y");
    $fields["from_month"] = date("m");
    $fields["from_day"] = "01";
    $fields["to_year"] = date("Y");
    $fields["to_month"] = date("m");
    $fields["to_day"] = date("d");
    extract($fields, EXTR_SKIP);
    $from_date = "{$from_year}-{$from_month}-{$from_day}";
    $to_date = "{$to_year}-{$to_month}-{$to_day}";
    $sql = "SELECT assets_hired.invnum, surname, des, assets_hired.invid,\r\n\t\t\t\textract('epoch' FROM hired_time) AS e_hired,\r\n\t\t\t\textract('epoch' FROM return_time) AS e_return\r\n\t\t\tFROM hire.assets_hired\r\n\t\t\t\tLEFT JOIN hire.notes_reprint\r\n\t\t\t\t\tON assets_hired.invid=notes_reprint.invid\r\n\t\t\t\tLEFT JOIN cubit.customers\r\n\t\t\t\t\tON assets_hired.cust_id=customers.cusnum\r\n\t\t\t\tLEFT JOIN cubit.assets\r\n\t\t\t\t\tON assets_hired.asset_id=assets.id\r\n\t\t\tWHERE hired_time BETWEEN '{$from_date} 0:00:00' AND '{$to_date} 23:59:59' OR\r\n\t\t\t\treturn_time BETWEEN '{$from_date} 0:00:00' AND '{$to_date} 23:59:59'\r\n\t\t\tORDER BY invnum DESC";
    $history_rslt = db_exec($sql) or errDie("Unable to retrieve history.");
    $history_out = "";
    while ($history_data = pg_fetch_array($history_rslt)) {
        if ($history_data["e_return"]) {
            $return = date("d-m-Y", $history_data["e_return"]);
        } else {
            $return = "Still on Hire";
        }
        $history_out .= "\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>H" . getHirenum($history_data["invid"], 1) . "</td>\r\n\t\t\t<td>{$history_data['surname']}</td>\r\n\t\t\t<td>{$history_data['des']}</td>\r\n\t\t\t<td>" . date("d-m-Y", $history_data["e_hired"]) . "</td>\r\n\t\t\t<td>{$return}</td>\r\n\t\t</tr>";
    }
    if (empty($history_out)) {
        $history_out = "\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td colspan='5'><li>No results found</li></td>\r\n\t\t</tr>";
    }
    $OUTPUT = "<center>\r\n\t<h3>Hire History Report</h3>\r\n\t<form method='post' action='" . SELF . "'>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr><th colspan='4'>Date Range</th></tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>" . mkDateSelect("from", $from_year, $from_month, $from_day) . "</td>\r\n\t\t\t<td>&nbsp; <b>To</b> &nbsp;</td>\r\n\t\t\t<td>" . mkDateSelect("to", $to_year, $to_month, $to_day) . "</td>\r\n\t\t\t<td>\r\n\t\t\t\t<input type='submit' value='Select' style='font-weight: bold' />\r\n\t\t\t</td>\r\n\t\t</tr>\r\n\t</table>\r\n\t</form>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th>Hire No</th>\r\n\t\t\t<th>Company / Name</th>\r\n\t\t\t<th>Product</th>\r\n\t\t\t<th>Date Hired</th>\r\n\t\t\t<th>Date Returned</th>\r\n\t\t</tr>\r\n\t\t{$history_out}\r\n\t</table>";
    return $OUTPUT;
}
function display()
{
    extract($_REQUEST);
    $fields = array();
    $fields["from_year"] = date("Y");
    $fields["from_month"] = date("m");
    $fields["from_day"] = "01";
    $fields["to_year"] = date("Y");
    $fields["to_month"] = date("m");
    $fields["to_day"] = date("d");
    extract($fields, EXTR_SKIP);
    $from_date = "{$from_year}-{$from_month}-{$from_day}";
    $to_date = "{$to_year}-{$to_month}-{$to_day}";
    // Retrieve invoices
    $sql = "SELECT * FROM hire.hire_invoices WHERE done='y'\r\n\t\t\t\tAND odate BETWEEN '{$from_date}' AND '{$to_date}'";
    $inv_rslt = db_exec($sql) or errDie("Unable to retrieve invoices.");
    $hires_out = "";
    while ($inv_data = pg_fetch_array($inv_rslt)) {
        // Retrieve customer
        $sql = "SELECT * FROM cubit.customers WHERE cusnum='{$inv_data['cusnum']}'";
        $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customers.");
        $cust_data = pg_fetch_array($cust_rslt);
        $hires_out .= "<tr class='" . bg_class() . "'>\r\n\t\t\t<td>{$inv_data['odate']}</td>\r\n\t\t\t<td align='center'>\r\n\t\t\t\t<a href='hire-invoice-new.php?invid={$inv_data['invid']}'>\r\n\t\t\t\t\tH" . getHirenum($inv["invid"], 1) . "\r\n\t\t\t\t</a>\r\n\t\t\t</td>\r\n\t\t\t<td>{$cust_data['surname']}</td>\r\n\t\t\t<td>" . CUR . "{$inv_data['total']}</td>\r\n\t\t\t<!--<td><a href='hires_return.php?invid={$inv_data['invid']}'>Return</a></td>-->\r\n\t\t\t<!--<td><a href='hires_swap.php?invid={$inv_data['invid']}'>Swap</a></td>-->\r\n\t\t</tr>";
    }
    if (empty($hires_out)) {
        $hires_out = "<tr class='" . bg_class() . "'>\r\n\t\t\t<td colspan='5'>No hire notes found for this date range.</td>\r\n\t\t</tr>";
    }
    $OUTPUT = "<center>\r\n\t<h3>Hire Report</h3>\r\n\t<form method='post' action='" . SELF . "'>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th colspan='4'>Date Range</th>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>" . mkDateSelect("from", $from_year, $from_month, $from_day) . "</td>\r\n\t\t\t<td><b> To </b></td>\r\n\t\t\t<td>" . mkDateSelect("to", $to_year, $to_month, $to_day) . "</td>\r\n\t\t\t<td><input type='submit' value='Select' style='font-weight: bold' /></td>\r\n\t\t</tr>\r\n\t</table>\r\n\t</form>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<td colspan='5'>{$msg}</td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<th>Date</th>\r\n\t\t\t<th>Hire No</td>\r\n\t\t\t<th>Customer</th>\r\n\t\t\t<th>Total</th>\r\n\t\t\t<!--<th colspan='2'>Options</th>-->\r\n\t\t</tr>\r\n\t\t{$hires_out}\r\n\t</table>\r\n\t</center>";
    return $OUTPUT;
}
function display()
{
    extract($_REQUEST);
    $fields = array();
    $fields["search"] = "";
    $fields["type_id"] = 0;
    $fields["from_year"] = date("Y");
    $fields["from_month"] = date("m");
    $fields["from_day"] = date("d");
    $fields["to_year"] = date("Y");
    $fields["to_month"] = date("m");
    $fields["to_day"] = date("t");
    extract($fields, EXTR_SKIP);
    if ($type_id) {
        $type_sql = "AND assets.type_id='{$type_id}'";
    } else {
        $type_sql = "";
    }
    $sql = "SELECT qty, des, serial, customers.cusnum, customers.cusname,\r\n\t\t\t\tcustomers.surname, to_date, invnum, hire_invitems.invid,\r\n\t\t\t\thire_invitems.id, done, printed, grpname, name\r\n\t\t\t\tFROM hire.hire_invitems\r\n\t\t\t\t\tLEFT JOIN cubit.assets\r\n\t\t\t\t\t\tON hire_invitems.asset_id = assets.id\r\n\t\t\t\t\tLEFT JOIN hire.hire_invoices\r\n\t\t\t\t\t\tON hire_invitems.invid = hire_invoices.invid\r\n\t\t\t\t\tLEFT JOIN cubit.customers\r\n\t\t\t\t\t\tON hire_invoices.cusnum = customers.cusnum\r\n\t\t\t\t\tLEFT JOIN cubit.assetgrp\r\n\t\t\t\t\t\tON assets.grpid=assetgrp.grpid\r\n\t\t\t\t\tLEFT JOIN cubit.asset_types\r\n\t\t\t\t\t\tON assets.type_id=asset_types.id\r\n\t\t\t\tWHERE done='y' {$type_sql} AND remaction IS NULL AND\r\n\t\t\t\t\tprinted='y' AND (cast(qty as text) ILIKE '%{$search}%' OR\r\n\t\t\t\t\tserial ILIKE '%{$search}%' OR\r\n\t\t\t\t\tcustomers.cusname ILIKE '{$search}%' OR\r\n\t\t\t\t\tcustomers.surname ILIKE '{$search}%' OR\r\n\t\t\t\t\tcast(to_date as text) ILIKE '%{$search}%' OR\r\n\t\t\t\t\tcast(invnum as text) ILIKE '%{$search}%'\r\n\t\t\t\t\tOR grpname ILIKE '%{$search}%' OR name ILIKE '%{$search}%')\r\n\t\t\t\tORDER BY des ASC";
    $asset_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
    $sql = "SELECT id, name FROM cubit.asset_types";
    $type_rslt = db_exec($sql) or errDie("Unable to retrieve asset types.");
    $type_sel = "<select name='type_id' onchange='javascript:document.form.submit()'\r\n\t\t\t\t  style='width: 100%'>";
    $type_sel .= "<option value='0'>[All]</option>";
    while ($type_data = pg_fetch_array($type_rslt)) {
        if ($type_data["id"] == $type_id) {
            $sel = "selected='t'";
        } else {
            $sel = "";
        }
        $type_sel .= "\r\n\t\t<option value='{$type_data['id']}' {$sel}>\r\n\t\t\t{$type_data['name']}\r\n\t\t</option>";
    }
    $type_sel .= "</select>";
    $hired_out = "";
    while ($asset_data = pg_fetch_array($asset_rslt)) {
        $hired_out .= "<tr class='" . bg_class() . "'>\r\n\t\t\t<td align='center'>\r\n\t\t\t\t<a href='javascript:popupOpen" . "(\"hire-invoice-new.php?invid={$asset_data['invid']}\")'>\r\n\t\t\t\t\tH" . getHirenum($asset_data["invid"], 1) . "\r\n\t\t\t\t</a>\r\n\t\t\t</td>\r\n\t\t\t<td>{$asset_data['grpname']}</td>\r\n\t\t\t<td>{$asset_data['name']}</td>\r\n\t\t\t<td>{$asset_data['des']}</td>\r\n\t\t\t<td>{$asset_data['serial']}</td>\r\n\t\t\t<td align='center'>{$asset_data['qty']}</td>\r\n\t\t\t<td>{$asset_data['cusname']} {$asset_data['surname']}</td>\r\n\t\t\t<td align='center'>" . returnDate($asset_data["id"]) . "</td>\r\n\t\t</tr>";
    }
    // Display something atleast, even though we've got no results.
    if (empty($hired_out)) {
        $hired_out = "<tr class='" . bg_class() . "'>\r\n\t\t\t<td colspan='8'><li>No results found.</li></td>\r\n\t\t</tr>";
    }
    // Available assets -------------------------------------------------------
    $sql = "SELECT grpname, name, des, assets.id, serial2\r\n\t\t\tFROM cubit.assets\r\n\t\t\t\tLEFT JOIN cubit.assetgrp ON assets.grpid=assetgrp.grpid\r\n\t\t\t\tLEFT JOIN cubit.asset_types ON assets.type_id=asset_types.id\r\n\t\t\tWHERE remaction is NULL AND (grpname ILIKE '%{$search}%' OR\r\n\t\t\t\tname ILIKE '%{$search}%' OR des ILIKE '%{$search}%') {$type_sql}\r\n\t\t\tORDER BY des ASC";
    $asset_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
    $available_out = "";
    while ($asset_data = pg_fetch_array($asset_rslt)) {
        if (isHired($asset_data["id"])) {
            continue;
        }
        $available_out .= "\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>{$asset_data['grpname']}</td>\r\n\t\t\t<td>{$asset_data['name']}</td>\r\n\t\t\t<td>{$asset_data['des']}</td>\r\n\t\t\t<td>" . getSerial($asset_data["id"]) . "</td>\r\n\t\t\t<td>" . getUnits($asset_data["id"]) . "</td>\r\n\t\t</tr>";
    }
    if (empty($available_out)) {
        $available_out = "<tr class='" . bg_class() . "'>\r\n\t\t\t<td colspan='5'><li>No results found.</li></td>\r\n\t\t</tr>";
    }
    $OUTPUT = "<center>\r\n\t<h3>Asset Report</th>\r\n\t<br /><br />\r\n\t<form method='post' action='" . SELF . "' name='form'>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th colspan='4'>Date Range</th>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>" . mkDateSelect("from", $from_year, $from_month, $from_day) . "</td>\r\n\t\t\t<td>&nbsp; <b>To</b> &nbsp;</td>\r\n\t\t\t<td>" . mkDateSelect("to", $to_year, $to_month, $to_day) . "</td>\r\n\t\t\t<td><input type='submit' value='Select' /></td>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'><td colspan='4' align='center'>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr>\r\n\t\t\t\t<th colspan='2'>Search</th>\r\n\t\t\t\t<th>Asset Type</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td><input type='text' name='search' value='{$search}' /></td>\r\n\t\t\t\t<td><input type='submit' value='Search' /></td>\r\n\t\t\t\t<td>{$type_sel}</td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t\t</td></tr>\r\n\t</table>\r\n\t</form>\r\n\t<h3>Hired Out</h3>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th>Hire No</th>\r\n\t\t\t<th>Asset Group</th>\r\n\t\t\t<th>Asset Type</th>\r\n\t\t\t<th>Asset</th>\r\n\t\t\t<th>Serial</th>\r\n\t\t\t<th>Qty</th>\r\n\t\t\t<th>Customer</th>\r\n\t\t\t<th>Expected Return</th>\r\n\t\t</tr>\r\n\t\t{$hired_out}\r\n\t</table>\r\n\t<h3>Available</h3>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th>Asset Group</th>\r\n\t\t\t<th>Asset Type</th>\r\n\t\t\t<th>Asset</th>\r\n\t\t\t<th>Serial</th>\r\n\t\t\t<th>Qty</th>\r\n\t\t</tr>\r\n\t\t{$available_out}\r\n\t</table>";
    return $OUTPUT;
}
function display()
{
    extract($_REQUEST);
    $fields = array();
    $fields["date_year"] = date("Y");
    $fields["date_month"] = date("m");
    $fields["date_day"] = date("d");
    extract($fields, EXTR_SKIP);
    $date = dateFmt($date_year, $date_month, $date_day);
    for ($i = 0; $i < 2; $i++) {
        if ($i) {
            $collection = "collect";
        } else {
            $collection = "deliver";
        }
        $sql = "SELECT * FROM hire.collection\r\n\t\t\t\tWHERE {$collection}='1'\r\n\t\t\t\t\tAND time BETWEEN '{$date} 0:00:00' AND '{$date} 23:59:59'";
        $clct_rslt = db_exec($sql) or errDie("Unable to retrieve collection.");
        while ($clct_data = pg_fetch_array($clct_rslt)) {
            if (!$clct_data["item_id"]) {
                continue;
            }
            $sql = "SELECT * FROM cubit.assets WHERE id='{$clct_data['asset_id']}'";
            $asset_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
            $sql = "SELECT * FROM hire.hire_invitems WHERE id='{$clct_data['item_id']}'";
            $item_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
            $item_data = pg_fetch_array($item_rslt);
            if (empty($item_data["invid"])) {
                continue;
            }
            $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$item_data['invid']}'";
            $inv_rslt = db_exec($sql) or errDie("Unable to retrieve invoices.");
            $inv_data = pg_fetch_array($inv_rslt);
            while ($asset_data = pg_fetch_array($asset_rslt)) {
                ${$collection} .= "<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>H" . getHirenum($inv_data["invid"], 1) . "</td>\r\n\t\t\t\t\t<td>{$asset_data['des']}</td>\r\n\t\t\t\t\t<td>{$inv_data['cusname']} {$inv_data['surname']}</td>\r\n\t\t\t\t\t<td>" . hireAddress($inv_data["invid"]) . "</td>\r\n\t\t\t\t\t<td>" . getSerial($asset_data["id"]) . "</td>\r\n\t\t\t\t</tr>";
            }
        }
        if (empty(${$collection})) {
            ${$collection} = "<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td colspan='5'><li>No results found.</li></td>\r\n\t\t\t</tr>";
        }
    }
    $OUTPUT = "<center>\r\n\t<h3>Collect and Deliver Report</h3>\r\n\t<form method='post' action='" . SELF . "'>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr><th colspan='2'>Date</th></tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>" . mkDateSelect("date", $date_year, $date_month, $date_day) . "</td>\r\n\t\t\t<td><input type='submit' value='Select' style='font-weight: bold' /></td>\r\n\t\t</tr>\r\n\t</table>\r\n\t</form>\r\n\t<p></p>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th colspan='5'>Deliver</th>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<th>Hire No</th>\r\n\t\t\t<th>Asset</th>\r\n\t\t\t<th>Customer</th>\r\n\t\t\t<th>Address</th>\r\n\t\t\t<th>Serial</th>\r\n\t\t</tr>\r\n\t\t{$deliver}\r\n\t\t<tr>\r\n\t\t\t<th colspan='5'>Collect</th>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<th>Hire No</th>\r\n\t\t\t<th>Asset</th>\r\n\t\t\t<th>Customer</th>\r\n\t\t\t<th>Address</th>\r\n\t\t\t<th>Serial</th>\r\n\t\t</tr>\r\n\t\t{$collect}\r\n\t</table>\r\n\t</center>";
    return $OUTPUT;
}
function display()
{
    extract($_REQUEST);
    $fields = array();
    $fields["from_year"] = date("Y");
    $fields["from_month"] = date("m");
    $fields["from_day"] = "01";
    $fields["to_year"] = date("Y");
    $fields["to_month"] = date("m");
    $fields["to_day"] = date("d");
    $fields["print"] = 0;
    extract($fields, EXTR_SKIP);
    if (!$print) {
        $OUTPUT = "<center>\r\n\t\t<h3>Driver Collect/Deliver</h3>\r\n\t\t<form method='post' action='" . SELF . "'>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr><th colspan='4'>Date Range</th></tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>" . mkDateSelect("from", $from_year, $from_month, $from_day) . "</td>\r\n\t\t\t\t<td>&nbsp; <b>To</b> &nbsp;</td>\r\n\t\t\t\t<td>" . mkDateSelect("to", $to_year, $to_month, $to_day) . "</td>\r\n\t\t\t\t<td>\r\n\t\t\t\t\t<input type='submit' value='Select' style='font-weight: bold' />\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td colspan='4' align='center'>\r\n\t\t\t\t\t<input type='submit' name='print' value='Print' />\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t\t</form>";
    } else {
        $OUTPUT = "";
    }
    $sql = "\r\n\tSELECT hire_invoices.invid, hire_invitems.collection, customers.surname,\r\n\t\tinvnum, branch_addr, branch_descrip, addr1, bustel, cellno\r\n\t\tFROM hire.hire_invitems\r\n\t\t\tLEFT JOIN hire.hire_invoices\r\n\t\t\t\tON hire_invitems.invid=hire_invoices.invid\r\n\t\t\tLEFT JOIN cubit.customers\r\n\t\t\t\tON hire_invoices.cusnum=customers.cusnum\r\n\t\t\tLEFT JOIN cubit.customer_branches\r\n\t\t\t\tON customers.cusnum=customer_branches.cusnum";
    $item_rslt = db_exec($sql) or errDie("Unable to retrieve hire note items.");
    $item_out = "";
    while ($item_data = pg_fetch_array($item_rslt)) {
        // Parse collection
        $collection = explode(", ", $item_data["collection"]);
        foreach ($collection as $value) {
            if ($value == "Client Collect") {
                continue;
            }
            if ($item_data["branch_addr"]) {
                $address = nl2br($item_data["branch_descrip"]);
            } else {
                $address = nl2br($item_data["addr1"]);
            }
            $item_out .= "\r\n\t\t\t<table " . TMPL_tblDflts . " width='400' style='border: 1px solid #000'>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td><b>{$item_data['surname']}</b></td>\r\n\t\t\t\t\t<td>" . ucfirst($value) . "</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Hire No: H" . getHirenum($item_data["invid"], 1) . "</td>\r\n\t\t\t\t\t<td>Date:_____________________</td>\r\n\t\t\t\t</td>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Business Tel: {$item_data['bustel']}</td>\r\n\t\t\t\t\t<td>Cell No: {$item_data['cellno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td colspan='2'>{$address}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td style='padding-top: 10px'>Signature (Driver)</td>\r\n\t\t\t\t\t<td>___________________________</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td style='padding-top: 10px'>Signature (Recipient)</td>\r\n\t\t\t\t\t<td>___________________________</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t<br />";
        }
    }
    $OUTPUT .= "{$item_out}";
    if ($print) {
        $OUTPUT = clean_html($OUTPUT);
        require "../tmpl-print.php";
    } else {
        return $OUTPUT;
    }
}
function report()
{
    extract($_REQUEST);
    $sql = "SELECT invnum, hire_invid, invid, surname, discount, total, cash\n\t\t\tFROM cubit.nons_invoices\n\t\t\t\tLEFT JOIN cubit.customers\n\t\t\t\t\tON nons_invoices.cusnum=customers.cusnum\n\t\t\tWHERE username='******' AND \n\t\t\t\tnons_invoices.odate='" . date("Y-m-d") . "'\n\t\t\t\tAND hire_invid>0 AND invnum>0";
    $items_rslt = db_exec($sql) or errDie("Unable to retrieve cash sales.");
    $items_out = "";
    $total = 0;
    while ($items_data = pg_fetch_array($items_rslt)) {
        $items_out .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>" . getHirenum($items_data["hire_invid"], 1) . "</td>\n\t\t\t<td>{$items_data['invnum']}</td>\n\t\t\t<td>{$items_data['surname']}</td>\n\t\t\t<td>{$items_data['discount']}</td>\n\t\t\t<td>{$items_data['total']}</td>\n\t\t\t<td align='right'>{$items_data['cash']}</td>\n\t\t</tr>";
        $total += $items_data["cash"];
    }
    $sql = "SELECT hire_invoices.invid AS hire_invid, invnum, inv_invid, cash, \n\t\t\t\tcustomers.surname, discount, total\n\t\t\tFROM hire.cash\n\t\t\t\tLEFT JOIN hire.hire_invoices ON hire_invoices.invid=cash.invid\n\t\t\t\tLEFT JOIN cubit.customers ON hire_invoices.cusnum=customers.cusnum\n\t\t\tWHERE date='" . date("Y-m-d") . "' AND username='******'";
    $items_rslt = db_exec($sql) or errDie("Unable to retrieve cash.");
    while ($items_data = pg_fetch_array($items_rslt)) {
        $items_out .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>" . getHirenum($items_data["hire_invid"], 1) . "</td>\n\t\t\t<td>{$items_data['invnum']}</td>\n\t\t\t<td>{$items_data['surname']}</td>\n\t\t\t<td>{$items_data['discount']}</td>\n\t\t\t<td>{$items_data['total']}</td>\n\t\t\t<td align='right'>{$items_data['cash']}</td>\n\t\t</tr>";
        $total += $items_data["cash"];
    }
    $OUTPUT = "<h3>Hire Cash Up</h3>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Hire No</th>\n\t\t\t<th>Invoice No</th>\n\t\t\t<th>Customer</th>\n\t\t\t<th>Discount</th>\n\t\t\t<th>Total</th>\n\t\t\t<th>Paid Cash</th>\n\t\t</tr>\n\t\t{$items_out}\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='5'><b>TOTAL</b>\n\t\t\t<td align='right'><b>" . sprint($total) . "</b></td>\n\t\t</tr>\n\t</table>";
    return $OUTPUT;
}
function enter()
{
    extract($_REQUEST);
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$_REQUEST['invid']}'";
    $inv_rslt = db_exec($sql) or errDie("Unable to retrieve invoices.");
    $inv_data = pg_fetch_array($inv_rslt);
    $sql = "SELECT * FROM cubit.customers WHERE cusnum='{$inv_data['cusnum']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customers.");
    $cust_data = pg_fetch_array($cust_rslt);
    $sql = "SELECT invid FROM hire.unsigned_hirenotes WHERE invid='{$invid}'";
    $uh_rslt = db_exec($sql) or errDie("Unable to retrieve unsinged hirenotes.");
    if (!pg_num_rows($uh_rslt)) {
        $sql = "INSERT INTO hire.unsigned_hirenotes (invid, trans_date, invnum,\r\n\t\t\t\t\tcusnum)\r\n\t\t\t\tVALUES ('{$inv_data['invid']}', '{$inv_data['odate']}',\r\n\t\t\t\t\t'" . getHirenum($inv_data["invid"]) . "', '{$inv_data['cusnum']}')";
        db_exec($sql) or errDie("Unable to create unsigned hire note.");
        $uh_id = pglib_lastid("hire.unsigned_hirenotes", "id");
    } else {
        $uh_id = pg_fetch_result($uh_rslt, 0);
    }
    $OUTPUT = "<h3>Signed Hire Note</h3>\r\n\t<form method='post' action='" . SELF . "' enctype='multipart/form-data'>\r\n\t<input type='hidden' name='key' value='write' />\r\n\t<input type='hidden' name='invid' value='{$invid}' />\r\n\t<input type='hidden' name='uh_id' value='{$uh_id}' />\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th colspan='2'>Details</th>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>Hire No.</td>\r\n\t\t\t<td>H" . getHirenum($inv_data["invid"], 1) . "</td>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>Customer</td>\r\n\t\t\t<td>{$cust_data['cusname']} {$cust_data['surname']}</td>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>Signed Hire Note</td>\r\n\t\t\t<td><input type='file' name='file' /></td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td colspan='2' align='right'>\r\n\t\t\t\t<input type='submit' value='Write &raquo' />\r\n\t\t\t</td>\r\n\t\t</tr>\r\n\t</table>\r\n\t</form>";
    return $OUTPUT;
}
function newHire($_POST)
{
    extract($_POST);
    // Remove booking if any
    $sql = "DELETE FROM hire.bookings WHERE id='{$bk_id}'";
    db_exec($sql) or errDie("Unable to remove booking.");
    $sql = "SELECT catname FROM cubit.customers WHERE cusnum='{$cusnum}'";
    $cat_rslt = db_exec($sql) or errDie("Unable to retrieve customers.");
    $category = pg_fetch_result($cat_rslt, 0);
    if ($deposit_type == "CSH" && $deposit_amt != "0.00") {
        $deposit_print = "popupOpen(\"hire-invoice-print.php?invid={$invid}&key=cash_receipt\");";
    } else {
        $deposit_print = "";
    }
    $invnum = getHirenum($invid);
    $sql = "UPDATE hire.monthly_invoices SET invnum='{$invnum}' WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to assign hire number to monthly items.");
    $sql = "UPDATE hire.monthly_invitems SET invnum='{$invnum}' WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to assign hire number to monthly items.");
    $sql = "UPDATE hire.hire_invoices SET timestamp=CURRENT_TIMESTAMP, invnum='{$invnum}' WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to update hire invoices.");
    $OUTPUT = "\r\n\t\t<script>\r\n\t\t\tmove(\"" . SELF . "\");\r\n\t\t\tprinter(\"hire/hire-invoice-print.php?invid={$invid}\");\r\n\t\t\tpopupSized(\"signed_hirenote_save.php?invid={$invid}\", \"1\", 500, 300);\r\n\t\t\t{$deposit_print}\r\n\t\t</script>";
    require "template.php";
    exit;
}
function display()
{
    extract($_REQUEST);
    define("HOUR", 60 * 60);
    define("DAY", HOUR * 24);
    define("WEEK", DAY * 7);
    define("TOMMOROW", time() + DAY);
    $fields = array();
    $fields["from_year"] = date("Y");
    $fields["from_month"] = date("m");
    $fields["from_day"] = date("d") <= 7 ? "01" : date("d") - 7;
    $fields["to_year"] = date("Y");
    $fields["to_month"] = date("m");
    $fields["to_day"] = date("d");
    $fields["total_invoiced"] = 0;
    $fields["total_not_invoiced"] = 0;
    extract($fields, EXTR_SKIP);
    $from_time = mktime(0, 0, 0, $from_month, $from_day, $from_year);
    $to_time = mktime(0, 0, 0, $to_month, $to_day, $to_year);
    $from_date = date("Y-m-d", $from_time);
    $to_date = date("Y-m-d", $to_time);
    // Make sure the date selection is not the same
    if ($from_date == $to_date) {
        $to_date = date("Y-m-d", TOMMOROW);
    }
    $OUTPUT = "\r\n\t\t<center>\r\n\t\t<style>\r\n\t\t\ttd, th { font-size: 0.7em; }\r\n\t\t</style>\r\n\t\t<h3>Hire by Period Detail Report</h3>\r\n\t\t<form method='POST' action='" . SELF . "'>\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr>\r\n\t\t\t\t<th colspan='4'>Date Range</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td>" . mkDateSelect("from", $from_year, $from_month, $from_day) . "</td>\r\n\t\t\t\t<td>&nbsp; <b>To</b> &nbsp;</td>\r\n\t\t\t\t<td>" . mkDateSelect("to", $to_year, $to_month, $to_day) . "</td>\r\n\t\t\t\t<td><input type='submit' value='Select' style='font-weight: bold' /></td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t\t</form>";
    $sql = "SELECT assets_hired.id, invnum, assets.id AS asset_id, des, surname,\r\n\t\t\t\thired_time, return_time, inv_invnum, value, item_id, cust_id,\r\n\t\t\t\tassets.grpid, grpname, assets_hired.invid, qty, basis, weekends,\r\n\t\t\t\textract('epoch' FROM hired_time) AS e_hired,\r\n\t\t\t\textract('epoch' FROM return_time) AS e_return\r\n\t\t\tFROM hire.assets_hired\r\n\t\t\t\tLEFT JOIN cubit.assets ON assets_hired.asset_id=assets.id\r\n\t\t\t\tLEFT JOIN cubit.customers ON assets_hired.cust_id=customers.cusnum\r\n\t\t\t\tLEFT JOIN cubit.assetgrp ON assets.grpid=assetgrp.grpid\r\n\t\t\tWHERE\r\n\t\t\t\thired_time BETWEEN '{$from_date} 0:00:00' AND '{$to_date} 23:59:59'\r\n\t\t\t\tOR return_time BETWEEN '{$from_date} 0:00:00' AND '{$to_date} 23:59:59'\r\n\t\t\t\tOR (hired_time BETWEEN '{$from_date} 0:00:00' AND '{$to_date} 23:59:59'\r\n\t\t\t\t\tAND return_time IS NULL)\r\n\t\t\tORDER BY invid ASC";
    $details_rslt = db_exec($sql) or errDie("Unable to retrieve details.");
    $items_out = array();
    while ($details_data = pg_fetch_array($details_rslt)) {
        // Is this within one of the valid asset hire groups
        if (!preg_match("/(Equipment|Plant)/", $details_data["grpname"])) {
            continue;
        }
        if (!$details_data["inv_invnum"]) {
            $sql = "SELECT amt, basis, extract('epoch' FROM to_date) AS e_to\r\n\t\t\t\t\tFROM hire.hire_invitems\r\n\t\t\t\t\tWHERE id='{$details_data['item_id']}'";
            $item_rslt = db_exec($sql) or errDie("Unable to retrieve amount.");
            list($value, $basis, $e_to) = pg_fetch_array($item_rslt);
            $expected_disp = "";
            // Calculate the amounts for items not yet returned
            switch ($basis) {
                case "per_hour":
                    $hours_beyond_expected = ($to_time - $e_to) / HOUR;
                    if ($hours_beyond_expected) {
                        $basis_per_hour = basisPrice($details_data["cust_id"], $details_data["id"], $basis);
                        $value_beyond = $basis_per_day * $days_beyond_expected;
                        $details_data["value"] = $value + $value_beyond;
                    } else {
                        $details_data["value"] = $value;
                    }
                case "per_day":
                    $days_beyond_expected = $to_time - $e_to;
                    $sundays = 0;
                    for ($i = $details_data["e_hired"]; $i <= $days_beyond_expected; $i += 60 * 60 * 24) {
                        if (date("w", $i) == 0) {
                            $sundays++;
                        }
                    }
                    if ($details_data["weekends"]) {
                        $show_sundays = $sundays + 0.6 * $sundays;
                    } else {
                        $show_sundays = 0;
                    }
                    $days_beyond_expected /= DAY - $show_sundays;
                    if ($days_beyond_expected) {
                        $basis_per_day = basisPrice($details_data["cust_id"], $details_data["id"], $basis);
                        $value_beyond = $basis_per_day * $days_beyond_expected;
                        $details_data["value"] = $value + $value_beyond;
                    } else {
                        $details_data["value"] = $value;
                    }
                    break;
                case "per_week":
                    $weeks_beyond_expected = ($to_time - $e_to) / WEEK;
                    if ($weeks_beyond_expected) {
                        $basis_per_week = basis_price($details_data["cust_id"], $details_data["id"], $basis);
                        $value_beyond = $basis_per_day * $days_beyond_expected;
                        $details_data["value"] = $value + $value_beyond;
                    } else {
                        $details_data["value"] = $value;
                    }
                    break;
            }
            $total_not_invoiced += $details_data["value"];
        } else {
            $total_invoiced += $details_data["value"];
        }
        $total_hire = $total_invoiced + $total_not_invoiced;
        if (empty($details_data["return_time"])) {
            $return_disp = "\r\n\t\t\t<span style='color: #f00'>\r\n\t\t\t\t(Still on Hire) " . date("d-m-Y", $to_time) . "\r\n\t\t\t</span>";
        } else {
            $return_disp = date("d-m-Y G:i:s", $details_data["e_return"]);
        }
        // Units Days / Hours
        $days_hours = "";
        if ($details_data["basis"] == "per_day" || $details_data["basis"] == "per_week") {
            $days_hours = "DAY";
        } else {
            $days_hours = "HOUR";
        }
        // Invoiced / Forecasted
        if (!isset($totals[$details_data["grpid"]]["forecast"])) {
            $totals[$details_data["grpid"]]["forecast"] = 0.0;
        }
        if (!isset($totals[$details_data["grpid"]]["invoiced"])) {
            $totals[$details_data["grpid"]]["invoiced"] = 0.0;
        }
        if (empty($details_data["return_time"])) {
            $forecast_value = $details_data["value"];
            $invoiced_value = "";
            $totals[$details_data["grpid"]]["forecast"] += $details_data["value"];
        } else {
            $forecast_value = "";
            $invoiced_value = $details_data["value"];
            $totals[$details_data["grpid"]]["invoiced"] += $details_data["value"];
        }
        // Weekends
        if ($details_data["weekends"]) {
            $weekends = "w/e charge";
        } else {
            $weekends = "";
        }
        $sql = "\r\n\t\tSELECT qty FROM hire.hire_nons_inv_items\r\n\t\tWHERE invid='{$details_data['inv_invnum']}' AND\r\n\t\t\tasset_id='{$details_data['asset_id']}'";
        $invqty_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
        $invqty = pg_fetch_result($invqty_rslt, 0);
        if (empty($invqty)) {
            $invqty = 0;
        }
        $items_out[$details_data["grpid"]][] = "\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td align='center'>H" . getHirenum($details_data["invid"], 1) . "</td>\r\n\t\t\t\t<td align='center'>{$details_data['inv_invnum']}</td>\r\n\t\t\t\t<td align='center'>{$details_data['surname']}</td>\r\n\t\t\t\t<td>" . getSerial($details_data["asset_id"], 1) . " {$details_data['des']}</td>\r\n\t\t\t\t<td align='center'>{$days_hours}</td>\r\n\t\t\t\t<td>" . date("d-m-Y", $details_data["e_hired"]) . "</td>\r\n\t\t\t\t<td>" . returnDate($details_data["item_id"]) . "</td>\r\n\t\t\t\t<td align='right'>" . sprint($invoiced_value) . "</td>\r\n\t\t\t\t<td>{$weekends}</td>\r\n\t\t\t\t<td align='right'>" . sprint($forecast_value) . "</td>\r\n\t\t\t\t<!--\r\n\t\t\t\t<td align='center'>" . detailsHoursHired($details_data["id"]) . "</td>\r\n\t\t\t\t<td align='center'>" . detailsDaysHired($details_data["id"]) . "</td>\r\n\t\t\t\t<td align='center'>" . detailsWeeksHired($details_data["id"]) . "</td>\r\n\t\t\t\t<td align='center'>" . date("d-m-Y G:i:s", $details_data["e_hired"]) . "</td>\r\n\t\t\t\t<td align='center'>{$return_disp}</td>\r\n\t\t\t\t<td align='right'>" . sprint($details_data["value"]) . "</td>\r\n\t\t\t\t-->\r\n\t\t\t</tr>";
    }
    if (!count($items_out)) {
        $details_out = "\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td colspan='7'><li>No results found.</li></td>\r\n\t\t</tr>";
    }
    if (!isset($total_hire)) {
        $total_hire = 0;
    }
    $OUTPUT .= "\r\n\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t<tr>\r\n\t\t\t\t<th style='padding-right: 10px'>Total Invoiced Hire</th>\r\n\t\t\t\t<th style='padding-left: 10px'>Total Non Invoiced Hire</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td align='center'>" . sprint($total_invoiced) . "</td>\r\n\t\t\t\t<td align='center'>" . sprint($total_not_invoiced) . "</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<th colspan='2'>Total Hire</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td align='center' colspan='2'><b>" . sprint($total_hire) . "</b></td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t\t<br />";
    foreach ($items_out as $grpid => $lv2) {
        $sql = "SELECT grpname FROM cubit.assetgrp WHERE grpid='{$grpid}'";
        $group_rslt = db_exec($sql) or errDie("Unable to retrieve asset groups.");
        $group_name = pg_fetch_result($group_rslt, 0);
        $OUTPUT .= "<h3>{$group_name} Hire Revenue</h3>\r\n\t\t\t<table " . TMPL_tblDflts . " width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th>Hire Number</th>\r\n\t\t\t\t\t<th>Invoice Number</th>\r\n\t\t\t\t\t<th>Customer</th>\r\n\t\t\t\t\t<th>Asset</th>\r\n\t\t\t\t\t<th>Units Days / Hours</th>\r\n\t\t\t\t\t<th>Date Out</th>\r\n\t\t\t\t\t<th>Expect / Actual</th>\r\n\t\t\t\t\t<th>Rand (Ex VAT) Invoiced\r\n\t\t\t\t\t<th>&nbsp;</th>\r\n\t\t\t\t\t<th>Rand (Ex VAT) Forecast</th>\r\n\t\t\t\t\t<!--\r\n\t\t\t\t\t<th>Hours Hired</th>\r\n\t\t\t\t\t<th>Days Hired</th>\r\n\t\t\t\t\t<th>Weeks Hired</th>\r\n\t\t\t\t\t<th>Date Hired</th>\r\n\t\t\t\t\t<th>Date Returned</th>\r\n\t\t\t\t\t<th>Value (Ex VAT)</th>\r\n\t\t\t\t\t-->\r\n\t\t\t\t</tr>";
        foreach ($items_out[$grpid] as $line_disp) {
            $OUTPUT .= $line_disp;
        }
        $OUTPUT .= "</table>";
    }
    return $OUTPUT;
}
function reprint()
{
    extract($_REQUEST);
    // Retrieve the hire note
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$invid}'";
    $inv_rslt = db_exec($sql) or errDie("Unable to retrieve hire note.");
    $inv = pg_fetch_array($inv_rslt);
    $invnum = $inv["invnum"];
    $OUTPUT = "<center>\r\n\t<h2>Tax Invoice</h2>\r\n\t<table cellpadding='0' cellspacing='1' border=0 width=750>\r\n\t<tr><td valign=top width=40%>\r\n\t\t<table " . TMPL_tblDflts . " border=0>\r\n\t\t\t<tr><td>{$inv['surname']}</td></tr>\r\n\t\t</table>\r\n\t</td><td valign=top width=35%>\r\n\t\t" . COMP_NAME . "<br>\r\n\t\t" . COMP_ADDRESS . "<br>\r\n\t\t" . COMP_TEL . "<br>\r\n\t\t" . COMP_FAX . "<br>\r\n\t\tReg No. " . COMP_REGNO . "<br>\r\n\t</td><td valign=bottom align=right width=25%>\r\n\t\t<table cellpadding='2' cellspacing='0' border=1 bordercolor='#000000'>\r\n\t\t\t<tr><td><b>Hire No.</b></td><td valign=center>H" . getHirenum($inv["invid"], 1) . "</td></tr>\r\n\t\t\t<tr><td><b>Order No.</b></td><td valign=center>{$inv['ordno']}</td></tr>\r\n\t\t\t<tr><td><b>Terms</b></td><td valign=center>Cash</td></tr>\r\n\t\t\t<tr><td><b>Invoice Date</b></td><td valign=center>{$inv['odate']}</td></tr>\r\n\t\t\t<tr><td><b>VAT</b></td><td valign=center>{$inv['chrgvat']}</td></tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td><br></td></tr>\r\n\t<tr><td colspan=3>\r\n\t<table cellpadding='5' cellspacing='0' border=1 width=100% bordercolor='#000000'>\r\n\t\t<tr><th>ITEM NUMBER</th><th width=45%>DESCRIPTION</th><th>QTY</th><th>UNIT PRICE</th><th>AMOUNT</th><tr>\r\n\t\t{$products}\r\n\t</table>\r\n\t</td></tr>\r\n\t<tr><td>\r\n\t\t{$inv['custom_txt']}\r\n\t\t{$Com}\r\n\t</td><td align=right colspan=2>\r\n\t\t<table cellpadding='5' cellspacing='0' border=1 width=50% bordercolor='#000000'>\r\n\t\t\t<tr><td><b>SUBTOTAL</b></td><td align=right>" . CUR . " {$SUBTOT}</td></tr>\r\n\t\t\t<tr><td><b>Trade Discount</b></td><td align=right>" . CUR . " {$inv['discount']}</td></tr>\r\n\t\t\t<tr><td><b>Delivery Charge</b></td><td align=right>" . CUR . " {$inv['delivery']}</td></tr>\r\n\t\t\t<tr><td><b>VAT @ {$VATP}%</b></td><td align=right>" . CUR . " {$VAT}</td></tr>\r\n\t\t\t<tr><th><b>GRAND TOTAL<b></th><td align=right>" . CUR . " {$TOTAL}</td></tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td><br></td></tr>\r\n\t<tr><td>\r\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=1>\r\n\t\t\t<tr><td colspan=2>VAT Exempt indicator = #</td></tr>\r\n\t\t\t<tr><th>VAT No.</th><td align=center>" . COMP_VATNO . "</td></tr>\r\n        </table>\r\n\t</td><td><br></td></tr>\r\n\t</table></center>";
    require "../tmpl-print.php";
}
function display()
{
    extract($_REQUEST);
    $fields = array();
    $fields["from_year"] = date("Y");
    $fields["from_month"] = date("m");
    $fields["from_day"] = "01";
    $fields["to_year"] = date("Y");
    $fields["to_month"] = date("m");
    $fields["to_day"] = date("d");
    $fields["search"] = "~:BLANK:~";
    $fields["filter"] = "";
    $fields["rsearch"] = "";
    extract($fields, EXTR_SKIP);
    $from_date = dateFmt($from_year, $from_month, $from_day);
    $to_date = dateFmt($to_year, $to_month, $to_day);
    $filter_list = array("cust" => "Customers", "inv" => "Hire No");
    $filter_sel = "<select name='filter' style='width: 100%'>";
    foreach ($filter_list as $key => $value) {
        if ($filter == $key) {
            $sel = "selected='selected'";
        } else {
            $sel = "";
        }
        $filter_sel .= "<option value='{$key}' {$sel}>{$value}</option>";
    }
    $filter_sel .= "</select>";
    if (!empty($search) && $filter == "inv") {
        $nsearch = $search;
        if (!is_numeric($search)) {
            $nsearch = 0;
        }
        $rsearch = "AND invnum='{$nsearch}'";
    }
    if ($search == "~:BLANK:~") {
        $sql = "SELECT * FROM hire.hire_invoices\r\n\t\t\t\t\tWHERE done='haha notreally' and printed='youmustbekidding'";
        $search = "";
    } else {
        $sql = "SELECT * FROM hire.hire_invoices\r\n\t\t\t\tWHERE done='y' AND printed='y'\r\n\t\t\t\t\tAND odate BETWEEN '{$from_date}' AND '{$to_date}' {$rsearch}\r\n\t\t\t\tORDER BY odate DESC";
    }
    $hinv_rslt = db_exec($sql) or errDie("Unable to retrieve hire notes.");
    $notes_out = "";
    while ($hinv_data = pg_fetch_array($hinv_rslt)) {
        if (!empty($search) && $filter == "cust") {
            $sql = "SELECT * FROM cubit.customers\r\n\t\t\t\t\tWHERE cusname ILIKE '%{$search}%' OR surname ILIKE '%{$search}%'";
            $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customers.");
            if (!pg_num_rows($cust_rslt)) {
                continue;
            }
        }
        // Retrieve the customer
        $sql = "SELECT * FROM cubit.customers WHERE cusnum='{$hinv_data['cusnum']}'";
        $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
        $cust_data = pg_fetch_array($cust_rslt);
        // Check if we've got a signed hire note
        $sql = "SELECT * FROM hire.signed_hirenotes WHERE invid='{$hinv_data['invid']}'";
        $sh_rslt = db_exec($sql) or errDie("Unable to check for scanned hire note.");
        $sh_data = pg_fetch_array($sh_rslt);
        if (!pg_num_rows($sh_rslt)) {
            continue;
        }
        $notes_out .= "<tr class='" . bg_class() . "'>\r\n\t\t\t<td>{$hinv_data['odate']}</td>\r\n\t\t\t<td>H" . getHirenum($hinv_data["invid"], 1) . "</td>\r\n\t\t\t<td>{$cust_data['surname']} {$cust_data['cusname']}</td>\r\n\t\t\t<td>\r\n\t\t\t\t<a href='" . SELF . "?key=get&id={$sh_data['id']}'>\r\n\t\t\t\t\tSigned Hire Note\r\n\t\t\t\t</a>\r\n\t\t\t</td>\r\n\t\t</tr>";
    }
    if (empty($notes_out)) {
        $notes_out = "<tr class='" . bg_class() . "'>\r\n\t\t\t<td colspan='4'><li>No results, please enter a customer name or hire\r\n\t\t\tno.</li></td>\r\n\t\t</tr>";
    }
    $OUTPUT = "<center>\r\n\t<h3>Signed Hire Notes</h3>\r\n\t<form method='post' action='" . SELF . "'>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th colspan='4'>Date Range</th>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>" . mkDateSelect("from", $from_year, $from_month, $from_day) . "</td>\r\n\t\t\t<td><b> To </b></td>\r\n\t\t\t<td>" . mkDateSelect("to", $to_year, $to_month, $to_day) . "</td>\r\n\t\t\t<td><input type='submit' value='Select' style='font-weight: bold' /></td>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<th colspan='4'>Search</th>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td colspan='2'>\r\n\t\t\t\t<input type='text' name='search' value='{$search}' style='width: 100%;' />\r\n\t\t\t</td>\r\n\t\t\t<td>{$filter_sel}</td>\r\n\t\t\t<td><input type='submit' value='Search' style='font-weight: bold' /></td>\r\n\t\t</tr>\r\n\t</table>\r\n\t</form>\r\n\t<p></p>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th>Date</th>\r\n\t\t\t<th>Hire No</th>\r\n\t\t\t<th>Customer</th>\r\n\t\t\t<th>Options</th>\r\n\t\t</tr>\r\n\t\t{$notes_out}\r\n\t</table>\r\n\t</center>";
    return $OUTPUT;
}
function cwrite($_GET)
{
    $showvat = TRUE;
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    if (isset($ctyp) && $ctyp == 's') {
        $v->isOk($cusnum, "num", 1, 20, "Invalid customer number.");
    } elseif (isset($ctyp) && $ctyp == 'c') {
        $v->isOk($deptid, "num", 1, 20, "Invalid Department.");
    }
    // 	if(isset($stkaccs)){
    // 		foreach($stkaccs as $key => $accid){
    // 			$v->isOk ($accid, "num", 1, 20, "Invalid Item Account number.");
    // 		}
    // 	}else{
    // 		$v->isOk ($invid, "num", 0, 0, "Invalid Item Account number.");
    // 	}
    if (!isset($description) && !count($description)) {
        $v->addError(0, "No items selected.");
    }
    # display errors, if any
    if ($v->isError()) {
        $err = $v->genErrors();
        $err .= "<input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $err;
    }
    // Update descriptions
    foreach ($description as $key => $value) {
        $sql = "UPDATE hire.hire_nons_inv_items SET description='{$value}' WHERE id='{$key}'";
        db_exec($sql) or errDie("Unable to update descriptions.");
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM cubit.nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "' and done='n'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $td = $inv['odate'];
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($td) >= strtotime($blocked_date_from) and strtotime($td) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    db_connect();
    # cust % bank
    if ($ctyp == 's') {
        $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cus = pg_fetch_array($custRslt);
        $details = "\r\n\t\t<tr><td>{$cus['surname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($cus['addr1']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$cus['vatnum']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $cus['surname'];
    } elseif ($ctyp == 'c') {
        $cus['surname'] = $inv['cusname'];
        $cus['addr1'] = $inv['cusaddr'];
        $cus["del_addr1"] = "";
        $cus["paddr1"] = "";
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        $dept = pg_fetch_array($deptRslt);
        $details = "\r\n\t\t<tr><td>{$inv['cusname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($inv['cusaddr']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$inv['cusvatno']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $inv['cusname'];
    } else {
        $cus["del_addr1"] = "";
        $cus["paddr1"] = "";
        $cus['surname'] = $inv['cusname'];
        $cus['addr1'] = $inv['cusaddr'];
        $details = "\r\n\t\t<tr><td>{$inv['cusname']}</td></tr>\r\n\t\t<tr><td>" . nl2br($inv['cusaddr']) . "</td></tr>\r\n\t\t<tr><td>VAT No. {$inv['cusvatno']}</td></tr>\r\n\t\t<tr><td>Customer Order Number: {$inv['cordno']}</td></tr>";
        $na = $inv['cusname'];
    }
    # Begin updates
    $refnum = getrefnum();
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "NO VAT");
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    /* - End Hooks - */
    //lock(2);
    $real_invid = divlastid('inv', USER_DIV);
    //unlock(2);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.");
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM hire.hire_nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # Put in product
    $i = 0;
    $page = 0;
    while ($stk = pg_fetch_array($stkdRslt)) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $sql = "SELECT basis, hours, weeks,\r\n\t\t\t\t\textract('epoch' from from_date) AS e_from,\r\n\t\t\t\t\textract('epoch' from to_date) AS e_to\r\n\t\t\t\tFROM hire.hire_invitems\r\n\t\t\t\tWHERE id='{$stk['item_id']}'";
        $hired_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
        $hired_data = pg_fetch_array($hired_rslt);
        // --------------------------------------------------------------------
        $sql = "SELECT * FROM cubit.assets WHERE id='{$stk['asset_id']}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
        $asset_data = pg_fetch_array($asset_rslt);
        $sql = "SELECT traddisc FROM hire.hire_invoices WHERE invid='{$inv['hire_invid']}'";
        $disc_rslt = db_exec($sql) or errDie("Unable to retrieve discount.");
        $traddisc = pg_fetch_result($disc_rslt, 0);
        $sql = "UPDATE hire.assets_hired SET return_time=CURRENT_TIMESTAMP\r\n\t\t\t\tWHERE item_id='{$stk['item_id']}'";
        db_exec($sql) or errDie("Unable to update hired assets.");
        if (isset($monthly) && !$monthly) {
            if (!isSerialized($asset_data["id"])) {
                $new_qty = $asset_data["serial2"] + $stk["qty"];
                $sql = "UPDATE cubit.assets SET serial2='{$new_qty}' WHERE id='{$stk['asset_id']}'";
                db_exec($sql) or errDie("Unable to update assets.");
            }
            $hire_num = getHirenum($inv["hire_invid"]);
            if ($hire_num) {
                $sql = "SELECT * FROM hire.hire_invoices WHERE invnum='{$hire_num}'";
                $hi_rslt = db_exec($sql) or errDie("Unable to retrieve invoices.");
                while ($hi_data = pg_fetch_array($hi_rslt)) {
                    $sql = "DELETE FROM hire.hire_invitems\r\n\t\t\t\t\t\t\tWHERE invid='{$hi_data['invid']}'";
                    db_exec($sql) or errDie("Unable to remove old items.");
                }
                $sql = "DELETE FROM hire.hire_invoices WHERE invnum='{$hire_num}'";
                db_exec($sql) or errDie("Unable to remove invoices.");
                $sql = "DELETE FROM hire.monthly_invoices WHERE invnum='{$hire_num}'";
                db_exec($sql) or errDie("Unable to remove invoices.");
                $sql = "UPDATE hire.assets_hired SET return_time=current_timestamp\r\n\t\t\t\t\t\tWHERE invnum='{$hire_num}'";
                db_exec($sql) or errDie("Unable to update return time.");
            }
            $sql = "DELETE FROM hire.hire_invitems WHERE id='{$stk['item_id']}'";
            db_exec($sql) or errDie("Unable to remove returned item.");
            $sql = "DELETE FROM hire.monthly_invitems WHERE item_id='{$stk['item_id']}'";
            db_exec($sql) or errDie("Unable to remove old items.");
            $sql = "UPDATE hire.assets_hired SET return_time=current_timestamp\r\n\t\t\t\t\tWHERE item_id='{$stk['item_id']}'";
            db_exec($sql) or errDie("Unable to remove old items.");
            $sql = "DELETE FROM hire.monthly_invoices\r\n\t\t\t\t\tWHERE invid='{$inv['hire_invid']}'";
            db_exec($sql) or errDie("Unable to remove monthly.");
            $sql = "DELETE FROM hire.hire_invitems\r\n\t\t\t\t\tWHERE invid='{$inv['hire_invid']}'";
            db_exec($sql) or errDie("Unable to remove monthly.");
        }
        $stkacc = $stkaccs[$stk['id']];
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatex']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $stk['vatex'] = "y";
        }
        //print $inv['chrgvat'];exit;
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $t = $inv['chrgvat'];
        $VATP = TAX_VAT;
        # keep records for transactions
        if (isset($totstkamt[$stkacc])) {
            if ($stk['vatex'] == "y") {
                $totstkamt[$stkacc] += vats($stk['amt'], 'novat', $vd['vat_amount']);
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                }
            }
        } else {
            if ($stk['vatex'] == "y") {
                $totstkamt[$stkacc] = $stk['amt'];
                $inv['chrgvat'] = "";
                $va = 0;
            } else {
                // Seems only this one is used for our hiring purposes
                $totstkamt[$stkacc] = $stk['amt'];
                $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                }
            }
        }
        // 		if(isset($totstkamt[$stkacc])){
        // 			$totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat']);
        // 		}else{
        // 			$totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat']);
        // 		}
        $sql = "UPDATE hire.hire_nons_inv_items SET accid = '{$stkacc}' WHERE id = '{$stk['id']}'";
        $sRslt = db_exec($sql);
        if ($stk['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        // 		$time_from = "$from_day-$from_month-$from_year $from_hour:$from_minute";
        // 		$time_to = "$to_day-$to_month-$to_year $to_hour:$to_minute";
        if ($hired_data["weeks"]) {
            $hired_days = sprint($hired_data["weeks"] * 7);
        } elseif ($hired_data["e_from"] > 0) {
            $secs = $hired_data["e_to"] - $hired_data["e_from"];
            $hired_days = sprint($secs / (60 * 60 * 24) + 1);
        } elseif ($hired_data["hours"]) {
            $secs = $hired_data["hours"] / 24;
            $hired_days = sprint($secs);
        } else {
            $hired_days = 0;
        }
        $hired_days = floor($hired_days);
        switch ($hired_data["basis"]) {
            case "per_hour":
                $basis = "Hourly";
                $basis_s = "hour";
                $basis_p = "per_hour";
                break;
            case "per_day":
                $basis = "Daily";
                $basis_s = "day";
                $basis_p = "per_day";
                break;
            case "per_week":
                $basis = "Weekly";
                $basis_s = "week";
                $basis_p = "per_week";
        }
        $rate = basisPrice($inv["cusnum"], $stk["asset_id"], $basis_p);
        if (empty($rate)) {
            $rate = "0.00";
        }
        $sql = "UPDATE hire.hire_nons_inv_items SET hired_days='{$hired_days}',\r\n\t\t\trate='{$rate}' WHERE id='{$stk['id']}'";
        db_exec($sql) or errDie("Unable to save to items.");
        $products[$page][] = "<tr valign=top>\r\n\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$stk['description']}&nbsp;</td>\r\n\t\t\t<td style='border-right: 2px solid #000'>{$stk['qty']}&nbsp;</td>\r\n\t\t\t<td style='border-right: 2px solid #000'>{$hired_days}&nbsp;</td>\r\n\t\t\t<td align='right' style='border-right: 2px solid #000'>({$basis}) " . sprint($rate) . " &nbsp;</td>\r\n\t\t\t<td align='right'>" . CUR . sprint($stk["amt"]) . "&nbsp;</td>\r\n\t\t</tr>";
        $i++;
    }
    $inv['chrgvat'] = $t;
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "<tr>\r\n \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n  \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n \t\t\t\t<td>&nbsp;</td>\r\n \t\t\t</tr>";
        }
    }
    $sql = "INSERT INTO hire.hires (inv_id, user_id, cust_id, from_time)\r\n\t\t\tVALUES ('{$inv['invid']}', " . USER_ID . ", '{$inv['cusnum']}', CURRENT_TIMESTAMP)";
    db_exec($sql) or errDie("Unable to create new hire.");
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "novat");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    if (isset($bankid)) {
        $bankid += 0;
        db_conn("cubit");
        $sql = "SELECT * FROM bankacct WHERE bankid = '{$inv['accid']}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class=err>Bank not Found.</li>";
            $confirm .= "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $deptd = pg_fetch_array($deptRslt);
        }
        db_conn('core');
        $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
        $rd = db_exec($Sl) or errDie("Unable to get data.");
        $data = pg_fetch_array($rd);
        $BA = $data['accnum'];
    }
    $tot_post = 0;
    # bank  % cust
    if ($ctyp == 's') {
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<li class=err>Department not Found.</li>";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $tpp = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            $wamt += $inv["delivery"] / count($totstkamt);
            $wamt -= $inv["discount"] / count($totstkamt);
            # Debit Customer and Credit stock
            $tot_post += $wamt;
            writetrans($dept['debtacc'], $stkacc, $td, $refnum, $SUBTOT, "Non-Stock Sales on invoice No.{$real_invid} customer {$cus['surname']}.");
        }
        # Debit bank and credit the account involved
        if ($VAT != 0) {
            $tot_post += $VAT;
            writetrans($dept['debtacc'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$cus['surname']}.");
        }
        $sdate = date("Y-m-d");
    } else {
        if (!isset($accountc)) {
            $accountc = 0;
        }
        if (!isset($dept['pca'])) {
            $accountc += 0;
            $dept['pca'] = $accountc;
            $dept['debtacc'] = $accountc;
        }
        if (isset($bankid)) {
            $dept['pca'] = $BA;
        }
        $tpp = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            if (!isset($cust['surname'])) {
                $cust['surname'] = $inv['cusname'];
                $cust['addr1'] = $inv['cusaddr'];
            }
            # Debit Customer and Credit stock
            $wamt += $inv["delivery"] / count($totstkamt);
            $tot_post += $wamt;
            writetrans($dept['pca'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$cust['surname']}.");
        }
        if (isset($bankid)) {
            db_connect();
            $bankid += 0;
            $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div) VALUES ('{$bankid}', 'deposit', '{$td}', '{$inv['cusname']}', 'Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}', '0', '{$TOTAL}', '{$VAT}', '{$inv['chrgvat']}', 'no', '{$stkacc}', '" . USER_DIV . "')";
            $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
            $sql = "UPDATE cubit.hire_nons_invoices SET jobid='{$bankid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
            $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
        }
        # Debit bank and credit the account involved
        if ($VAT != 0) {
            $tot_post += $VAT;
            writetrans($dept['pca'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$cust['surname']}.");
        }
        $sdate = date("Y-m-d");
    }
    $tot_post = sprint($tot_post);
    db_connect();
    if ($ctyp == 's') {
        $sql = "UPDATE cubit.nons_invoices SET cusid = '{$cusnum}', ctyp = '{$ctyp}', cusname = '{$cus['surname']}', cusaddr = '{$cus['addr1']}', cusvatno = '{$cus['vatnum']}', done = 'y', invnum = '{$real_invid}', balance = total WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
        //
        // 		# Record the payment on the statement
        // 		$sql = "INSERT INTO stmnt(cusnum, invid, docref, amount, date, type, div) VALUES('$cusnum', '$real_invid', '$inv[docref]', '$TOTAL','$inv[odate]', 'Non-Stock Invoice', '".USER_DIV."')";
        // 		$stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.",SELF);
        //
        // 		# Record the payment on the statement
        // 		$sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('$cusnum', '$real_invid', '$inv[docref]', '$TOTAL', '$TOTAL','$inv[sdate]', 'Non-Stock Invoice', '".USER_DIV."')";
        // 		$stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.",SELF);
        //
        // 		# Update the customer (make balance more)
        // 		$sql = "UPDATE customers SET balance = (balance + '$TOTAL'::numeric(13,2)) WHERE cusnum = '$cusnum' AND div = '".USER_DIV."'";
        // 		$rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.",SELF);
        //
        // 		# Make ledge record
        // 		custledger($cusnum,$stkacc , $td, $real_invid, "Non Stock Invoice No. $real_invid", $TOTAL, "d");
        // 		custDT($TOTAL, $cusnum, $td);
        //
        // 		$tot_dif=sprint($tot_post-$TOTAL);
        if (!isset($tot_dif)) {
            $tot_dif = 0;
        }
        if ($tot_dif > 0) {
            writetrans($varacc, $dept['debtacc'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($dept['debtacc'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
        }
    } else {
        $date = date("Y-m-d");
        $sql = "UPDATE cubit.nons_invoices SET balance=total, cusname = '{$cust['surname']}', accid = '{$dept['pca']}', ctyp = '{$ctyp}', cusaddr = '{$cust['addr1']}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
        $tot_dif = sprint($tot_post - $TOTAL);
        if ($tot_dif > 0) {
            writetrans($varacc, $dept['pca'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($dept['pca'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
        }
    }
    db_connect();
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\r\n\tVALUES('{$inv['odate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$VAT}', '{$TOTAL}', 'non', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    com_invoice($inv['salespn'], $TOTAL - $VAT, 0, $real_invid, $inv["odate"]);
    db_conn('cubit');
    if (!isset($cusnum)) {
        $cusnum = 0;
    }
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\r\n\t('{$cusnum}','{$na}','Non stock Invoice {$real_invid}','{$inv['sdate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    // Customer Statement -----------------------------------------------------
    # Record the payment on the statement
    $sql = "INSERT INTO stmnt(cusnum, invid, docref, amount, date, type, div)\r\n\t\t\tVALUES('{$inv['cusnum']}', '{$inv['invid']}', '{$inv['invnum']}', '{$TOTAL}',\r\n\t\t\t\t'{$inv['odate']}', 'Hire Invoice H{$real_invid}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record");
    # Record the payment on the statement
    $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance,\r\n\t\t\t\tdate, type, div)\r\n\t\t\tVALUES ('{$inv['cusnum']}', '{$inv['invid']}', '{$inv['invnum']}', '{$TOTAL}',\r\n\t\t\t\t'{$TOTAL}', '{$inv['odate']}', 'Hire Invoice no H{$real_invid}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record.");
    # Update the customer (make balance more)
    $sql = "UPDATE customers SET balance = (balance + '{$TOTAL}'::numeric(13,2))\r\n\t\t\tWHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $stkacc = qryAccountsName("Hire Sales");
    $stkacc = $stkacc["accid"];
    # Make ledger record
    custledger($inv["cusnum"], $stkacc, $inv["odate"], $inv["invid"], "Hire Invoice No. H{$real_invid}", $TOTAL, "d");
    custDT($TOTAL, $inv["cusnum"], $inv["odate"]);
    // ------------------------------------------------------------------------
    # Get selected stock in this invoice
    $sql = "SELECT * FROM hire.hire_nons_inv_items\r\n\t\t\tWHERE invid='{$invid}' AND div='" . USER_DIV . "'";
    $item_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
    $item_count = pg_num_rows($item_rslt);
    $totamt = 0;
    while ($item_data = pg_fetch_array($item_rslt)) {
        $totamt += $item_data["amt"];
        $sql = "SELECT * FROM cubit.assets WHERE id='{$item_data['asset_id']}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
        $asset_data = pg_fetch_array($asset_rslt);
        $discount = $item_data["amt"] / 100 * $traddisc;
        // Add up revenue
        $sql = "INSERT INTO hire.revenue (group_id, asset_id, total, discount,\r\n\t\t\t\t\thire_invnum, inv_invnum, cusname)\r\n\t\t\t\tVALUES ('{$asset_data['grpid']}', '{$item_data['asset_id']}',\r\n\t\t\t\t\t'{$item_data['amt']}', '{$discount}', '{$hirenum}',\r\n\t\t\t\t\t'{$real_invid}', '{$inv['cusname']}')";
        db_exec($sql) or errDie("Unable to update revenue");
        $sql = "INSERT INTO cubit.nons_inv_items (invid, qty, description,\r\n\t\t\tdiv, amt, unitcost, vatex, accid, asset_id)\r\n\t\tVALUES ('{$invid}', '{$item_data['qty']}',\r\n\t\t\t'{$item_data['description']}', '{$item_data['div']}', '{$item_data['amt']}',\r\n\t\t\t'{$item_data['amt']}',  '2', '{$item_data['accid']}', '{$item_data['asset_id']}')";
        db_exec($sql) or errDie("Unable to add non stock items.");
        $sql = "UPDATE hire.assets_hired SET return_time=CURRENT_TIMESTAMP,\r\n\t\t\t\t\tinv_invnum='{$real_invid}', value='{$item_data['amt']}'\r\n\t\t\t\tWHERE item_id='{$item_data['item_id']}'";
        db_exec($sql) or errDie("Unable to record asset return time.");
    }
    // Add the delivery discount to the total revenue
    if ($inv["delivery"]) {
        $discount = $inv["delivery"] / 100 * $traddisc;
        $sql = "INSERT INTO hire.revenue (discount)\r\n\t\t\t\tVALUES ('{$discount}')";
        db_exec($sql) or errDie("Unable to update revenue");
    }
    $cc = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', ''); </script>";
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='SALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sp = "<tr><td><b>Sales Person:</b> {$inv['salespn']}</td></tr>";
    } else {
        $sp = "";
    }
    if ($inv['chrgvat'] == "yes") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "no") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if ($inv["remarks"] == "") {
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
        $commRslt = db_exec($sql) or errDie("Unable to retrieve the default comments from Cubit.");
        $inv["remarks"] = pg_fetch_result($commRslt, 0);
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company information from Cubit.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    db_conn("cubit");
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank information from Cubit.");
    $bank_data = pg_fetch_array($bank_rslt);
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;\r\n\t";
    // 	$nolr_borders = "
    // 		border-top: 2px solid #000;
    // 		border-left: none;
    // 		border-right: none;
    // 		border-bottom: none;
    // 	";
    $sql = "UPDATE hire.hire_invoices SET done='y', delivery='0.00'\r\n\t\t\tWHERE invnum='" . getHirenum($inv["hire_invid"]) . "'";
    db_exec($sql) or errDie("Unable to update invoices.");
    vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock Sales, invoice No.{$real_invid}", $TOTAL, $inv["vat"]);
    $details = "";
    $SUBTOT = sprint($totamt);
    for ($i = 0; $i <= $page; $i++) {
        if ($monthly) {
            $monthly_out = "\r\n\t\t\t<tr>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>Invoiced to date " . date("d-m-Y") . "</td>\r\n\t\t\t</tr>";
        } else {
            $monthly_out = "";
        }
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $details .= "<center>\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='left' rowspan='2'><img src='../compinfo/getimg.php' width='230' height='47'></td>\r\n\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Invoice</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t</tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$real_invid}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Hire No:</b> {$hirenum}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$sp}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='center'><font size='4'><b>Tax Invoice To:</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cus['surname']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cus["addr1"]) . "&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cus["paddr1"]) . "&nbsp;</td>\r\n\t\t\t\t\t<td>" . nl2br($cus["del_addr1"]) . "&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>No of Days</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Rate</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$products_out}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$inv['remarks']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$SUBTOT}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>Delivery</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['delivery']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>Discount</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['discount']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['vat']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['total']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t<tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$monthly_out}\r\n\t\t\t</table>\r\n\t\t</table>\r\n\t\t";
    }
    $amt = $pcash + $pcheque + $pcc;
    $_POST["amt"] = $amt;
    $_POST["date"] = $inv["odate"];
    recvpayment_write();
    $sql = "UPDATE cubit.nons_invoices SET cash='{$pcash}' WHERE invid='{$inv['invid']}'";
    db_exec($sql) or errDie("Unable to update cash value.");
    pglib_transaction("COMMIT");
    // Retrieve the template settings from Cubit
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        $OUTPUT = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', '');</script>\r\n\t\t\t{$details}";
        require "../tmpl-print.php";
    } else {
        $OUTPUT = "<script> CostCenter('dt', 'Sales', '{$inv['odate']}', 'Non Stock Invoice No.{$real_invid}', '" . ($TOTAL - $VAT) . "', '');\r\n\t\tmove (\"../{$template}?invid={$inv['invid']}&type=nons\");\r\n\t\t</script>";
        require "template.php";
    }
}
function cdetails($_GET)
{
    $showvat = TRUE;
    # get vars
    extract($_GET);
    if (!isset($button) && isset($starting)) {
        return slct($_GET);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice number.");
    if (isset($ctyp) && $ctyp == 's') {
        $v->isOk($cusnum, "num", 1, 20, "Invalid customer number.");
    } elseif (isset($ctyp) && $ctyp == 'c') {
        $v->isOk($deptid, "num", 1, 20, "Invalid Department.");
    }
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm = "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>{$err}";
        return $confirm;
    }
    if ($ctyp == "ac") {
        return acdetails($_GET);
    }
    # Get Invoice info
    db_connect();
    $sql = "SELECT * FROM cubit.nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoices information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $details = "";
    if ($ctyp == 's') {
        $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cust = pg_fetch_array($custRslt);
        $details = "\r\n\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th colspan='2'> Customer Details </th>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<input type='hidden' name='cusnum' value='{$cusnum}'>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Customer</td>\r\n\t\t\t\t\t<td valign='center'>{$cust['cusname']} {$cust['surname']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Customer Address</td>\r\n\t\t\t\t\t<td valign='center'><pre>{$cust['addr1']}</pre></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Customer VAT Number</td>\r\n\t\t\t\t\t<td valign='center'>{$cust['vatnum']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Customer Order number</td>\r\n\t\t\t\t\t<td valign='center'>{$inv['cordno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Customer Balance (Excl this Invoice)</td>\r\n\t\t\t\t\t<td>" . CUR . sprint($cust["balance"]) . "</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>";
    } elseif ($ctyp == 'c') {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        $dept = pg_fetch_array($deptRslt);
        $details = "\r\n\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th colspan='2'> Customer Details </th>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<input type='hidden' name='deptid' value='{$deptid}'>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Customer</td>\r\n\t\t\t\t\t<td valign='center'>{$inv['cusname']} </td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Customer Address</td>\r\n\t\t\t\t\t<td valign='center'><pre>{$inv['cusaddr']}</pre></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Customer VAT Number</td>\r\n\t\t\t\t\t<td valign='center'>{$inv['cusvatno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Customer Order number</td>\r\n\t\t\t\t\t<td valign='center'>{$inv['cordno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>";
    } elseif ($ctyp == 'cb') {
        db_conn("cubit");
        $sql = "SELECT * FROM bankacct WHERE bankid = '{$inv['accid']}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Bank not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = "{$dept['bankname']} - {$dept['accname']}({$dept['acctype']})";
        }
        $details = "\r\n\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<th colspan='2'> Customer Details </th>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<input type='hidden' name='bankid' value='{$inv['accid']}'>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Customer</td>\r\n\t\t\t\t\t<td valign='center'>{$inv['cusname']} </td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Customer Address</td>\r\n\t\t\t\t\t<td valign='center'><pre>{$inv['cusaddr']}</pre></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Customer VAT Number</td>\r\n\t\t\t\t\t<td valign='center'>{$inv['cusvatno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Customer Order number</td>\r\n\t\t\t\t\t<td valign='center'>{$inv['cordno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t<td>Account</td>\r\n\t\t\t\t\t<td>{$supacc}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>";
    }
    $stkacc = "";
    core_connect();
    $sql = "SELECT * FROM accounts WHERE div = '" . USER_DIV . "' ORDER BY accname ASC";
    $accRslt = db_exec($sql);
    if (pg_numrows($accRslt) < 1) {
        return "<li>There are No accounts in Cubit.</li>";
    }
    while ($acc = pg_fetch_array($accRslt)) {
        if (isb($acc['accid'])) {
            continue;
        }
        $stkacc .= "<option value='{$acc['accid']}'>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</option>";
    }
    $stkacc .= "</select>";
    /* --- Start Products Display --- */
    # Products layout
    $products = "\r\n\t\t<table " . TMPL_tblDflts . " width='100%'>\r\n\t\t\t<tr>\r\n\t\t\t\t<th width='5%'>#</th>\r\n\t\t\t\t<th width='55%'>DESCRIPTION</th>\r\n\t\t\t\t<th width='10%'>QTY</th>\r\n\t\t\t\t<th width='10%'>UNIT PRICE</th>\r\n\t\t\t\t<th width='10%'>AMOUNT</th>\r\n\t\t\t\t<th width='10%'>ACCOUNT</th>\r\n\t\t\t<tr>";
    # get selected stock in this Invoice
    db_connect();
    $sql = "SELECT * FROM hire.hire_nons_inv_items WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $i++;
        // Check Tax Excempt
        db_conn("cubit");
        $sql = "SELECT zero FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $zRslt = db_exec($sql) or errDie("Unable to retrieve vat code from Cubit.");
        $vatex = pg_fetch_result($zRslt, 0);
        if ($vatex == "Yes") {
            $ex = "#";
        } else {
            $ex = "";
        }
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $Ri = db_exec($Sl);
        $vd = pg_fetch_array($Ri);
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        # put in product
        $products .= "\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td align='center'>{$i}</td>\r\n\t\t\t\t<td>{$ex} {$stkd['description']}</td>\r\n\t\t\t\t<td>{$stkd['qty']}</td>\r\n\t\t\t\t<td>{$stkd['unitcost']}</td>\r\n\t\t\t\t<td>" . CUR . " {$stkd['amt']}</td>\r\n\t\t\t\t<td " . ass("Select the account you wish to Credit") . "><select name='stkaccs[{$stkd['id']}]'>{$stkacc}</td>\r\n\t\t\t</tr>";
    }
    $products .= "</table>";
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Get Total
    $TOTAL = sprint($inv['total']);
    # Get vat
    $VAT = sprint($inv['vat']);
    /* --- End Some calculations --- */
    # format date
    list($syear, $smon, $sday) = explode("-", $inv['odate']);
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    /* -- Final Layout -- */
    $details = "\r\n\t\t<center>\r\n\t\t<h3>Non-Stock Invoice Details</h3>\r\n\t\t<form action='" . SELF . "' method='POST' name='form'>\r\n\t\t\t<input type='hidden' name='key' value='cconfirm'>\r\n\t\t\t<input type='hidden' name='invid' value={$invid}>\r\n\t\t\t<input type='hidden' name='ctyp' value={$ctyp}>\r\n\t\t<table " . TMPL_tblDflts . " width=95%>\r\n\t\t\t<tr>\r\n\t\t\t\t<td valign='top'>{$details}</td>\r\n\t\t\t\t<td valign='top' align='right'>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t<tr><th colspan='2'> Non-Stock Invoice Details </th></tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Non-Stock Invoice No.</td>\r\n\t\t\t\t\t\t\t<td valign='center'>T {$inv['invid']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Hire No.</td>\r\n\t\t\t\t\t\t\t<td valign='center'>H" . getHirenum($inv["hire_invid"], 1) . "</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Date</td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$sday}-{$smon}-{$syear}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>VAT Inclusive</td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$inv['chrgvat']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>Terms</td>\r\n\t\t\t\t\t\t\t<td valign='center'>{$inv['terms']} Days</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr><td><br></td></tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td colspan='2'>{$products}</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<th width='40%'>Quick Links</th>\r\n\t\t\t\t\t\t\t<th width='45%'>Remarks</th>\r\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='15%'><br></td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td align='center'>\r\n\t\t\t\t\t\t\t\t<a href='javascript:popupOpen(\"../nons-invoice-new.php\")'>New Non-Stock Invoices</a>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan=4 align=center valign=top>" . nl2br($inv['remarks']) . "</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td align='center'><a href='javascript:popupOpen(\"nons-invoice-view.php\")'>View Non-Stock Invoices</a></td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t\t<td align='right'>\r\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\r\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$inv['subtot']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<td>VAT {$vat14}</td>\r\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$inv['vat']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\r\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$inv['total']}</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td align='right'><input type='submit' value='Confirm &raquo'></td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t\t</form>\r\n\t\t</center>";
    return $details;
}
function details($_GET)
{
    $showvat = TRUE;
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $v->isOk($prd, "num", 1, 2, "Invalid prd.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>{$e['msg']}</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    pglib_transaction("BEGIN");
    updateTotals($invid);
    # Get invoice info
    db_conn($prd);
    $sql = "SELECT *, extract('epoch' from timestamp) AS e_time\r\n\t\t\t\tFROM hire.hire_invoices\r\n\t\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found[1]</i>";
    }
    $inv = pg_fetch_array($invRslt);
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found[2]</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    /* --- Start some checks --- */
    # check if invoice has been printed
    if ($inv['printed'] == "n") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has not been printed.</li>";
        return $error;
    }
    # check if stock was selected(yes = put done button)
    db_conn($prd);
    $sql = "SELECT asset_id FROM hire.hire_invitems WHERE invid = '{$inv['invid']}'";
    $crslt = db_exec($sql);
    if (pg_numrows($crslt) < 1) {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has no items.</li>";
        return $error;
    }
    /* --- End some checks --- */
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    $sql = "SELECT * FROM hire.hire_invitems  WHERE invid = '{$invid}'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # get selected stock in this warehouse
        db_connect();
        $sql = "SELECT * FROM assets WHERE id = '{$stkd['asset_id']}'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        $sp = "&nbsp;&nbsp;&nbsp;&nbsp;";
        # keep track of discounts
        $disc += $stkd['disc'];
        if ($stkd['account'] != 0) {
            $stk['stkcod'] = $stkd['description'];
            $stk['stkdes'] = "";
        }
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        $vd = pg_fetch_array($Ri);
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        # put in product
        $stkd['unitcost'] = $stkd['unitcost'] - $stkd['disc'];
        $return = returnDate($stkd["id"]);
        $hired = hiredDate($stkd["id"]);
        $products .= "\r\n\t\t\t\t<tr valign=top>\r\n\t\t\t\t\t<td>" . getSerial($stk["id"], 1) . " {$stk['des']} ({$stkd['collection']})</td>\r\n\t\t\t\t\t<td>{$stkd['qty']}</td>\r\n\t\t\t\t\t<td>{$hired}</td>\r\n\t\t\t\t\t<td>{$return}</td>\r\n\t\t\t\t\t<td align=right>" . sprint($stkd["amt"]) . "</td>\r\n\t\t\t\t</tr>";
        $client_collect = 0;
        $collect = 0;
        $deliver = 0;
        if (preg_match("/(Client Collect|collect)/", $stkd["collection"])) {
            $client_collect = 1;
        }
        if (preg_match("/(^Collect|, Collect)/", $stkd["collection"])) {
            $collect = 1;
        }
        if (preg_match("/Deliver/", $stkd["collection"])) {
            $deliver = 1;
        }
        $sql = "INSERT INTO hire.collection (asset_id, client_collect, collect,\r\n\t\t\t\t\tdeliver, item_id)\r\n\t\t\t\tVALUES ('{$stkd['asset_id']}', '{$client_collect}', '{$collect}',\r\n\t\t\t\t\t'{$deliver}', '{$stkd['id']}')";
        db_exec($sql) or errDie("Unable to add collection method.");
    }
    /* --- Start Some calculations --- */
    # subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    $traddiscm = $inv["discount"];
    // 	if(strlen($inv['traddisc']) > 0){
    // 		$traddiscm = sprint((($inv['traddisc']/100) * $SUBTOT));
    // 	}else{
    // 		$traddiscm = "0.00";
    // 	}
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    # Update number of prints
    // 	$inv['prints']++;
    // 	db_conn($prd);
    // 	$Sql = "UPDATE hire.hire_invitems SET prints = '$inv[prints]' WHERE invid = '$invid' AND div = '".USER_DIV."'";
    // 	$upRslt = db_exec($Sql) or errDie ("Unable to update invoice information");
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    if (strlen($inv['comm']) > 0) {
        $Com = "\r\n\t\t\t\t<table>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td>" . nl2br($inv['comm']) . "</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</table>";
    } else {
        $Com = "";
    }
    $time = date("G:i:s", $inv["e_time"]);
    if (isset($cccc)) {
        $cc = "<script> sCostCenter('dt', 'Sales', '{$date}', 'Invoice No.{$inv['invnum']} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$inv['invnum']}', '{$tcosamt}', ''); </script>";
    } else {
        $cc = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='PSALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sp = "<tr><td>Sales Person</td><td>{$inv['salespn']}</td></tr>";
    } else {
        $sp = "";
    }
    $Sl = "SELECT * FROM pc WHERE inv='{$inv['invnum']}'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) > 0) {
        $pd = pg_fetch_array($Ri);
        //$pc="<tr><td>Change</td><td align=right><b>".CUR." $pd[amount]</b></td></tr>";
        $pc = "";
        $change = $pd['amount'];
    } else {
        $pc = "";
        $change = 0;
    }
    $Sl = "SELECT * FROM payrec WHERE inv='{$inv['invnum']}' AND method='Cash'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) > 0) {
        $pd = pg_fetch_array($Ri);
        $pd['amount'] = sprint($pd['amount'] + $change);
        $pcash = "<!--<tr><td>Paid Cash</td><td align=right><b>" . CUR . " {$pd['amount']}</b></td></tr>-->";
    } else {
        $pcash = "";
    }
    $Sl = "SELECT * FROM payrec WHERE inv='{$inv['invnum']}' AND method='Cheque'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) > 0) {
        $pd = pg_fetch_array($Ri);
        $pcheque = "<tr><td>Paid Cheque</td><td align=right><b>" . CUR . " {$pd['amount']}</b></td></tr>";
    } else {
        $pcheque = "";
    }
    $Sl = "SELECT * FROM payrec WHERE inv='{$inv['invnum']}' AND method='Credit Card'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) > 0) {
        $pd = pg_fetch_array($Ri);
        $pcc = "<tr><td>Paid Credit Card</td><td align=right><b>" . CUR . " {$pd['amount']}</b></td></tr>";
    } else {
        $pcc = "";
    }
    $Sl = "SELECT * FROM payrec WHERE inv='{$inv['invnum']}' AND method='Credit'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) > 0) {
        $pd = pg_fetch_array($Ri);
        $pcc .= "<tr><td>On Credit</td><td align=right><b>" . CUR . " {$pd['amount']}</b></td></tr>";
    } else {
        $pcc .= "";
    }
    // 	$Sl="SELECT * FROM varrec WHERE inv='$inv[invnum]'";
    // 	$Ri=db_exec($Sl);
    //
    // 	if(pg_num_rows($Ri)>0) {
    // 		$rd=pg_fetch_array($Ri);
    //
    // 		$rounding="<tr><td>Rounding</td><td align=right>".CUR." $rd[amount]</td></tr>";
    // 	} else {
    // 		$rounding="";
    // 	}
    //
    if ($inv['rounding'] > 0) {
        $due = sprint($inv['total'] - $inv['rounding']);
        $rounding = "\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>Rounding</td>\r\n\t\t\t\t\t<td align='right'>" . CUR . " {$inv['rounding']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>Amount Due</td>\r\n\t\t\t\t\t<td align='right'>" . CUR . " {$due}</td>\r\n\t\t\t\t</tr>";
    } else {
        $rounding = "";
    }
    $cusinfo = "";
    if ($inv['cusnum'] > 0) {
        db_conn('cubit');
        $Sl = "SELECT * FROM customers WHERE cusnum='{$inv['cusnum']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $cd = pg_fetch_array($Ri);
        $inv['cusname'] = $cd['surname'] . " (VAT No. {$cd['vatnum']})";
        $cusinfo .= "<p>" . hireAddress($inv["invid"]) . "</p>";
        $cusinfo .= "Tel: {$cd['bustel']}<br />";
        $cusinfo .= "Order No: {$inv['cordno']}";
    } else {
        if (strlen($inv['vatnum']) > 1) {
            $inv['cusname'] = "{$inv['cusname']} (VAT No. {$inv['vatnum']})<br />";
            $cusinfo .= "Order No: {$inv['cordno']}";
        }
    }
    db_conn('cubit');
    $Sl = "SELECT img2 FROM compinfo";
    $Ri = db_exec($Sl);
    $id = pg_fetch_array($Ri);
    if (strlen($id['img2']) > 0) {
        $logo = "<tr>\r\n\t\t\t<td valign='top' width='100%' align=center><img src='compinfo/getimg2.php' width='230' height='47'></td>\r\n\t\t</tr>";
    } else {
        $logo = "";
    }
    $sql = "SELECT value FROM cubit.settings WHERE constant='CONTRACT_TEXT'";
    $contract_rslt = db_exec($sql) or errDie("Unable to retrieve contract.");
    $contract_text = nl2br(base64_decode(pg_fetch_result($contract_rslt, 0)));
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    $sql = "SELECT text FROM hire.thanks_text";
    $thanks_rslt = db_exec($sql) or errDie("Unable to retrieve thank you text.");
    $thank_you = pg_fetch_result($thanks_rslt, 0);
    $details = "<center>\r\n\t{$cc}\r\n\t<style>\r\n\t\th2 {\r\n\t\t\tfont-size: 2em;\r\n\t\t\tpadding: 0;\r\n\t\t\tmargin: 0;\r\n\t\t}\r\n\t\tth {\r\n\t\t\tfont-weight: bold;\r\n\t\t\ttext-align: left;\r\n\t\t}\r\n\t\t.print_input {\r\n\t\t\tfont-family: monospace;\r\n\t\t\tfont-weight: bold;\r\n\t\t}\r\n\t</style>\r\n\t<table cellpadding='0' cellspacing='1' border=1 width='97%'>\r\n\t<tr><td>\r\n\t\t<table cellpadding='5' cellspacing='0' width='100%'>\r\n\t\t\t<tr>\r\n\t\t\t\t<td><img src='../compinfo/getimg.php' width='230' height='47' /></td>\r\n\t\t\t\t<td align='right'><h2>HIRE NOTE</h2></td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t</tr></td>\r\n\t<tr><td>\r\n\t\t<table border='1' width='100%'>\r\n\t\t<tr>\r\n\t\t\t<td valign=top width='50%'>\r\n\t\t\t\t" . COMP_NAME . "<br />\r\n\t\t\t\t" . COMP_ADDRESS . "<br />\r\n\t\t\t\tTEL: " . COMP_TEL . "<br />\r\n\t\t\t\tFAX: " . COMP_FAX . "<br />\r\n\t\t\t\tRegistration Number: " . COMP_REGNO . "<br />\r\n\t\t\t\tVAT Registration Number: " . COMP_VATNO . "<br />\r\n\t\t\t</td>\r\n\t\t\t<td valign='top' width='50%'>\r\n\t\t\t\t{$inv['cusname']}<br />\r\n\t\t\t\t{$cusinfo}\r\n\t\t\t</td>\r\n\t\t</tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td>\r\n\t\t<table " . TMPL_tblDflts . " width='100%'>\r\n\t\t\t<tr>\r\n\t\t\t\t<td align='left' width='25%'>Note: H" . getHirenum($inv["invid"], 1) . "</td>\r\n\t\t\t\t<td align='center' width='25%'>CASHIER: {$inv['username']}</td>\r\n\t\t\t\t<td width='25%' align='center'>Time: {$time}</td>\r\n\t\t\t\t<td width='25%' align='right'>{$inv['odate']}</td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td>\r\n\t<table cellpadding='5' cellspacing='0' border='0' width='100%' bordercolor='#000000'>\r\n\t\t<tr>\r\n\t\t\t<th>CODE</th>\r\n\t\t\t<th>QTY</th>\r\n\t\t\t<th>HIRE DATE</th>\r\n\t\t\t<th>RETURN</th>\r\n\t\t\t<th style='text-align: right'>TOTAL</th>\r\n\t\t<tr>\r\n\t\t{$products}\r\n\t</table>\r\n\t</td></tr>\r\n\t<tr>\r\n\t\t<td valign='top'>\r\n\t\t<table width='100%'>\r\n\t\t<tr><td valign='top'>\r\n\t\t<table cellpadding='2' cellspacing='0' width='80%'>\r\n\t\t\t<tr><td colspan='2'>{$thank_you}</td></tr>\r\n\t\t\t<tr><td>{$Com}</td></tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>\r\n\t\t\t\t<font style='font-size: 0.75em'>" . nl2br($inv["custom_txt"]) . "<br />\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr><td>&nbsp;</td></tr>\r\n\t\t</table>\r\n\t\t</td>\r\n\t\t<td align=right valign='top'>\r\n\t\t<table cellpadding='2' cellspacing='0' width='50%'>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>Delivery Charge</td>\r\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$inv['delchrg']}</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>Trade Discount</td>\r\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$traddiscm}</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>SUBTOTAL</td>\r\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$SUBTOT}</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>VAT {$vat14}</td>\r\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$VAT}</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td nowrap>GRAND TOTAL</td>\r\n\t\t\t\t<td align='right' nowrap><b>" . CUR . " {$TOTAL}</b></td>\r\n\t\t\t</tr>\r\n\t\t\t{$sp}\r\n\t\t</table>\r\n\t</td></tr>\r\n\t\t<table cellpadding='2' cellspacing='0' width='100%' border='1'>\r\n\t\t\t<tr><td colspan='2'>\r\n\t\t\t<div style='font-size: .80em;'>" . stripslashes($contract_text) . "</div></div>\r\n\t\t\t</td></tr>\r\n\t\t\t<tr><td colspan='2'>&nbsp;</td></tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>Full Names (Print) ____________________________</td>\r\n\t\t\t\t<td>Identity Number ____________________________</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr><td colspan='2'>&nbsp;</td></tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>Signature - Customer ____________________________</td>\r\n\t\t\t\t<td>Signature - Authorized Agent ____________________________</td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t</td></tr>\r\n\t</table>\r\n\t</table>\r\n\t</center>";
    $OUTPUT = $details;
    // Save this hire note for later reprinting
    $db_details = base64_encode($details);
    $sql = "SELECT invid FROM hire.hire_invoices WHERE invid='{$inv['invid']}'";
    $hi_rslt = db_exec($sql) or errDie("Unable to retrieve hire notes.");
    if (pg_num_rows($hi_rslt)) {
        $sql = "INSERT INTO hire.notes_reprint (invid, invnum, cusnum, odate,\r\n\t\t\t\t\tbody)\r\n\t\t\t\tVALUES ('{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusnum']}',\r\n\t\t\t\t\t'{$inv['odate']}', '{$db_details}')";
        db_exec($sql) or errDie("Unable to save hire note.");
    }
    pglib_transaction("COMMIT");
    require "../tmpl-print.php";
}