function update($_POST)
{
    extract($_POST);
    $collect_ar = array();
    if (!empty($client_collect)) {
        $collect_ar[] = "Client Collect";
    }
    if (!empty($collect)) {
        $collect_ar[] = "Collect";
    }
    if (!empty($deliver)) {
        $collect_ar[] = "Deliver";
    }
    $collection = implode(", ", $collect_ar);
    // 	if ((in_array("Collect", $collect_ar) && in_array("Client Collect", $collect_ar))
    // 		|| (count($collect_ar) == 3)) {
    // 		return "<li class='err'>Invalid collection options selected.</li>";
    // 	}
    if (count($collect_ar) > 1 && in_array("Client Collect", $collect_ar)) {
        return "<li class='err'>Invalid collection options selected.</li>";
    }
    $temp_assets = explode(",", $temp_assets);
    pglib_transaction("BEGIN");
    if (isset($nhalf_day) && $nhalf_day == "checked") {
        $nhalf_day = 1;
    } else {
        $nhalf_day = 0;
    }
    if (isset($nweekends) && $nweekends == "checked") {
        $nweekends = 1;
    } else {
        $nweekends = 0;
    }
    $sql = "UPDATE hire.hire_invoices SET comm='{$comm}' WHERE invid='{$invid}'";
    $comm_rslt = db_exec($sql) or errDie("Unable to retrieve invoice.");
    foreach ($temp_assets as $key => $value) {
        $sql = "SELECT * FROM cubit.assets WHERE id='{$key}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
        $asset_data = pg_fetch_array($asset_rslt);
    }
    if (isset($amount)) {
        foreach ($amount as $key => $value) {
            // 			if (empty($monthly)) {
            // 				$amount[$key] = "";
            // 			}
            if (!user_is_admin(USER_ID)) {
                $amount[$key] = "";
            }
            if (!isset($half_day[$key]) || empty($half_day[$key])) {
                $half_day[$key] = 0;
            }
            if (!isset($weekends[$key]) || empty($weekends[$key])) {
                $weekends[$key] = 0;
            } else {
                $weekends[$key] = 1;
            }
            if (empty($amount[$key]) && $amount != "0") {
                if ($basis[$key] == "per_day") {
                    $hifrm = "{$mfrm_year[$key]}-{$mfrm_month[$key]}-{$mfrm_day[$key]}";
                    $hito = "{$mto_year[$key]}-{$mto_month[$key]}-{$mto_day[$key]}";
                    $hours = "0";
                    /* calculate amount */
                    $ftime = getDTEpoch("{$hifrm} 0:00:00");
                    $ttime = getDTEpoch("{$hito} 0:00:00");
                    $days = 0;
                    $weeks = 0;
                    while ($ftime <= $ttime) {
                        if (date("w", $ftime) == 0 && isset($weekends[$key]) && $weekends[$key]) {
                            $days += 0.6;
                        } else {
                            ++$days;
                        }
                        $ftime += 24 * 60 * 60;
                    }
                    if (is_numeric($rain_days[$key])) {
                        $days -= $rain_days[$key];
                    }
                    $timeunits = $days;
                } else {
                    if ($basis[$key] == "per_hour") {
                        $hifrm = $hito = mkdate($pinv_year, $pinv_month, $pinv_day);
                        $timeunits = $hours;
                        $weeks = 0;
                        if (empty($hours) || !is_numeric($hours)) {
                            return "\r\n\t\t\t\t\t\t\t<li class='err'>\r\n\t\t\t\t\t\t\t\t<b>ERROR</b>: Invalid amount of hours.\r\n\t\t\t\t\t\t\t</li>";
                        }
                    } else {
                        if ($nbasis == "per_week") {
                            $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                            $timeunits = $weeks;
                            $hours = 0;
                            if (empty($weeks) || !is_numeric($weeks)) {
                                return "\r\n\t\t\t\t\t\t\t<li class='err'>\r\n\t\t\t\t\t\t\t\t<b>ERROR</b>: Invalid amount of weeks.\r\n\t\t\t\t\t\t\t</li>";
                            }
                        }
                    }
                }
                if ($half_day[$key]) {
                    $amount[$key] = $qty[$key] * $timeunits * (basisPrice($cusnum, $asset_id[$key], $basis[$key]) * $qty[$key]) - basisPrice($cusnum, $asset_id[$key], $basis[$key]) * $qty[$key] + basisPrice($cusnum, $asset_id[$key], $basis[$key]) * $qty[$key] / 2;
                } else {
                    $amount[$key] = $qty[$key] * $timeunits * basisPrice($cusnum, $asset_id[$key], $basis[$key]);
                }
            }
            if ($amount[$key] == 0) {
                $amount[$key] = 0;
                $blank_amount = 1;
            } else {
                $blank_amount = 0;
            }
            $sql = "UPDATE hire.hire_invitems SET amt='{$amount[$key]}',\r\n\t\t\t\t\t\thalf_day='{$half_day[$key]}', weekends='{$weekends[$key]}'\r\n\t\t\t\t\tWHERE id='{$key}'";
            db_exec($sql) or errDie("Unable to update item amount.");
            $sql = "UPDATE hire.reprint_invitems SET amt='{$amount[$key]}',\r\n\t\t\t\t\t\thalf_day='{$half_day[$key]}', weekends='{$weekends[$key]}'\r\n\t\t\t\t\tWHERE item_id='{$key}'";
            db_exec($sql) or errDie("Unable to update return item amount.");
            if ($blank_amount) {
                $amount[$key] = "";
            }
            //$hifrm = "$hifrm_year[$key]-$hifrm_month[$key]-$hifrm_day[$key]";
            //$hito = "$hito_year[$key]-$hito_month[$key]-$hito_day[$key]";
            if (!isset($remove[$key])) {
                $sql = "SELECT basis FROM hire.hire_invitems WHERE id='{$key}'";
                $item_rslt = db_exec($sql) or errDie("Unable to retrieve basis.");
                $mbasis = pg_fetch_result($item_rslt, 0);
                /* determine time units */
                if ($mbasis == "per_day") {
                    $mfrm = mkdate($mfrm_year[$key], $mfrm_month[$key], $mfrm_day[$key]);
                    $mto = mkdate($mto_year[$key], $mto_month[$key], $mto_day[$key]);
                    /* calculate amount */
                    $ftime = mktime(0, 0, 0, $mfrm_month[$key], $mfrm_day[$key], $mfrm_year[$key]);
                    $ttime = mktime(0, 0, 0, $mto_month[$key], $mto_day[$key], $mto_year[$key]);
                    $days = 0;
                    if (empty($weeks)) {
                        $weeks = 0;
                    }
                    if (empty($hours)) {
                        $hours = 0;
                    }
                    while ($ftime <= $ttime) {
                        if (date("w", $ftime) == 0 && isset($weekends[$key]) && $weekends[$key]) {
                            $days += 0.6;
                        } else {
                            ++$days;
                        }
                        $ftime += 24 * 60 * 60;
                    }
                    $timeunits = $days;
                    $sql = "UPDATE hire.hire_invitems\r\n\t\t\t\t\t\t\tSET from_date='{$mfrm}', to_date='{$mto}'\r\n\t\t\t\t\t\t\tWHERE id='{$key}'";
                    db_exec($sql) or errDie("Unable to update items.");
                    $sql = "UPDATE hire.reprint_invitems\r\n\t\t\t\t\t\t\tSET from_date='{$mfrm}', to_date='{$mto}'\r\n\t\t\t\t\t\t\tWHERE item_id='{$key}'";
                    db_exec($sql) or errDie("Unable to update reprint items.");
                }
            } else {
                // Delete the old items
                $sql = "DELETE FROM hire.hire_invitems WHERE id='{$key}'";
                db_exec($sql) or errDie("Unable to remove old items.");
                $sql = "DELETE FROM hire.reprint_invitems WHERE item_id='{$key}'";
                db_exec($sql) or errDie("Unable to remove old reprint items.");
                //.Remove if the item has been hired as well
                $sql = "DELETE FROM hire.assets_hired WHERE item_id='{$key}'";
                db_exec($sql) or errDie("Unable to remove items from hired log.");
            }
        }
    }
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$invid}'";
    $hi_rslt = db_exec($sql) or errDie("Unable to retrieve invoice.");
    $invb = pg_fetch_array($hi_rslt);
    // Insert new items
    if ($nasset_id != "0" || $nbasis != "0") {
        if ($nasset_id == "0") {
            return "<li class='err'><b>ERROR</b>: No asset selected.</li>";
        }
        /* get asset id */
        list($serialqty, $nasset_id) = explode(":", $nasset_id);
        /* disabled items don't get passed through */
        if ($serialqty == "s" || !isset($nqty)) {
            $nqty = "1";
        } else {
            $sql = "SELECT serial2 FROM cubit.assets WHERE id='{$nasset_id}'";
            $dqty_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
            $dqty = pg_fetch_result($dqty_rslt, 0);
            if ($dqty - $nqty < 0) {
                return "<li class='err'><b>ERROR</b>: Invalid quantity. Only &nbsp; <b>{$dqty}</b> &nbsp; available.</li>";
            }
        }
        if (empty($nqty) || !is_numeric($nqty)) {
            return "<li class='err'><b>ERROR</b>: Invalid quantity</li>";
        }
        /* determine time units */
        if ($nbasis == "per_day") {
            $nhifrm = mkdate($nhifrm_year, $nhifrm_month, $nhifrm_day);
            $nhito = mkdate($nhito_year, $nhito_month, $nhito_day);
            $hours = "0";
            /* calculate amount */
            $ftime = mktime(0, 0, 0, $nhifrm_month, $nhifrm_day, $nhifrm_year);
            $ttime = mktime(0, 0, 0, $nhito_month, $nhito_day, $nhito_year);
            $days = 0;
            $weeks = 0;
            while ($ftime <= $ttime) {
                if (date("w", $ftime) == 0 && isset($nweekends) && $nweekends) {
                    $days += 0.6;
                } else {
                    ++$days;
                }
                $ftime += 24 * 60 * 60;
            }
            $timeunits = $days;
        } else {
            if ($nbasis == "per_hour") {
                $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                $timeunits = $hours;
                $weeks = 0;
                if (empty($hours) || !is_numeric($hours)) {
                    return "<li class='err'><b>ERROR</b>: Invalid amount of hours.</li>";
                }
            } else {
                if ($nbasis == "per_week") {
                    $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                    $timeunits = $weeks;
                    $hours = 0;
                    if (empty($weeks) || !is_numeric($weeks)) {
                        return "<li class='err'><b>ERROR</b>: Invalid amount of weeks.</li>";
                    }
                } else {
                    return "<li class='err'><b>ERROR</b>: No basis selected.</li>";
                }
            }
        }
        /* calculate amount according to hire settings, quantity and time units */
        if ($nhalf_day) {
            $camt = $nqty * $timeunits * basisPrice($cusnum, $nasset_id, $nbasis) - basisPrice($cusnum, $nasset_id, $nbasis) + basisPrice($cusnum, $nasset_id, $nbasis) / 2;
        } else {
            $camt = $nqty * $timeunits * basisPrice($cusnum, $nasset_id, $nbasis);
        }
        /* insert item */
        $sql = "SELECT asset_id FROM hire.hire_invitems WHERE invid='{$invid}' AND asset_id='{$nasset_id}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
        // No duplicate assets
        if (!pg_num_rows($asset_rslt)) {
            if (isHired($nasset_id)) {
                return "\r\n\t\t\t\t<li class='err'>\r\n\t\t\t\t\t<b>ERROR</b>: Asset has already hired out.\r\n\t\t\t\t</li>";
            }
            $sql = "\r\n\t\t\t\tINSERT INTO hire.hire_invitems (\r\n\t\t\t\t\tinvid, asset_id, qty, amt, from_date, to_date, basis, hours, weeks, \r\n\t\t\t\t\tcollection, half_day, weekends\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$nasset_id}', '{$nqty}', '{$camt}', '{$nhifrm}', '{$nhito}', '{$nbasis}', '{$hours}', '{$weeks}', \r\n\t\t\t\t\t'{$collection}', '{$nhalf_day}', '{$nweekends}'\r\n\t\t\t\t)";
            db_exec($sql) or errDie("Unable to create new invoice item.");
            $item_id = pglib_lastid("hire.hire_invitems", "id");
            $sql = "\r\n\t\t\t\tINSERT INTO hire.reprint_invitems (\r\n\t\t\t\t\tinvid, asset_id, qty, amt, from_date, to_date, basis, hours, weeks, \r\n\t\t\t\t\tcollection, half_day, weekends, item_id\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$nasset_id}', '{$nqty}', '{$camt}', '{$nhifrm}', '{$nhito}', '{$nbasis}', '{$hours}', '{$weeks}', \r\n\t\t\t\t\t'{$collection}', '{$nhalf_day}', '{$nweekends}', '{$item_id}'\r\n\t\t\t\t)";
            db_exec($sql) or errDie("Unable to create reprint invoice item.");
        }
    }
    if ($monthly == "true") {
        $sql = "DELETE FROM hire.monthly_invitems WHERE invid='{$invid}'";
        db_exec($sql) or errDie("Unable to remove monthly items.");
    } else {
        $sql = "SELECT * FROM hire.hire_invitems WHERE invid='{$invid}'";
        $mii_rslt = db_exec($sql) or errDie("Unable to retrieve inv items.");
        $sql = "DELETE FROM hire.monthly_invitems WHERE invid='{$invid}'";
        db_exec($sql) or errDie("Unable to remove monthly items.");
        while ($item = pg_fetch_array($mii_rslt)) {
            $sql = "\r\n\t\t\t\tINSERT INTO hire.monthly_invitems (\r\n\t\t\t\t\tinvid, asset_id, qty, amt, from_date, to_date, \r\n\t\t\t\t\tbasis, hours, weeks, collection, half_day, \r\n\t\t\t\t\tweekends, item_id\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$item['invid']}', '{$item['asset_id']}', '{$item['qty']}', '{$item['amt']}', '{$item['from_date']}', '{$item['to_date']}', \r\n\t\t\t\t\t'{$item['basis']}', '{$item['hours']}', '{$item['weeks']}', '{$item['collection']}', '{$item['half_day']}', \r\n\t\t\t\t\t'{$item['weekends']}', '{$item['id']}'\r\n\t\t\t\t)";
            db_exec($sql) or errDie("Unable to create monthly items.");
        }
    }
    $sql = "SELECT * FROM hire.reprint_invoices WHERE invid='{$invid}'";
    $ri_rslt = db_exec($sql) or errDie("Unable to retrieve reprints.");
    // Create a new entry, or update
    if (pg_num_rows($ri_rslt)) {
        $sql = "\r\n\t\t\tUPDATE hire.reprint_invoices \r\n\t\t\tSET deptid='{$invb['deptid']}', cusnum='{$invb['cusnum']}', deptname='{$invb['deptname']}', cusacc='{$invb['cusacc']}', \r\n\t\t\t\tcusname='{$invb['cusname']}', surname='{$invb['surname']}', cusaddr='{$invb['cusaddr']}', cusvatno='{$invb['cusvatno']}', \r\n\t\t\t\tcordno='{$invb['cordno']}', ordno='{$invb['ordno']}', chrgvat='{$invb['chrgvat']}', terms='{$invb['terms']}', \r\n\t\t\t\ttraddisc='{$invb['traddisc']}', salespn='{$invb['salespn']}', odate='{$invb['odate']}', delchrg='{$invb['delchrg']}', \r\n\t\t\t\tsubtot='{$invb['subtot']}', vat='{$invb['vat']}', total='{$invb['total']}', balance='{$invb['balance']}', \r\n\t\t\t\tcomm='{$invb['comm']}', printed='{$invb['printed']}', done='{$invb['done']}', div='{$invb['div']}', \r\n\t\t\t\tusername='******'username']}', rounding='{$invb['rounding']}', delvat='{$invb['delvat']}', vatnum='{$invb['vatnum']}', \r\n\t\t\t\tpcash='{$invb['pcash']}', pcheque='{$invb['pcheque']}', pcc='{$invb['pcc']}', pcredit='{$invb['pcredit']}' \r\n\t\t\tWHERE invid='{$invid}'";
        db_exec($sql) or errDie("Unable to update reprint.");
    } else {
        $sql = "\r\n\t\t\tINSERT INTO hire.reprint_invoices(\r\n\t\t\t\tinvid, invnum, deptid, cusnum, deptname, cusacc, \r\n\t\t\t\tcusname, surname, cusaddr, cusvatno, cordno, ordno, \r\n\t\t\t\tchrgvat, terms, traddisc, salespn, odate, delchrg, \r\n\t\t\t\tsubtot, vat, total, balance, comm, printed, done, div, \r\n\t\t\t\tusername, rounding, delvat, vatnum, pcash, pcheque, \r\n\t\t\t\tpcc, pcredit\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$invid}', '{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', \r\n\t\t\t\t'{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}', \r\n\t\t\t\t'{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', \r\n\t\t\t\t'{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', 'y', 'y', '" . USER_DIV . "', \r\n\t\t\t\t'" . USER_NAME . "', '{$invb['rounding']}', '{$invb['delvat']}', '{$invb['vatnum']}', '{$invb['pcash']}', '{$invb['pcheque']}', \r\n\t\t\t\t'{$invb['pcc']}', '{$invb['pcredit']}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to add reprint.");
    }
    $sql = "SELECT * FROM hire.monthly_invoices\r\n\t\t\tWHERE invid='{$invid}' OR invnum='{$invb['invnum']}'";
    $mi_rslt = db_exec($sql) or errDie("Unable to retrieve monthly.");
    // Should we create a new entry
    if (pg_num_rows($mi_rslt)) {
        $sql = "\r\n\t\t\tUPDATE hire.monthly_invoices \r\n\t\t\tSET deptid='{$invb['deptid']}', cusnum='{$invb['cusnum']}', deptname='{$invb['deptname']}', cusacc='{$invb['cusacc']}', \r\n\t\t\t\tcusname='{$invb['cusname']}', surname='{$invb['surname']}', cusaddr='{$invb['cusaddr']}', cusvatno='{$invb['cusvatno']}', \r\n\t\t\t\tcordno='{$invb['cordno']}', ordno='{$invb['ordno']}', chrgvat='{$invb['chrgvat']}', terms='{$invb['terms']}', \r\n\t\t\t\ttraddisc='{$invb['traddisc']}', salespn='{$invb['salespn']}', odate='{$invb['odate']}', delchrg='{$invb['delchrg']}', \r\n\t\t\t\tsubtot='{$invb['subtot']}', vat='{$invb['vat']}', total='{$invb['total']}', balance='{$invb['balance']}', \r\n\t\t\t\tcomm='{$invb['comm']}', printed='{$invb['printed']}', done='{$invb['done']}', div='{$invb['div']}', \r\n\t\t\t\tusername='******'username']}', rounding='{$invb['rounding']}', delvat='{$invb['delvat']}', vatnum='{$invb['vatnum']}', \r\n\t\t\t\tpcash='{$invb['pcash']}', pcheque='{$invb['pcheque']}', pcc='{$invb['pcc']}', pcredit='{$invb['pcredit']}', \r\n\t\t\t\thire_invid='{$invid}' \r\n\t\t\tWHERE invid='{$invb['invid']}'";
    } elseif (empty($monthly)) {
        $sql = "\r\n\t\t\t\tINSERT INTO hire.monthly_invoices (\r\n\t\t\t\t\tinvid, invnum, deptid, cusnum, deptname, cusacc, \r\n\t\t\t\t\tcusname, surname, cusaddr, cusvatno, cordno, \r\n\t\t\t\t\tordno, chrgvat, terms, traddisc, salespn, odate, \r\n\t\t\t\t\tdelchrg, subtot, vat, total, balance, comm, \r\n\t\t\t\t\tprinted, done, div, username, rounding, delvat, vatnum, \r\n\t\t\t\t\tpcash, pcheque, pcc, pcredit, invoiced_month, hire_invid\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', \r\n\t\t\t\t\t'{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', \r\n\t\t\t\t\t'{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', \r\n\t\t\t\t\t'{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', \r\n\t\t\t\t\t'y', 'y', '" . USER_DIV . "', '" . USER_NAME . "', '{$invb['rounding']}', '{$invb['delvat']}', '{$invb['vatnum']}', \r\n\t\t\t\t\t'{$invb['pcash']}', '{$invb['pcheque']}', '{$invb['pcc']}', '{$invb['pcredit']}', '" . date("m") . "', '{$invid}'\r\n\t\t\t\t)";
    }
    db_exec($sql) or errDie("Unable to store monthly invoice.");
    pglib_transaction("COMMIT");
    if (isset($upBtn)) {
        if ($upBtn == "Return") {
            return returnHire();
        } elseif ($upBtn == "Invoice") {
            return invoiceHire();
        }
    }
    return false;
}
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 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 update($_POST)
{
    extract($_POST);
    $collect_ar = array();
    if (!empty($client_collect)) {
        $collect_ar[] = "Client Collect";
    }
    if (!empty($collect)) {
        $collect_ar[] = "Collect";
    }
    if (!empty($deliver)) {
        $collect_ar[] = "Deliver";
    }
    $collection = implode(", ", $collect_ar);
    // 	if ((in_array("Collect", $collect_ar) && in_array("Client Collect", $collect_ar))
    // 		|| (count($collect_ar) == 3)) {
    // 		return "<li class='err'>Invalid collection options selected.</li>";
    // 	}
    if (count($collect_ar) > 1 && in_array("Client Collect", $collect_ar)) {
        return "<li class='err'>Invalid collection options selected.</li>";
    }
    $temp_assets = explode(",", $temp_assets);
    pglib_transaction("BEGIN");
    // Stock Sales
    if (isset($snremove) && is_array($snremove)) {
        foreach ($snremove as $id => $value) {
            $sql = "DELETE FROM hire.hire_stock_items WHERE id='{$id}'";
            db_exec($sql) or errDie("Unable to remove stock item.");
        }
    }
    if (isset($snstock) && $snstock > 0) {
        if (!is_numeric($snqty)) {
            $snqty = 1;
        }
        #get vatperc for this item
        $get_vatp = "SELECT vat_amount FROM vatcodes WHERE id = '{$snvatcode}' LIMIT 1";
        $run_vatp = db_exec($get_vatp) or errDie("Unable to get vat code information.");
        if (pg_numrows($run_vatp) < 1) {
            $vatperc = 0;
        } else {
            $vatperc = pg_fetch_result($run_vatp, 0, 0);
        }
        //		$sql = "SELECT selamt FROM cubit.stock WHERE stkid='$snstock'";
        //		$price_rslt = db_exec($sql) or errDie("Unable to retrieve price.");
        //		$price = pg_fetch_result($price_rslt, 0);
        $price = get_excl_stock($snstock) * $snqty;
        $excl_price = get_excl_stock($snstock) * $snqty;
        $vatamount = sprint($excl_price / 100 * $vatperc);
        $price += 0;
        $price += sprint($excl_price / 100 * $vatperc);
        $snamt = $price * $snqty;
        #hack, because stores functionality isnt working ...
        $get_store = "SELECT whid FROM stock WHERE stkid = '{$snstock}' LIMIT 1";
        $run_store = db_exec($get_store) or errDie("Unable to get stock store information.");
        $snstore = pg_fetch_result($run_store, 0, 0);
        $sql = "\r\n\t\t\tINSERT INTO hire.hire_stock_items (\r\n\t\t\t\twhid, invid, stkid, qty, vatcode, unitcost, \r\n\t\t\t\tamount, excl_amount, vatamount\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$snstore}', '{$invid}', '{$snstock}', '{$snqty}', '{$snvatcode}', '" . sprint($price / $snqty) . "', \r\n\t\t\t\t'" . sprint($snamt / $snqty) . "', '{$excl_price}', '{$vatamount}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to add stock.");
        $sql = "UPDATE cubit.stock SET alloc=(alloc+'{$snqty}') WHERE stkid='{$snstock}'";
        db_exec($sql) or errDie("Unable to update stock allocation.");
    }
    if (isset($nhalf_day) && $nhalf_day == "checked") {
        $nhalf_day = 1;
    } else {
        $nhalf_day = 0;
    }
    if (isset($nweekends) && $nweekends == "checked") {
        $nweekends = 1;
    } else {
        $nweekends = 0;
    }
    $sql = "UPDATE hire.hire_invoices SET comm='{$comm}' WHERE invid='{$invid}'";
    $comm_rslt = db_exec($sql) or errDie("Unable to retrieve invoice.");
    foreach ($temp_assets as $key => $value) {
        $sql = "SELECT * FROM cubit.assets WHERE id='{$key}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
        $asset_data = pg_fetch_array($asset_rslt);
    }
    if (isset($amount)) {
        foreach ($amount as $key => $value) {
            // 			if (empty($monthly)) {
            // 				$amount[$key] = "";
            // 			}
            #redundant code ... breaks new hire if you click update multiple times (sets item amount = 0 after second update)
            //			if (!user_is_admin(USER_ID)) {
            //				$amount[$key] = "";
            //			}
            if (!isset($half_day[$key]) || empty($half_day[$key])) {
                $half_day[$key] = 0;
            }
            if (!isset($weekends[$key]) || empty($weekends[$key])) {
                $weekends[$key] = 0;
            } else {
                $weekends[$key] = 1;
            }
            if (!isset($total_days[$key]) || empty($total_days[$key])) {
                $epoch_from = strtotime($from_date[$key]);
                $epoch_to = strtotime($to_date[$key]);
                $total_days[$key] = ($epoch_to - $epoch_from) / (60 * 60 * 24) + 1;
                $total_days[$key] = ceil($total_days[$key]);
            }
            $sql = "SELECT qty, total_days, half_day FROM hire.hire_invitems WHERE id='{$key}'";
            $old_rslt = db_exec($sql) or errDie("Unable to retrieve old qty.");
            list($oldqty, $olddays, $oldhalf_day) = pg_fetch_array($old_rslt);
            if (!isset($oldqty)) {
                $oldqty = 1;
            }
            if (!isset($qty[$key])) {
                $oldqty = 1;
                $qty[$key] = 1;
            }
            if ($half_day[$key]) {
                $half_day[$key] = 1;
                $recalc = FALSE;
            } else {
                $half_day[$key] = 0;
            }
            if (empty($amount) && $amount != 0 || $oldqty != $qty[$key] || $olddays != $total_days[$key] || (!isset($amount[$key]) or empty($amount[$key])) || $half_day == 1) {
                if ($basis[$key] == "per_day") {
                    $to_time = strtotime($from_date[$key]) + $total_days[$key] * (60 * 60 * 24);
                    $hifrm = "{$mfrm_year[$key]}-{$mfrm_month[$key]}-{$mfrm_day[$key]}";
                    $hito = date("Y-m-d", $to_time);
                    $hours = "0";
                    /* calculate amount */
                    $ftime = getDTEpoch("{$hifrm} 0:00:00");
                    $ttime = getDTEpoch("{$hito} 0:00:00");
                    $days = 0;
                    $weeks = 0;
                    $months = 0;
                    while ($ftime <= $ttime) {
                        if (date("w", $ftime) == 0 && isset($weekends[$key]) && $weekends[$key]) {
                            $days += 0.6;
                        } else {
                            ++$days;
                        }
                        $ftime += 24 * 60 * 60;
                    }
                    $timeunits = $total_days[$key];
                } else {
                    if ($basis[$key] == "per_hour") {
                        $hifrm = $hito = mkdate($pinv_year, $pinv_month, $pinv_day);
                        $timeunits = $hours;
                        $weeks = 0;
                        $months = 0;
                        if (empty($hours) || !is_numeric($hours)) {
                            return "<li class='err'><b>ERROR</b>: Invalid amount of hours.</li>";
                        }
                    } else {
                        if ($nbasis == "per_week") {
                            $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                            $timeunits = $weeks;
                            $hours = 0;
                            $months = 0;
                            if (empty($weeks) || !is_numeric($weeks)) {
                                return "<li class='err'><b>ERROR</b>: Invalid amount of weeks.</li>";
                            }
                        } else {
                            if ($nbasis == "per_month") {
                                $nhifrm = $nhito = mkDate($pinv_year, $pinv_month, $pinv_day);
                                $timeunits = $months;
                                $weeks = 0;
                                $hours = 0;
                                if (empty($months) || !is_numeric($months)) {
                                    return "<li class='err'><b>ERROR</b>: Invalid amount of months.</li>";
                                }
                            }
                        }
                    }
                }
                if ($half_day[$key]) {
                    //					$amount[$key] = ($qty[$key] * $timeunits * (basisPrice($cusnum, $asset_id[$key], $basis[$key]) * $qty[$key]) - (basisPrice($cusnum, $asset_id[$key], $basis[$key]) * $qty[$key]) + ((basisPrice($cusnum, $asset_id[$key], $basis[$key]) * $qty[$key])) / halfday_rate());
                    $amount[$key] = sprint($qty[$key] * ($timeunits * basisPrice($cusnum, $asset_id[$key], $basis[$key]) - basisPrice($cusnum, $asset_id[$key], $basis[$key]) + basisPrice($cusnum, $asset_id[$key], $basis[$key]) / halfday_rate()));
                } else {
                    $amount[$key] = $qty[$key] * $timeunits * basisPrice($cusnum, $asset_id[$key], $basis[$key]);
                }
            }
            if ($amount[$key] == 0) {
                $amount[$key] = 0;
                $blank_amount = 1;
            } else {
                $blank_amount = 0;
            }
            $sql = "\r\n\t\t\t\tUPDATE hire.hire_invitems \r\n\t\t\t\tSET amt='{$amount[$key]}', half_day='{$half_day[$key]}', weekends='{$weekends[$key]}', \r\n\t\t\t\t\ttotal_days='{$total_days[$key]}', qty='{$qty[$key]}' \r\n\t\t\t\tWHERE id='{$key}'";
            db_exec($sql) or errDie("Unable to update item amount.");
            $sql = "\r\n\t\t\t\tUPDATE hire.reprint_invitems \r\n\t\t\t\tSET amt='{$amount[$key]}', half_day='{$half_day[$key]}', weekends='{$weekends[$key]}' \r\n\t\t\t\tWHERE item_id='{$key}'";
            db_exec($sql) or errDie("Unable to update return item amount.");
            if ($blank_amount) {
                $amount[$key] = "";
            }
            //$hifrm = "$hifrm_year[$key]-$hifrm_month[$key]-$hifrm_day[$key]";
            //$hito = "$hito_year[$key]-$hito_month[$key]-$hito_day[$key]";
            if (!isset($remove[$key])) {
                $sql = "SELECT basis FROM hire.hire_invitems WHERE id='{$key}'";
                $item_rslt = db_exec($sql) or errDie("Unable to retrieve basis.");
                $mbasis = pg_fetch_result($item_rslt, 0);
                /* determine time units */
                if ($mbasis == "per_day") {
                    $mfrm = mkdate($mfrm_year[$key], $mfrm_month[$key], $mfrm_day[$key]);
                    $mto = mkdate($mto_year[$key], $mto_month[$key], $mto_day[$key]);
                    /* calculate amount */
                    $ftime = mktime(0, 0, 0, $mfrm_month[$key], $mfrm_day[$key], $mfrm_year[$key]);
                    $ttime = mktime(0, 0, 0, $mto_month[$key], $mto_day[$key], $mto_year[$key]);
                    $days = 0;
                    if (empty($weeks)) {
                        $weeks = 0;
                    }
                    if (empty($hours)) {
                        $hours = 0;
                    }
                    if (empty($months)) {
                        $months = 0;
                    }
                    while ($ftime <= $ttime) {
                        if (date("w", $ftime) == 0 && isset($weekends[$key]) && $weekends[$key]) {
                            $days += 0.6;
                        } else {
                            ++$days;
                        }
                        $ftime += 24 * 60 * 60;
                    }
                    $timeunits = $days;
                    $sql = "\r\n\t\t\t\t\t\tUPDATE hire.hire_invitems \r\n\t\t\t\t\t\tSET from_date='{$mfrm}', to_date='{$mto}' \r\n\t\t\t\t\t\tWHERE id='{$key}'";
                    db_exec($sql) or errDie("Unable to update items.");
                    $sql = "\r\n\t\t\t\t\t\tUPDATE hire.reprint_invitems \r\n\t\t\t\t\t\tSET from_date='{$mfrm}', to_date='{$mto}' \r\n\t\t\t\t\t\tWHERE item_id='{$key}'";
                    db_exec($sql) or errDie("Unable to update reprint items.");
                }
            } else {
                // Delete the old items
                $sql = "DELETE FROM hire.hire_invitems WHERE id='{$key}'";
                db_exec($sql) or errDie("Unable to remove old items.");
                $sql = "DELETE FROM hire.reprint_invitems WHERE item_id='{$key}'";
                db_exec($sql) or errDie("Unable to remove old reprint items.");
                //.Remove if the item has been hired as well
                $sql = "DELETE FROM hire.assets_hired WHERE item_id='{$key}'";
                db_exec($sql) or errDie("Unable to remove items from hired log.");
            }
        }
    }
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$invid}'";
    $hi_rslt = db_exec($sql) or errDie("Unable to retrieve invoice.");
    $invb = pg_fetch_array($hi_rslt);
    // Default basis
    if (!empty($nasset_id) && $nbasis == "0") {
        list($serialqty, $tasset_id) = explode(":", $nasset_id);
        $nbasis = default_basis($tasset_id);
    }
    // Insert new items
    if ($nasset_id != "0") {
        if ($nasset_id == "0") {
            return "<li class='err'><b>ERROR</b>: No asset selected.</li>";
        }
        /* get asset id */
        list($serialqty, $nasset_id) = explode(":", $nasset_id);
        /* disabled items don't get passed through */
        if ($serialqty == "s" || !isset($nqty)) {
            $nqty = "1";
        } else {
            $sql = "SELECT serial2 FROM cubit.assets WHERE id='{$nasset_id}'";
            $dqty_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
            $dqty = pg_fetch_result($dqty_rslt, 0);
            if ($dqty - $nqty < 0) {
                return "<li class='err'><b>ERROR</b>: Invalid quantity. Only &nbsp; <b>{$dqty}</b> &nbsp; available.</li>";
            }
        }
        if (empty($nqty) || !is_numeric($nqty)) {
            return "<li class='err'><b>ERROR</b>: Invalid quantity</li>";
        }
        // Default basis
        if ($nbasis == "0") {
            $nbasis = default_basis($nasset_id);
        }
        /* determine time units */
        if ($nbasis == "per_day") {
            $nhifrm = mkdate($nhifrm_year, $nhifrm_month, $nhifrm_day);
            $nhito = mkdate($nhito_year, $nhito_month, $nhito_day);
            $hours = "0";
            /* calculate amount */
            $ftime = mktime(0, 0, 0, $nhifrm_month, $nhifrm_day, $nhifrm_year);
            $ttime = mktime(0, 0, 0, $nhito_month, $nhito_day, $nhito_year);
            $days = 0;
            $weeks = 0;
            $months = 0;
            while ($ftime <= $ttime) {
                if (date("w", $ftime) == 0 && isset($nweekends) && $nweekends) {
                    $days += 0.6;
                } else {
                    ++$days;
                }
                $ftime += 24 * 60 * 60;
            }
            $timeunits = $days;
        } else {
            if ($nbasis == "per_hour") {
                $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                $timeunits = $hours;
                $weeks = 0;
                $months = 0;
                if (empty($hours) || !is_numeric($hours)) {
                    return "<li class='err'><b>ERROR</b>: Invalid amount of hours.</li>";
                }
            } else {
                if ($nbasis == "per_week") {
                    $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                    $timeunits = $weeks;
                    $hours = 0;
                    $months = 0;
                    if (empty($weeks) || !is_numeric($weeks)) {
                        return "<li class='err'><b>ERROR</b>: Invalid amount of weeks.</li>";
                    }
                } else {
                    if ($nbasis == "per_month") {
                        $nhifrm = $nhito = mkdate($pinv_year, $pinv_month, $pinv_day);
                        $timeunits = $months;
                        $hours = 0;
                        $weeks = 0;
                        if (empty($months) || !is_numeric($months)) {
                            return "<li class='err'><b>ERROR</b>: Invalid amount of months.</li>";
                        }
                    } else {
                        return "<li class='err'><b>ERROR</b>: No basis selected.</li>";
                    }
                }
            }
        }
        /* calculate amount according to hire settings, quantity and time units */
        if ($nhalf_day) {
            $camt = $nqty * $timeunits * basisPrice($cusnum, $nasset_id, $nbasis) - basisPrice($cusnum, $nasset_id, $nbasis) + basisPrice($cusnum, $nasset_id, $nbasis) / halfday_rate();
        } else {
            $camt = $nqty * $timeunits * basisPrice($cusnum, $nasset_id, $nbasis);
        }
        /* insert item */
        $sql = "SELECT asset_id FROM hire.hire_invitems\r\n\t\t\t\tWHERE invid='{$invid}' AND asset_id='{$nasset_id}'";
        $asset_rslt = db_exec($sql) or errDie("Unable to retrieve assets.");
        // No duplicate assets
        if (!pg_num_rows($asset_rslt) || !isSerialized($nasset_id)) {
            if (isHired($nasset_id)) {
                return "\r\n\t\t\t\t<li class='err'>\r\n\t\t\t\t\t<b>ERROR</b>: Asset has already hired out.\r\n\t\t\t\t</li>";
            }
            $sql = "\r\n\t\t\t\tINSERT INTO hire.hire_invitems (\r\n\t\t\t\t\tinvid, asset_id, qty, amt, from_date, to_date, basis, hours, weeks, \r\n\t\t\t\t\tmonths, collection, half_day, weekends\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$nasset_id}', '{$nqty}', '{$camt}', '{$nhifrm}', '{$nhito}', '{$nbasis}', '{$hours}', '{$weeks}', \r\n\t\t\t\t\t'{$months}', '{$collection}', '{$nhalf_day}', '{$nweekends}'\r\n\t\t\t\t)";
            db_exec($sql) or errDie("Unable to create new invoice item.");
            $item_id = pglib_lastid("hire.hire_invitems", "id");
            $sql = "\r\n\t\t\t\tINSERT INTO hire.reprint_invitems (\r\n\t\t\t\t\tinvid, asset_id, qty, amt, from_date, to_date, basis, hours, weeks, \r\n\t\t\t\t\tmonths, collection, half_day, weekends, item_id\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$nasset_id}', '{$nqty}', '{$camt}', '{$nhifrm}', '{$nhito}', '{$nbasis}', '{$hours}', '{$weeks}', \r\n\t\t\t\t\t'{$months}', '{$collection}', '{$nhalf_day}', '{$nweekends}', '{$item_id}'\r\n\t\t\t\t)";
            db_exec($sql) or errDie("Unable to create reprint invoice item.");
        }
    }
    if ($monthly == "true") {
        $sql = "DELETE FROM hire.monthly_invitems WHERE invid='{$invid}'";
        db_exec($sql) or errDie("Unable to remove monthly items.");
    } else {
        $sql = "SELECT * FROM hire.hire_invitems WHERE invid='{$invid}'";
        $mii_rslt = db_exec($sql) or errDie("Unable to retrieve inv items.");
        $sql = "DELETE FROM hire.monthly_invitems WHERE invid='{$invid}'";
        db_exec($sql) or errDie("Unable to remove monthly items.");
        while ($item = pg_fetch_array($mii_rslt)) {
            $sql = "\r\n\t\t\t\tINSERT INTO hire.monthly_invitems (\r\n\t\t\t\t\tinvid, asset_id, qty, amt, from_date, to_date, \r\n\t\t\t\t\tbasis, hours, weeks, months, collection, half_day, \r\n\t\t\t\t\tweekends, item_id, invnum\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$item['invid']}', '{$item['asset_id']}', '{$item['qty']}', '{$item['amt']}', '{$item['from_date']}', '{$item['to_date']}', \r\n\t\t\t\t\t'{$item['basis']}', '{$item['hours']}', '{$item['weeks']}', '{$item['months']}', '{$item['collection']}', '{$item['half_day']}',\r\n\t\t\t\t\t'{$item['weekends']}', '{$item['id']}', '{$invb['invnum']}'\r\n\t\t\t\t)";
            db_exec($sql) or errDie("Unable to create monthly items.");
        }
    }
    $sql = "SELECT * FROM hire.reprint_invoices WHERE invid='{$invid}'";
    $ri_rslt = db_exec($sql) or errDie("Unable to retrieve reprints.");
    // Create a new entry, or update
    if (pg_num_rows($ri_rslt)) {
        $sql = "\r\n\t\t\tUPDATE hire.reprint_invoices \r\n\t\t\tSET deptid='{$invb['deptid']}', cusnum='{$invb['cusnum']}', deptname='{$invb['deptname']}', cusacc='{$invb['cusacc']}',\r\n\t\t\t\tcusname='{$invb['cusname']}', surname='{$invb['surname']}', cusaddr='{$invb['cusaddr']}', cusvatno='{$invb['cusvatno']}', \r\n\t\t\t\tcordno='{$invb['cordno']}', ordno='{$invb['ordno']}', chrgvat='{$invb['chrgvat']}', terms='{$invb['terms']}', \r\n\t\t\t\ttraddisc='{$invb['traddisc']}', salespn='{$invb['salespn']}', odate='{$invb['odate']}', delchrg='{$delchrg}', \r\n\t\t\t\tsubtot='{$invb['subtot']}', vat='{$invb['vat']}', total='{$invb['total']}', balance='{$invb['balance']}', \r\n\t\t\t\tcomm='{$invb['comm']}', printed='{$invb['printed']}', done='{$invb['done']}', div='{$invb['div']}', \r\n\t\t\t\tusername='******'username']}', rounding='{$invb['rounding']}', delvat='{$invb['delvat']}', vatnum='{$invb['vatnum']}', \r\n\t\t\t\tpcash='{$invb['pcash']}', pcheque='{$invb['pcheque']}', pcc='{$invb['pcc']}', pcredit='{$invb['pcredit']}' \r\n\t\t\tWHERE invid='{$invid}'";
        db_exec($sql) or errDie("Unable to update reprint.");
    } else {
        $sql = "\r\n\t\t\tINSERT INTO hire.reprint_invoices (\r\n\t\t\t\tinvid, invnum, deptid, cusnum, deptname, cusacc, \r\n\t\t\t\tcusname, surname, cusaddr, cusvatno, cordno, ordno, \r\n\t\t\t\tchrgvat, terms, traddisc, salespn, odate, delchrg, \r\n\t\t\t\tsubtot, vat, total, balance, comm, printed, done, div, \r\n\t\t\t\tusername, rounding, delvat, vatnum, pcash, pcheque, \r\n\t\t\t\tpcc, pcredit\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$invid}', '{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', \r\n\t\t\t\t'{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}',\r\n\t\t\t\t'{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', \r\n\t\t\t\t'{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', 'y', 'y', '" . USER_DIV . "', \r\n\t\t\t\t'" . USER_NAME . "', '{$invb['rounding']}', '{$invb['delvat']}', '{$invb['vatnum']}', '{$invb['pcash']}', '{$invb['pcheque']}', \r\n\t\t\t\t'{$invb['pcc']}', '{$invb['pcredit']}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to add reprint.");
    }
    $sql = "SELECT * FROM hire.monthly_invoices WHERE invid='{$invid}' OR invnum='{$invb['invnum']}' AND invnum!=0";
    $mi_rslt = db_exec($sql) or errDie("Unable to retrieve monthly.");
    // Should we create a new entry
    if (pg_num_rows($mi_rslt)) {
        $sql = "\r\n\t\t\tUPDATE hire.monthly_invoices \r\n\t\t\tSET deptid='{$invb['deptid']}', cusnum='{$invb['cusnum']}', deptname='{$invb['deptname']}', cusacc='{$invb['cusacc']}', \r\n\t\t\t\tcusname='{$invb['cusname']}', surname='{$invb['surname']}', cusaddr='{$invb['cusaddr']}', cusvatno='{$invb['cusvatno']}', \r\n\t\t\t\tcordno='{$invb['cordno']}', ordno='{$invb['ordno']}', chrgvat='{$invb['chrgvat']}', terms='{$invb['terms']}', \r\n\t\t\t\ttraddisc='{$invb['traddisc']}', salespn='{$invb['salespn']}', odate='{$invb['odate']}', delchrg='{$invb['delchrg']}', \r\n\t\t\t\tsubtot='{$invb['subtot']}', vat='{$invb['vat']}', total='{$invb['total']}', balance='{$invb['balance']}', \r\n\t\t\t\tcomm='{$invb['comm']}', printed='{$invb['printed']}', done='{$invb['done']}', div='{$invb['div']}', \r\n\t\t\t\tusername='******'username']}', rounding='{$invb['rounding']}', delvat='{$invb['delvat']}', vatnum='{$invb['vatnum']}', \r\n\t\t\t\tpcash='{$invb['pcash']}', pcheque='{$invb['pcheque']}', pcc='{$invb['pcc']}', pcredit='{$invb['pcredit']}', \r\n\t\t\t\thire_invid='{$invid}' \r\n\t\t\tWHERE invid='{$invb['invid']}'";
    } elseif (empty($monthly)) {
        $sql = "\r\n\t\t\t\tINSERT INTO hire.monthly_invoices (\r\n\t\t\t\t\tinvid, invnum, deptid, cusnum, deptname, cusacc, \r\n\t\t\t\t\tcusname, surname, cusaddr, cusvatno, cordno, \r\n\t\t\t\t\tordno, chrgvat, terms, traddisc, salespn, \r\n\t\t\t\t\todate, delchrg, subtot, vat, total, balance, \r\n\t\t\t\t\tcomm, printed, done, div, username, rounding, delvat, \r\n\t\t\t\t\tvatnum, pcash, pcheque, pcc, pcredit, invoiced_month, \r\n\t\t\t\t\thire_invid\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$invid}', '{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', \r\n\t\t\t\t\t'{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', \r\n\t\t\t\t\t'{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', \r\n\t\t\t\t\t'{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}', '{$invb['total']}', '{$invb['balance']}', \r\n\t\t\t\t\t'{$invb['comm']}', 'y', 'y', '" . USER_DIV . "', '" . USER_NAME . "', '{$invb['rounding']}', '{$invb['delvat']}', \r\n\t\t\t\t\t'{$invb['vatnum']}', '{$invb['pcash']}', '{$invb['pcheque']}', '{$invb['pcc']}', '{$invb['pcredit']}', '" . date("m") . "', \r\n\t\t\t\t\t'{$invb['invid']}' \r\n\t\t\t\t)";
    }
    db_exec($sql) or errDie("Unable to store monthly invoice.");
    pglib_transaction("COMMIT");
    if (!isSerialized($nasset_id) && (!isset($_SESSION["ns"]) || !$_SESSION["ns"])) {
        $_SESSION["ns"] = 1;
    } else {
        $_SESSION["ns"] = 0;
    }
    if (isset($upBtn)) {
        if ($upBtn == "Return") {
            return returnHire();
        } elseif ($upBtn == "Invoice") {
            return invoiceHire();
        }
    }
    return false;
}
function updateAmounts($item_id)
{
    pglib_transaction("BEGIN");
    $sql = "SELECT *, cusnum\r\n\t\t\tFROM hire.hire_invitems\r\n\t\t\t\tLEFT JOIN hire.hire_invoices\r\n\t\t\t\t\tON hire_invitems.invid=hire_invoices.invid\r\n\t\t\tWHERE id='{$item_id}'";
    $item_rslt = db_exec($sql) or errDie("Unable to retrieve hire items.");
    $item = pg_fetch_array($item_rslt);
    if ($item["basis"] == "per_day") {
        $from_time = getDTEpoch("{$item['from_date']} 0:00:00");
        $to_time = getDTEpoch("{$item['to_date']} 23:59:59");
        $days = 0;
        $weeks = 0;
        while ($from_time <= $to_time) {
            if (date("w", $from_time) == 0 && $item["weekends"]) {
                $days += 0.6;
            } else {
                ++$days;
            }
            $from_time += 60 * 60 * 24;
        }
        $timeunits = ceil($days);
    } elseif ($item["basis"] == "per_week") {
        $timeunits = $item["weeks"];
    } elseif ($item["basis"] == "per_hour") {
        $timeunits = $item["hours"];
    }
    $amount = $item["qty"] * $timeunits * basisPrice($item["cusnum"], $item["asset_id"], $item["basis"]);
    if ($item["basis"] = "per_day") {
        $total_days = ",total_days='{$timeunits}'";
    } else {
        $total_days = "0";
    }
    $sql = "UPDATE hire.hire_invitems SET amt='{$amount}' {$total_days} WHERE id='{$item_id}'";
    db_exec($sql) or errDie("Unable to update hire items.");
    // Update totals
    $sql = "\r\n\tSELECT sum(amt) FROM hire.hire_invitems\r\n\tWHERE invid='{$item['invid']}'";
    $subtot_rslt = db_exec($sql) or errDie("Unable to retrieve subtotal.");
    $subtot = pg_fetch_result($subtot_rslt, 0);
    // Trade discount
    $sql = "SELECT traddisc FROM hire.hire_invoices WHERE invid='{$item['invid']}'";
    $disc_rslt = db_exec($sql) or errDie("Unable to retrieve discount.");
    $disc = pg_fetch_result($disc_rslt, 0);
    $traddiscamt = $subtot / 100 * $disc;
    $subtot = $subtot - $traddiscamt;
    $vat = $subtot / 100 * 14;
    $total = $subtot + $vat;
    $sql = "\r\n\tUPDATE hire.hire_invoices SET total='{$total}', vat='{$vat}',\r\n\t\tdiscount='{$traddiscamt}' \r\n\tWHERE invid='{$item['invid']}'";
    db_exec($sql) or errDie("Unable to update amounts.");
    pglib_transaction("COMMIT");
    return $amount;
}