function update($_POST)
{
    # Get Vars ( banked[] )
    extract($_POST);
    # check if anything is selected
    if (!isset($banked)) {
        $err = "<li class='err'> Please Select at least one entry to update.";
        return cashbook($_POST, $err);
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    $refnum = getrefnum();
    /*refnum*/
    db_conn('core');
    $rid = pglib_lastid("save_bank_recon", "id");
    $rid++;
    # Record all trans
    foreach ($banked as $key => $cashid) {
        # Connect to database
        db_Connect();
        $sql = "SELECT * FROM cashbook WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $cashRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve details from database.", SELF);
        $cash = pg_fetch_array($cashRslt);
        # Set record as banked
        db_connect();
        $sql = "UPDATE cashbook SET banked = 'yes',rid='{$rid}' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to set bank deposit as banked in Cubit.", SELF);
    }
    // Connect to database
    db_connect();
    $sql = "SELECT * FROM cashbook WHERE bankid = '{$bankid}' AND banked = 'no' AND div = '" . USER_DIV . "' ORDER BY date DESC";
    $cashRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank transactions from database.", SELF);
    $sql = "SELECT * FROM bankacct WHERE bankid= '{$bankid}' AND div = '" . USER_DIV . "'";
    $bankRslt = db_exec($sql);
    $bank = pg_fetch_array($bankRslt);
    $cur = CUR;
    $amtd = "amount";
    if ($bank['btype'] == 'int') {
        $currs = getSymbol($bank['fcid']);
        $cur = $currs['symbol'];
        $amtd = "famount";
    }
    $tot = 0;
    $totr = 0;
    $totp = 0;
    $recpts = "";
    $paymnts = "";
    while ($cash = pg_fetch_array($cashRslt)) {
        if ($cash['trantype'] == "deposit") {
            $recpts .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$cash['date']}</td>\n\t\t\t\t\t<td>{$cash['descript']}</td>\n\t\t\t\t\t<td align='right'>{$cur} {$cash[$amtd]}</td>\n\t\t\t\t</tr>";
            $totr += $cash[$amtd];
        } else {
            $paymnts .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$cash['date']}</td>\n\t\t\t\t\t<td>{$cash['descript']}</td>\n\t\t\t\t\t<td align='right'>{$cur} {$cash[$amtd]}</td>\n\t\t\t\t</tr>";
            $totp += $cash[$amtd];
        }
        $tot += $cash[$amtd];
    }
    $reconbal = sprint($cbal + ($totr - $totp));
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.";
    }
    $banklnk = pg_fetch_array($rslt);
    # Get bank balance
    $sql = "SELECT (debit - credit) as bal FROM trial_bal WHERE period='12' AND accid = '{$banklnk['accnum']}' AND div = '" . USER_DIV . "'";
    $brslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    $bal = pg_fetch_array($brslt);
    if ($bank['btype'] == 'int') {
        $bal['bal'] = $bank['fbalance'];
    }
    $diff = sprint($reconbal - $bal['bal']);
    $derr = "";
    if ($diff != 0) {
        $derr = "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><b class='err'>Bank statement and computer balance not balancing by</b></td>\n\t\t\t\t<td align='right'>{$cur} {$diff}</td>\n\t\t\t</tr>";
    }
    $totp = sprint($totp);
    // Layout
    $update = "\n\t\t<center>\n\t\t<h3>Bank Reconciliation Output</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form1'>\n\t\t\t<input type='hidden' name='key' value='save'>\n\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t<table cellpadding='2' cellspacing='0' border=0 bordercolor='#000000' width='80%'>\n\t\t\t<tr>\n\t\t\t\t<td colspan='10'>\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border=0 bordercolor='#000000' width=100%>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Bank Account : </b>{$bank['accname']}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td align='right'><b>Prepared By : </b>" . USER_NAME . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Closing Balance As per Bank Statement : </b>{$cur} {$cbal}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td><b>Plus Outstanding Receipts :</b></td>\n\t\t\t</tr>\n\t\t\t<!--<tr><th>Date</th><th>Reference</th><th>Amount</th></tr>-->\n\t\t\t{$recpts}\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='right'><b>Sub Total</b></td>\n\t\t\t\t<td align='right'>{$cur} {$totr}</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td><b>Less Outstanding Payments :</b></td>\n\t\t\t</tr>\n\t\t\t<!--<tr><th>Date</th><th>Reference</th><th>Amount</th></tr>-->\n\t\t\t{$paymnts}\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='right'><b>Sub Total</b></td>\n\t\t\t\t<td align='right'>{$cur} {$totp}</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br><td></tr>\n\t\t\t{$derr}\n\t\t\t<tr><td><br><td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><b>Reconciled Bank Balance</b></td>\n\t\t\t\t<td align='right'>{$cur} {$reconbal}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><b>Computer Bank Balance</b></td>\n\t\t\t\t<td align='right'>{$cur} {$bal['bal']}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><b>Diff</b></td>\n\t\t\t\t<td align='right'>{$cur} {$diff}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>";
    $upcode = base64_encode($update);
    $button = "</table></form>";
    core_connect();
    $gendate = date("Y-m-d");
    $sql = "\n\t\tINSERT INTO save_bank_recon (\n\t\t\tbankid, gendate, recon, div\n\t\t) VALUES (\n\t\t\t'{$bankid}', '{$gendate}', '{$upcode}', '" . USER_DIV . "'\n\t\t)";
    $saveRslt = db_exec($sql) or errDie("Unable to save bank recon to database", SELF);
    $update .= $button;
    $OUTPUT = $update;
    require "../tmpl-print.php";
}
function enterDeduct()
{
    # connect to db
    db_connect();
    # get last inserted id for new ref no
    // a little hack to make stoopid postgres not return a 1 as last id, when there is no last id
    if (pg_numrows(db_exec("SELECT 1 FROM salded")) < 1) {
        $lastid = 1;
    } else {
        $lastid = pglib_lastid("salded", "id") + 1;
    }
    $refno = "saldeduct" . sprintf("%02d", $lastid);
    $Tp = array("No" => "No", "Yes" => "Yes");
    $taxables = extlib_cpsel("taxable", $Tp, "No");
    $arrtype = array("Amount" => "Amount", "Percentage" => "Percentage");
    $seltype = extlib_cpsel("type", $arrtype, "Percentage");
    $check1 = "";
    $check2 = "";
    if (isset($type) and $type == "Percentage") {
        $check2 = "checked='yes'";
    } else {
        $check1 = "checked='yes'";
    }
    $enterDeduct = "\n\t\t<script>\n\t\t\tfunction inHouse() {\n\t\t\t\tfrm = getObjectById('dedfrm');\n\t\t\t\tfrm.creditor.value='In House';\n\t\t\t\tfrm.details.value='In House';\n\t\t\t}\n\t\t</script>\n\t\t<h3>New salary deduction</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<form id='dedfrm' action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t<input type='hidden' name='refno' value='{$refno}'>\n\t\t\t<input type='hidden' name='catid' value='B10'>\n\t\t\t<tr>\n\t\t\t\t<th>Field</th>\n\t\t\t\t<th>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Name of deduction</td>\n\t\t\t\t<td align='center'><input type='text' size='20' name='deduction'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Creditor name</td>\n\t\t\t\t<td align='center'><input type='text' size='20' name='creditor'></td>\n\t\t\t\t<td><input type='button' value='In House' onClick='inHouse();'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Reference no.</td>\n\t\t\t\t<td align='center'>{$refno}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Creditor Details/In House</td>\n\t\t\t\t<td align='center'><input type='text' size='20' name='details'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Before PAYE: Tax Deductable</td>\n\t\t\t\t<td align='center'>{$taxables}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Deduction Type</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='radio' name='type' value='Amount' {$check1}> Amount\n\t\t\t\t\t<input type='radio' name='type' value='Percentage' {$check2}> Percent\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='right'><input type='submit' value='Confirm &raquo;'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>" . mkQuickLinks(ql("../admin-employee-add.php", "Add Employee"), ql("../admin-employee-view.php", "View Employees"));
    return $enterDeduct;
}
function fromQuote()
{
    extract($_REQUEST);
    $sql = "INSERT INTO cubit.pick_slips (user_id) VALUES ('" . USER_ID . "')";
    $ps_rslt = db_exec($sql) or errDie("Unable to retrieve slips.");
    $ps_id = pglib_lastid("cubit.pick_slips", "id");
    $sql = "SELECT * FROM cubit.quote_items WHERE quoid='{$quoid}'";
    $quote_rslt = db_exec($sql) or errDie("Unable to retrieve quote items.");
    while ($quote_data = pg_fetch_array($quote_rslt)) {
        $sql = "INSERT INTO cubit.pickslip_stk (pickslip_id, stock_id, qty)\n\t\t\t\tVALUES ('{$ps_id}', '{$quote_data['stkid']}', '{$quote_data['qty']}')";
        db_exec($sql) or errDie("Unable to add pickslip.");
    }
    header("Location: " . SELF . "?key=print&slip_id={$ps_id}");
}
function import_file()
{
    extract($_REQUEST);
    $sql = "SELECT * FROM cubit.import_assets";
    $import_rslt = db_exec($sql) or errDie("Unable to retrieve import assets.");
    $counter = 0;
    while ($row = pg_fetch_array($import_rslt)) {
        $sql = "\r\n\t\t\tINSERT INTO cubit.assets (\r\n\t\t\t\tserial, locat, des, date, bdate, \r\n\t\t\t\tamount, div, grpid, accdep, dep_perc, \r\n\t\t\t\tdep_month, serial2, team_id, puramt, conacc, \r\n\t\t\t\tsaledate, saleamt, invid, autodepr_date, \r\n\t\t\t\tsdate, temp_asset, nonserial, type_id, \r\n\t\t\t\tsplit_from, days, on_hand, svdate\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$row['serial']}', '{$row['locat']}', '{$row['des']}', '{$row['date']}', '{$row['bdate']}', \r\n\t\t\t\t'{$row['amount']}', '{$row['div']}', '{$row['grpid']}', '{$row['accdep']}', '{$row['dep_perc']}', \r\n\t\t\t\t'{$row['dep_month']}', '{$row['serial2']}', '{$row['team_id']}', '{$row['puramt']}', '{$row['conacc']}', \r\n\t\t\t\t'{$row['saledate']}', '{$row['saleamt']}', '{$row['invid']}', '{$row['autodepr_date']}', \r\n\t\t\t\t'{$row['sdate']}', '{$row['temp_asset']}', '{$row['nonserial']}', '{$row['type_id']}', \r\n\t\t\t\t'{$row['split_from']}', '{$row['days']}', '{$row['on_hand']}', '{$row['svdate']}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to add asset.");
        $asset_id = pglib_lastid("cubit.assets", "id");
        $sql = "\r\n\t\t\tINSERT INTO hire.basis_prices (\r\n\t\t\t\tassetid, per_day, \r\n\t\t\t\tper_hour, per_week\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$asset_id}', '" . $per_day[$row["id"]] . "', \r\n\t\t\t\t'" . $per_hour[$row["id"]] . "', '" . $per_week[$row["id"]] . "'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to add price.");
        $counter++;
    }
    return "{$counter} Assets Have Been Imported.";
}
function write()
{
    extract($_REQUEST);
    if (!preg_match("/(png|jpg|gif)\$/", $_FILES["file"]["name"])) {
        $msg = "<li class='err'>We only accept images of type png, jpg or gif</li>";
        return enter($sorder_num, $msg);
    }
    $fp = fopen($_FILES["file"]["tmp_name"], "rb");
    $buf = "";
    while (!feof($fp)) {
        $buf .= fread($fp, 1024);
    }
    $file = base64_encode($buf);
    $sql = "INSERT INTO cubit.pslip_signed_files (file) VALUES ('{$file}')";
    db_exec($sql) or errDie("Unable to add signed invoice.");
    $id = pglib_lastid("cubit.pslip_signed_files", "id");
    $sql = "\n\t\tINSERT INTO cubit.pslip_signed_index (\n\t\t\tid, file_name, file_type, sordid\n\t\t) VALUES (\n\t\t\t'{$id}', '" . $_FILES["file"]["name"] . "', '" . $_FILES["file"]["type"] . "', '{$sordid}'\n\t\t)";
    db_exec($sql) or errDie("Unable to add signed invoice index.");
    $OUTPUT = "\n\t\t<h3>Signed Invoice</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Write</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><li>Signed Invoice Successfully Added.</li></td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
function enter()
{
    extract($_REQUEST);
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$_REQUEST['invid']}'";
    $inv_rslt = db_exec($sql) or errDie("Unable to retrieve invoices.");
    $inv_data = pg_fetch_array($inv_rslt);
    $sql = "SELECT * FROM cubit.customers WHERE cusnum='{$inv_data['cusnum']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customers.");
    $cust_data = pg_fetch_array($cust_rslt);
    $sql = "SELECT invid FROM hire.unsigned_hirenotes WHERE invid='{$invid}'";
    $uh_rslt = db_exec($sql) or errDie("Unable to retrieve unsinged hirenotes.");
    if (!pg_num_rows($uh_rslt)) {
        $sql = "INSERT INTO hire.unsigned_hirenotes (invid, trans_date, invnum,\r\n\t\t\t\t\tcusnum)\r\n\t\t\t\tVALUES ('{$inv_data['invid']}', '{$inv_data['odate']}',\r\n\t\t\t\t\t'" . getHirenum($inv_data["invid"]) . "', '{$inv_data['cusnum']}')";
        db_exec($sql) or errDie("Unable to create unsigned hire note.");
        $uh_id = pglib_lastid("hire.unsigned_hirenotes", "id");
    } else {
        $uh_id = pg_fetch_result($uh_rslt, 0);
    }
    $OUTPUT = "<h3>Signed Hire Note</h3>\r\n\t<form method='post' action='" . SELF . "' enctype='multipart/form-data'>\r\n\t<input type='hidden' name='key' value='write' />\r\n\t<input type='hidden' name='invid' value='{$invid}' />\r\n\t<input type='hidden' name='uh_id' value='{$uh_id}' />\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr>\r\n\t\t\t<th colspan='2'>Details</th>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>Hire No.</td>\r\n\t\t\t<td>H" . getHirenum($inv_data["invid"], 1) . "</td>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>Customer</td>\r\n\t\t\t<td>{$cust_data['cusname']} {$cust_data['surname']}</td>\r\n\t\t</tr>\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td>Signed Hire Note</td>\r\n\t\t\t<td><input type='file' name='file' /></td>\r\n\t\t</tr>\r\n\t\t<tr>\r\n\t\t\t<td colspan='2' align='right'>\r\n\t\t\t\t<input type='submit' value='Write &raquo' />\r\n\t\t\t</td>\r\n\t\t</tr>\r\n\t</table>\r\n\t</form>";
    return $OUTPUT;
}
function display()
{
    extract($_REQUEST);
    $doc_output = "\n\t<div style='width: 95%; background: #fff; border: 1px solid #000'>\n\t\t{$bodydata}\n\t</div>";
    $size = sizeof($bodydata);
    $document = base64_encode($bodydata);
    if (!$id) {
        $sql = "INSERT INTO cubit.documents (title, filename, status, team_id, wordproc)\n\t\tVALUES ('{$title}', '{$title}.html', 'active', '{$team_id}', 1)";
        db_exec($sql) or errDie("Unable to save document.");
        db_conn("cubit");
        $docid = pglib_lastid("documents", "docid");
    } else {
        $sql = "UPDATE cubit.documents\n\t\t\t\tSET title='{$title}', filename='{$title}.html', team_id='{$team_id}'\n\t\t\t\tWHERE docid='{$id}'";
        $doc_rslt = db_exec($sql) or errDie("Unable to save document.");
        $docid = $id;
    }
    $sql = "INSERT INTO cubit.document_files (doc_id, filename, file, size)\n\tVALUES ('{$docid}', '{$title}.html', '{$document}', '{$size}')";
    db_exec($sql) or errDie("Unable to save document.");
    $OUTPUT = "\n\tDocument Successfully Saved<br />\n\t{$doc_output}";
    return $OUTPUT;
}
function create_dummy($deptid, $spurnum, $spurtype, $spurprd)
{
    db_connect();
    # Dummy Vars
    $remarks = "";
    $supaddr = "";
    $terms = "0";
    $total = 0;
    $subtot = 0;
    $pdate = date("Y-m-d");
    $ddate = date("Y-m-d");
    $shipchrg = "0.00";
    $purnum = divlastid("pur", USER_DIV);
    # Insert purchase to DB
    $sql = "INSERT INTO nons_purchases(deptid, supplier, supaddr, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, remarks, received, done, prd, div, purnum, spurnum, spurtype, spurprd)";
    $sql .= " VALUES('{$deptid}', '',  '{$supaddr}', '{$terms}', '{$pdate}', '{$ddate}', '{$shipchrg}', '{$subtot}', '{$total}', '{$total}', 'yes', '0', '{$remarks}', 'n', 'n', '" . PRD_DB . "', '" . USER_DIV . "', '{$purnum}', '{$spurnum}', '{$spurtype}', '{$spurprd}')";
    $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Purchase to Cubit.", SELF);
    # Get next ordnum
    $purid = pglib_lastid("nons_purchases", "purid");
    return $purid;
}
function enterDeduct()
{
    # connect to db
    core_connect();
    $dedcat = "<select name='catid'>";
    $sql = "SELECT * FROM balance WHERE div = '" . USER_DIV . "'";
    $catRslt = db_exec($sql);
    if (pg_numrows($catRslt) < 1) {
        return "<li> There are no Balance Accounts categories yet in Cubit.";
    } else {
        while ($cat = pg_fetch_array($catRslt)) {
            if ($cat["catname"] == "Balance") {
                $selected = "selected";
            } else {
                $selected = "";
            }
            $dedcat .= "<option value='{$cat['catid']}' {$selected}>{$cat['catname']}</option>";
        }
    }
    $dedcat .= "</select>";
    # connect to db
    db_connect();
    # get last inserted id for new ref no
    // a little hack to make stoopid postgres not return a 1 as last id, when there is no last id
    if (pg_numrows(db_exec("SELECT 1 FROM salded")) < 1) {
        $lastid = 1;
    } else {
        $lastid = pglib_lastid("salded", "id") + 1;
    }
    $refno = "saldeduct" . sprintf("%02d", $lastid);
    $Tp = array("No" => "No", "Yes" => "Yes");
    $taxables = extlib_cpsel("taxable", $Tp, "No");
    $arrtype = array("Amount" => "Amount", "Percentage" => "Percentage");
    $seltype = extlib_cpsel("type", $arrtype, "Percentage");
    $enterDeduct = "<h3>New salary deduction</h3>\n        <table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n        <form action='" . SELF . "' method=post>\n        <input type=hidden name=key value=confirm>\n        <input type=hidden name=refno value='{$refno}'>\n        <tr><th>Field</th><th>Value</th></tr>\n        <tr class='bg-odd'><td>Name of deduction</td><td align=center><input type=text size=20 name=deduction></td></tr>\n        <tr class='bg-even'><td>Creditor name</td><td align=center><input type=text size=20 name=creditor></td></tr>\n        <tr class='bg-odd'><td>Reference no.</td><td align=center>{$refno}</td></tr>\n\t<tr class='bg-even'><td>Account Category</td><td align=center>{$dedcat}</td></tr>\n\t<tr class='bg-odd'><td>Creditor details</td><td align=center><input type=text size=20 name=details></td></tr>\n\t<tr class='bg-even'><td>Deduct Before PAYE</td><td align=center>{$taxables}</td></tr>\n\t<tr class='bg-odd'><td>Deduction Type</td><td>{$seltype}</td></tr>\n\n\t<tr><td colspan=2 align=right><input type=submit value='Confirm &raquo;'></td></tr>\n        </form></table>" . mkQuickLinks(ql("../admin-employee-add.php", "Add Employee"), ql("../admin-employee-view.php", "View Employees"));
    return $enterDeduct;
}
function create($topacc, $accnum, $accname, $catid, $acctype, $vat)
{
    # Check Account name on selected type and category
    $sql = "SELECT * FROM accounts WHERE topacc = '{$topacc}' AND accnum = '{$accnum}'";
    $cRslt = db_exec($sql) or errDie("Unable to retrieve Account details from database.");
    if (pg_numrows($cRslt) > 0) {
        return 1;
    }
    $sql = "SELECT * FROM accounts WHERE accname = '{$accname}'";
    $cRslt = db_exec($sql) or errDie("Unable to retrieve Account details from database.");
    if (pg_numrows($cRslt) > 0) {
        return 2;
    }
    # write to DB
    $Sql = "INSERT INTO accounts (topacc, accnum, accname, acctype, catid, vat) VALUES ('{$topacc}', '{$accnum}', '{$accname}', '{$acctype}', '{$catid}', '{$vat}')";
    $accRslt = db_exec($Sql) or errDie("Unable to add Account to Database.", SELF);
    # get last inserted id for new acc
    $accid = pglib_lastid("accounts", "accid");
    # insert account into trial Balance
    $query = "INSERT INTO trial_bal(accid, topacc, accnum, accname, vat) VALUES('{$accid}', '{$topacc}', '{$accnum}', '{$accname}', '{$vat}')";
    $trialRslt = db_exec($query);
    # return Zero on success
    return 0;
}
function scan()
{
    // Check setting
    $sql = "SELECT set FROM cubit.picking_slip_setting";
    $setting_rslt = db_exec($sql) or errDie("Unable to retrieve setting.");
    $setting = pg_fetch_result($setting_rslt, 0);
    if ($setting == "n") {
        header("Location: picking_slip_settings.php");
    }
    $invoice = array("invoice" => "Scan Invoice");
    list($barcode) = array_values(flashRed($invoice));
    $sordid = decrypt_barcode($barcode);
    if (empty($sordid) || !is_numeric($sordid)) {
        $sordid = 0;
    }
    // Has this invoice been scanned before
    $sql = "SELECT id FROM cubit.pslip_scans WHERE sordid='{$sordid}'";
    $scan_rslt = db_exec($sql) or errDie("Unable to retrieve scans.");
    $sql = "SELECT sordid FROM cubit.sorders WHERE sordid='{$sordid}'";
    $sorder_rslt = db_exec($sql) or errDie("Unable to retrieve sales order.");
    if (pg_num_rows($sorder_rslt)) {
        $reason = "";
        if (pg_num_rows($scan_rslt)) {
            $reason = "DUPLICATE (No reason)";
        }
        $sql = "\n\t\t\tINSERT INTO cubit.pslip_scans (\n\t\t\t\tsordid, timestamp, userid, reason\n\t\t\t) VALUES (\n\t\t\t\t'{$sordid}', current_timestamp, '" . USER_ID . "', '{$reason}'\n\t\t\t)";
        db_exec($sql) or errDie("Unable to record scan.");
    } else {
        return scan_error();
    }
    if (pg_num_rows($scan_rslt)) {
        $scan_id = pglib_lastid("cubit.pslip_scans", "id");
        return reason($scan_id);
    }
    return dispatch($sordid);
}
Example #12
0
function write_sets($_POST)
{
    global $catids, $CUBIT_MODULES;
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($smonth, "num", 1, 2, "Invalid Financial year starting month.");
    /*$v->isOk ($monthend,"num",1 ,2, "Invalid month end date");
    	$v->isOk ($int1,"float",1 ,5, "Invalid interest 1.");
    	$v->isOk ($int2,"float",1 ,5, "Invalid interest 2.");
    	$v->isOk ($int3,"float",1 ,5, "Invalid interest 3.");
    	$v->isOk ($brack1,"float",1 ,10, "Invalid bracket 1.");
    	$v->isOk ($brack2,"float",1 ,10, "Invalid bracket 2.");*/
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $confirmCust;
    }
    pglib_transaction("BEGIN");
    makemap($smonth);
    core_connect();
    $sql = "SELECT accname FROM accounts WHERE accnum != '999' AND div = '" . USER_DIV . "'";
    $Rslt = db_exec($sql) or errDie("Unable to check database for existing accounts.");
    if (pg_numrows($Rslt) > 0) {
        $acc = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><li class='err'>ERROR : There are already accounts in Cubit</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t" . TBL_BR . "\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Note : </th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Quick Setup can only be run on a new cubit installation.</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t" . TBL_BR . "\n\t\t\t\t\t</table>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='15%'>\n\t\t\t\t\t\t" . TBL_BR . "\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t</table>";
        return $acc;
    }
    $sql = "\n\t\tINSERT INTO cubit.compinfo (\n\t\t\tcompname, slogan, logoimg, addr1, addr2, addr3, \n\t\t\taddr4, paddr1, paddr2, paddr3, tel, fax, \n\t\t\tvatnum, regnum, imgtype, img, div, paye, \n\t\t\tterms, postcode, img2, imgtype2, logoimg2, diplomatic_indemnity\n\t\t) VALUES (\n\t\t\t'{$_SESSION['comp']}', '', '', '', '', '', \n\t\t\t'', '', '', '', '', '',\n\t\t\t'', '', '', '', '" . USER_DIV . "', '', \n\t\t\t'', '', '', '', '', 'N'\n\t\t);";
    db_exec($sql) or errDie("Unable to update company information.");
    db_conn('cubit');
    $sql = "SELECT label FROM set WHERE label = 'ACCNEW_LNK' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to check database for existing account creation settings.");
    if (pg_num_rows($rslt) > 0) {
        $sql = "\n\t\t\tUPDATE set \n\t\t\tSET value = 'acc-new2.php', type = 'Account Creation' \n\t\t\tWHERE label = 'ACCNEW_LNK'";
    } else {
        $sql = "\n\t\t\tINSERT INTO set (\n\t\t\t\ttype, label, value, \n\t\t\t\tdescript, div\n\t\t\t) VALUES (\n\t\t\t\t'Account Creation', 'ACCNEW_LNK', 'acc-new2.php', \n\t\t\t\t'Use user selected account numbers', '" . USER_DIV . "'\n\t\t\t)";
    }
    db_exec($sql) or errDie("Unable to insert account creation settings to Cubit.");
    /* account categories */
    $catids = array("I" => 0, "E" => 0, "B" => 0);
    $sql = "\n\t\tINSERT INTO core.income (\n\t\t\tcatid, catname, div\n\t\t) VALUES (\n\t\t\t'I' || nextval('core.income_seq'), 'Income', '" . USER_DIV . "'\n\t\t)";
    $catRslt = db_exec($sql) or errDie("Unable to add income Category to Database.");
    $catids["I"] = "I" . pglib_getlastid("core.income_seq");
    $sql = "\n\t\tINSERT INTO core.expenditure (\n\t\t\tcatid, catname, div\n\t\t) VALUES (\n\t\t\t'E' || nextval('core.expenditure_seq'),'Expenditure', '" . USER_DIV . "'\n\t\t)";
    $catRslt = db_exec($sql) or errDie("Unable to add expense Category to Database.");
    $catids["E"] = "E" . pglib_getlastid("core.expenditure_seq");
    $sql = "\n\t\tINSERT INTO core.balance (\n\t\t\tcatid, catname, div\n\t\t) VALUES (\n\t\t\t'B' || nextval('core.balance_seq'),'Balance', '" . USER_DIV . "'\n\t\t)";
    $catRslt = db_exec($sql) or errDie("Unable to add balance Category to Database.");
    $catids["B"] = "B" . pglib_getlastid("core.balance_seq");
    /* START SETUP */
    $catid = $catids["I"];
    $sales_account = newacc("1000", "000", "Sales", "I", "f", "sales");
    $pos_sales_account = newacc("1100", "000", "Point of Sale - Sales", "I", "f", "sales");
    newacc("1150", "000", "Interest Received", "I", "f");
    newacc("1200", "000", "Sundry Income", "I", "f");
    newacc("1250", "000", "Exchange Rate Profit/Loss", "I", "f", "other_income");
    newacc("1300", "000", "Sale of Assets", "I", "f", "sales");
    linkacc("1300", "000", "salesacc", "saleofassets");
    linkacc("1150", "000", "salacc", "interestreceived");
    newacc("1660", "000", "Creditors Settlement Discount", "I", "f");
    newacc("1995", "000", "Previous Year Adjustment Income 1", "I", "f");
    newacc("1996", "000", "Previous Year Adjustment Income 2", "I", "f");
    newacc("1997", "000", "Previous Year Adjustment Income 3", "I", "f");
    newacc("1998", "000", "Previous Year Adjustment Income 4", "I", "f");
    newacc("1999", "000", "Previous Year Adjustment Income 5", "I", "f");
    $catid = $catids["E"];
    $cost_account = newacc("2150", "000", "Cost of Sales", "E", "f", "cost_of_sales");
    $pension_account = newacc("2510", "000", "Pension", "E", "f");
    newacc("2520", "000", "Retirement Annuity Fund", "E", "f");
    linkacc("2520", "000", "salacc", "retireexpense");
    newacc("2530", "000", "Provident Fund", "E", "f");
    linkacc("2530", "000", "salacc", "providentexpense");
    newacc("2540", "000", "Medical Aid", "E", "f");
    linkacc("2540", "000", "salacc", "medicalexpense");
    newacc("2160", "000", "Cost Variance", "E", "f", "cost_of_sales");
    linkacc("2160", "000", "pchsacc", "Cost Variance");
    newacc("2170", "000", "Variance", "E", "f", "cost_of_sales");
    linkacc("2170", "000", "salesacc", "sales_variance");
    newacc("2500", "000", "Salaries and Wages", "E", "f");
    linkacc("2500", "000", "salacc", "salaries");
    newacc("2550", "000", "Salaries - Commission", "E", "f");
    linkacc("2550", "000", "salacc", "Commission");
    newacc("2555", "000", "Salaries - Bonus", "E", "f");
    linkacc("2555", "000", "salacc", "Bonus");
    newacc("2560", "000", "UIF", "E", "f");
    linkacc("2560", "000", "salacc", "uifexp");
    newacc("2570", "000", "SDL", "E", "f");
    linkacc("2570", "000", "salacc", "sdlexp");
    newacc("2000", "000", "Accounting Fees", "E", "f");
    newacc("2050", "000", "Advertising and Promotions", "E", "f");
    newacc("2100", "000", "Bank Charges", "E", "f");
    newacc("2200", "000", "Depreciation", "E", "f");
    newacc("2250", "000", "Electricity and Water", "E", "f");
    newacc("2300", "000", "General Expenses", "E", "f");
    newacc("2350", "000", "Insurance", "E", "f");
    newacc("2400", "000", "Interest Paid", "E", "f");
    newacc("2450", "000", "Printing and Stationery", "E", "f");
    newacc("2650", "000", "Rent Paid", "E", "f");
    newacc("2600", "000", "Telephone and Fax", "E", "f");
    newacc("2700", "000", "POS Rounding", "E", "f", "cost_of_sales");
    linkacc("2700", "000", "salesacc", "rounding");
    newacc("2800", "000", "Normal Tax", "E", "f", "tax");
    linkacc("2510", "000", "salacc", "pensionexpense");
    newacc("2660", "000", "Creditors Settlement Discount", "E", "f");
    newacc("3660", "000", "Debtors Settlement Discount", "E", "f");
    newacc("4995", "000", "Previous Year Adjustment Expense 1", "E", "f");
    newacc("4996", "000", "Previous Year Adjustment Expense 2", "E", "f");
    newacc("4997", "000", "Previous Year Adjustment Expense 3", "E", "f");
    newacc("4998", "000", "Previous Year Adjustment Expense 4", "E", "f");
    newacc("4999", "000", "Previous Year Adjustment Expense 5", "E", "f");
    $catid = $catids["B"];
    newacc("5200", "000", "Retained Income / Accumulated Loss", "B", "f", "retained_income");
    newacc("5250", "000", "Share Capital / Members Contribution", "B", "f", "share_capital");
    newacc("5300", "000", "Shareholder / Director / Members Loan Account", "B", "f", "shareholders_loan");
    newacc("6000", "000", "Land & Buildings - Net Value", "B", "f", "fixed_asset");
    newacc("6000", "010", "Land & Buildings - Cost", "B", "f", "fixed_asset");
    newacc("6000", "020", "Land & Buildings - Accum Depreciation", "B", "f", "fixed_asset");
    newacc("6100", "020", "Motor Vehicle - Accum Depreciation", "B", "f", "fixed_asset");
    newacc("6100", "000", "Motor Vehicle - Net Value", "B", "f", "fixed_asset");
    newacc("6100", "010", "Motor Vehicle - Cost", "B", "f", "fixed_asset");
    newacc("6150", "000", "Computer Equipment - Net Value", "B", "f", "fixed_asset");
    newacc("6150", "010", "Computer Equipment - Cost", "B", "f", "fixed_asset");
    newacc("6150", "020", "Computer Equipment - Accum Depreciation", "B", "f", "fixed_asset");
    newacc("6160", "000", "Office Equipment - Net Value", "B", "f", "fixed_asset");
    newacc("6160", "010", "Office Equipment - Cost", "B", "f", "fixed_asset");
    newacc("6160", "020", "Office Equipment - Accum Depreciation", "B", "f", "fixed_asset");
    newacc("6170", "000", "Furniture & Fittings - Net Value", "B", "f", "fixed_asset");
    newacc("6170", "010", "Furniture & Fittings - Cost", "B", "f", "fixed_asset");
    newacc("6170", "020", "Furniture & Fittings - Accum Depreciation", "B", "f", "fixed_asset");
    $stock_control = newacc("6300", "000", "Inventory Suspense Account", "B", "f", "current_asset");
    $stock_account = newacc("6350", "000", "Inventory", "B", "f", "current_asset");
    $deptors_account = newacc("6400", "000", "Customer Control Account", "B", "f", "current_asset");
    $creditors_account = newacc("6500", "000", "Supplier Control Account", "B", "f", "current_liability");
    newacc("6600", "000", "Employees Control Account", "B", "f", "current_liability");
    newacc("2151", "000", "Stock Take Suspense Account", "E", "f", "cost_of_sales");
    linkacc("6600", "000", "salacc", "salaries control");
    linkacc("6600", "000", "salacc", "salaries control original");
    newacc("6700", "000", "Employee Loan Account", "B", "f", "current_asset");
    linkacc("6700", "000", "salacc", "loanacc");
    $bank_account = newacc("7000", "000", "Bank", "B", "f", "current_asset");
    newacc("7100", "000", "Petty Cash", "B", "f", "current_asset");
    linkacc("7100", "000", "bankacc", "Petty Cash");
    $pos_cash_account = newacc("7200", "000", "Cash on Hand", "B", "f", "current_asset");
    linkacc("7200", "000", "salacc", "cash");
    newacc("7300", "000", "POS Credit Card Control", "B", "f", "current_asset");
    linkacc("7300", "000", "salacc", "cc");
    newacc("8000", "000", "VAT Control Account", "B", "f", "current_liability");
    linkacc("8000", "000", "salesacc", "VAT");
    newacc("8010", "000", "VAT Input Account", "B", "f", "current_liability");
    linkacc("8010", "000", "salesacc", "VATIN");
    newacc("8020", "000", "VAT Output Account", "B", "f", "current_liability");
    linkacc("8020", "000", "salesacc", "VATOUT");
    newacc("8100", "000", "PAYE Payable", "B", "f", "current_liability");
    linkacc("8100", "000", "salacc", "PAYE");
    newacc("8200", "000", "UIF Payable", "B", "f", "current_liability");
    linkacc("8200", "000", "salacc", "UIF");
    linkacc("8200", "000", "salacc", "uifbal");
    newacc("8300", "000", "SDL Payable", "B", "f", "current_liability");
    linkacc("8300", "000", "salacc", "sdlbal");
    newacc("8400", "000", "Pension Payable", "B", "f", "current_liability");
    linkacc("8400", "000", "salacc", "pension");
    newacc("8500", "000", "Medical Aid Payable", "B", "f", "current_liability");
    linkacc("8500", "000", "salacc", "medical");
    newacc("8600", "000", "Retirement Annuity Fund Payable", "B", "f", "current_liability");
    linkacc("8600", "000", "salacc", "retire");
    newacc("8700", "000", "Provident Fund Payable", "B", "f", "current_liability");
    linkacc("8700", "000", "salacc", "provident");
    newacc("9000", "000", "Opening Balances / Suspense Account", "B", "f", "current_liability");
    newacc("9995", "000", "Previous Year Adjustment Balance 1", "B", "f", "fixed_asset");
    newacc("9996", "000", "Previous Year Adjustment Balance 2", "B", "f", "fixed_asset");
    newacc("9997", "000", "Previous Year Adjustment Balance 3", "B", "f", "fixed_asset");
    newacc("9998", "000", "Previous Year Adjustment Balance 4", "B", "f", "fixed_asset");
    newacc("9999", "000", "Previous Year Adjustment Balance 5", "B", "f", "fixed_asset");
    # Check if year has been opened
    $sql = "DELETE FROM core.year";
    $rslt = db_exec($sql);
    for ($i = 1; $i <= 10; $i++) {
        $sql = "INSERT INTO core.year VALUES('y" . ($selyear + $i - 1) . "', 'yr{$i}', 'n', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Could not set year name in Cubit", SELF);
    }
    $yrname = "y{$selyear}";
    $endmon = $smonth - 1;
    if (intval($endmon) == 0) {
        $endmon = 12;
    }
    $Sql = "TRUNCATE core.range";
    $Rs = db_exec($Sql) or errDie("Unable to empty year range", SELF);
    $firstmonth = $smonth;
    $activeyear = $yrname;
    $sql = "\n\t\tINSERT INTO core.range (\n\t\t\t\"start\", \"end\", div\n\t\t) VALUES (\n\t\t\t'{$smonth}', '{$endmon}', '" . USER_DIV . "'\n\t\t)";
    $Rslt = db_exec($sql) or errDie("Unable to insert year range", SELF);
    $sql = "SELECT * FROM core.year WHERE yrname='{$yrname}'";
    $yrs = db_exec($sql);
    $yr = pg_fetch_array($yrs);
    if ($yr['closed'] == 'y') {
        return "<center><li class='err'>ERROR : The Selected Financial year : <b>{$yrname}</b> has been closed.\n\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
    }
    $yrdb = $yr['yrdb'];
    $sql = "SELECT * FROM core.range";
    $Rslt = db_exec($sql);
    if (pg_numrows($Rslt) < 1) {
        $OUTPUT = "<center><li class='err'>ERROR : The Financial year Period range was not found on Database, Please make sure that everything is set during instalation.</li>";
        require "template.php";
    }
    $range = Pg_fetch_array($Rslt);
    // Months array
    $months = array("dummy", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    $sql = "INSERT INTO core.active (yrdb, yrname, prddb, prdname, div) VALUES ('{$yrdb}', '{$yrname}', '{$range['start']}', '" . $months[$range['start']] . "', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Could not Set Next Year Database and Name", SELF);
    db_conn("exten");
    $sql = "INSERT INTO departments (deptno, deptname, incacc, debtacc, credacc, pia, pca, div) VALUES ('1', 'Ledger 1', '{$sales_account}', '{$deptors_account}', '{$creditors_account}', '{$pos_sales_account}', '{$pos_cash_account}', '" . USER_DIV . "')";
    $deptRslt = db_exec($sql) or errDie("Unable to add deparment to system.", SELF);
    $sql = "INSERT INTO salespeople (salespno, salesp, div) VALUES ('1', 'General', '" . USER_DIV . "')";
    $salespRslt = db_exec($sql) or errDie("Unable to add warehouse to system.", SELF);
    $sql = "INSERT INTO  categories (category, div) VALUES ('General', '" . USER_DIV . "')";
    $catRslt = db_exec($sql) or errDie("Unable to add category to system.", SELF);
    $sql = "INSERT INTO  class (classname, div) VALUES ('General', '" . USER_DIV . "')";
    $catRslt = db_exec($sql) or errDie("Unable to add fringe benefit to system.", SELF);
    $sql = "INSERT INTO warehouses (whno, whname, stkacc, cosacc, conacc, div) VALUES ('1', 'Store 1', '{$stock_account}', '{$cost_account}', '{$stock_control}', '" . USER_DIV . "')";
    $whouseRslt = db_exec($sql) or errDie("Unable to add warehouse to system.", SELF);
    $whid = pglib_lastid("warehouses", "whid");
    $sql = "INSERT INTO  pricelist (listname, div) VALUES ('Standard', '" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to price list to system.", SELF);
    $sql = "INSERT INTO cubit.stockcat (catcod, cat, descript, div) VALUES('1', 'General', 'General Stock Category', '" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert stock category to Cubit.", SELF);
    $sql = "INSERT INTO cubit.stockclass (classcode, classname, div) VALUES ('1', 'General', '" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to add class to system.", SELF);
    $sql = "SELECT label FROM cubit.set WHERE label = 'DEF_WH' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to check database for existing settings.");
    if (pg_num_rows($rslt) > 0) {
        $sql = "UPDATE cubit.set SET value = '{$whid}', type = 'Default Warehouse' WHERE label = 'DEF_WH' AND div = '" . USER_DIV . "'";
    } else {
        $sql = "INSERT INTO cubit.set (type, label, value, descript, div) VALUES('Default Warehouse', 'DEF_WH', '{$whid}', '1 &nbsp;&nbsp;&nbsp; Store1', '" . USER_DIV . "')";
    }
    db_exec($sql) or errDie("Unable to insert settings to Cubit.");
    $sql = "SELECT label FROM cubit.set WHERE label = 'SELAMT_VAT' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to check database for existing settings.");
    if (pg_num_rows($rslt) > 0) {
        $sql = "UPDATE cubit.set SET value = 'inc', descript = 'Vat Inclusive' WHERE label = 'SELAMT_VAT' AND div = '" . USER_DIV . "'";
    } else {
        $sql = "INSERT INTO cubit.set (type, label, value, descript, div) VALUES('Vat type on stock selling price', 'SELAMT_VAT', 'inc', 'Vat Inclusive', '" . USER_DIV . "')";
    }
    db_exec($sql) or errDie("Unable to insert settings to Cubit.");
    $sql = "INSERT INTO cubit.currency (symbol,curcode,descrip,rate,def) VALUES ('R','ZAR', 'Rand',0.00,'')";
    db_exec($sql) or errDie("Unable to insert currency.");
    $sql = "\n\t\tINSERT INTO cubit.bankacct (\n\t\t\tacctype, bankname, branchname, branchcode, accname, \n\t\t\taccnum, details, div, btype, \n\t\t\tfcid, currency\n\t\t) VALUES (\n\t\t\t'Cheque', 'Bank', 'Branch', '000000', 'Account Name', \n\t\t\t'000000000000', 'Default bank Account', '" . USER_DIV . "', 'loc', \n\t\t\t(SELECT fcid FROM cubit.currency WHERE curcode='ZAR' LIMIT 1), 'Rand'\n\t\t)";
    db_exec($sql) or errDie("Unable to add bank account to database.");
    $accid = pglib_lastid("cubit.bankacct", "bankid");
    $sql = "INSERT INTO cubit.set (type, label, value, descript, div)\n\t\t\tVALUES('Banking Details Account', 'BANK_DET', '3', 'Bank Account: Account Name - Bank', '" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to set default bank account.");
    $hook = "INSERT INTO core.bankacc (accid, accnum, div) VALUES('{$accid}', '{$bank_account}', '" . USER_DIV . "')";
    $Rlst = db_exec($hook) or errDie("Unable to add link for for new bank account", SELF);
    $sql = "INSERT INTO crm.links (name,script) VALUES ('Add Client','../customers-new.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('View Client','../customers-view.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('New Invoice','../cust-credit-stockinv.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('Find Invoice','../invoice-search.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('View Stock','../stock-view.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('Add Supplier','../supp-new.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('View Suppliers','../supp-view.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('New Purchase','../purchase-new.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('View Purchases','../purchase-view.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('Add Quote','../quote-new.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('View Invoices','../invoice-view.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('View Quotes','../quote-view.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('Debtors Age Analysis','../reporting/debt-age-analysis.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('Creditors Age Analysis','../reporting/cred-age-analysis.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.links (name,script) VALUES ('Bank Reconciliation','../reporting/bank-recon.php')";
    db_exec($sql) or errDie("Unable to insert link.");
    $sql = "INSERT INTO crm.teams (name,div) VALUES ('Sales','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.teams (name,div) VALUES ('Support','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.teams (name,div) VALUES ('Accounts','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.teams (name,div) VALUES ('Company Relations','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.teams (name,div) VALUES ('Purchasing - Supplier Relations','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.tcats (name,div) VALUES ('Product Enquiries','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.tcats (name,div) VALUES ('Place an Order','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.tcats (name,div) VALUES ('Complain','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.tcats (name,div) VALUES ('Account querries','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.tcats (name,div) VALUES ('Delivery or Installation Tracking','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.tcats (name,div) VALUES ('Comment on good service or Remarks','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.tcats (name,div) VALUES ('Ask about employment','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.tcats (name,div) VALUES ('General','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.tcats (name,div) VALUES ('Potential Supplier','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.tcats (name,div) VALUES ('Product Support','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into teams");
    $sql = "INSERT INTO crm.actions (action) VALUES ('Called - Need to call again.')";
    db_exec($sql) or errDie("Unable to insert action.");
    $sql = "INSERT INTO crm.actions (action) VALUES ('Called - Could not get in touch')";
    db_exec($sql) or errDie("Unable to insert action.");
    $sql = "INSERT INTO crm.actions (action) VALUES ('Requested more information')";
    db_exec($sql) or errDie("Unable to insert action.");
    $sql = "INSERT INTO crm.actions (action) VALUES ('Sent Fax')";
    db_exec($sql) or errDie("Unable to insert action.");
    $pactivemonth = $activemonth;
    $pactivemonth--;
    if ($pactivemonth == 0) {
        $pactivemonth = 12;
    }
    $i = 0;
    $current = $firstmonth;
    $current--;
    if ($current == 0) {
        $current = 12;
    }
    /* disabled, it wurks differently now */
    while ($current != $pactivemonth && 0) {
        $i++;
        if ($i > 20) {
            break;
        }
        $current++;
        if ($current == 13) {
            $current = 1;
        }
        close_month('yr1', $current);
    }
    for ($i = 1; $i <= 12; ++$i) {
        close_month('yr1', $i);
    }
    $sql = "SELECT accid FROM core.accounts WHERE accname='Bank Charges'";
    $rslt = db_exec($sql);
    $ad = pg_fetch_array($rslt);
    $bc = $ad['accid'];
    $sql = "SELECT accid FROM core.accounts WHERE accname='Interest Paid'";
    $rslt = db_exec($sql);
    $ad = pg_fetch_array($rslt);
    $i = $ad['accid'];
    $sql = "SELECT accid FROM core.accounts WHERE accname='Interest Received'";
    $rslt = db_exec($sql);
    $ad = pg_fetch_array($rslt);
    $ii = $ad['accid'];
    $sql = "INSERT INTO exten.spricelist (listname,div) VALUES ('Standard','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert into supplier price list.");
    $sql = "INSERT INTO cubit.statement_refs (ref,dets,pn,action,account,by) VALUES ('CASH DEPOSIT FEE','i','-','c','{$bc}','Default');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.statement_refs (ref,dets,pn,action,account,by) VALUES ('FEE CHEQUE CASHED','i','-','c','{$bc}','Default');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.statement_refs (ref,dets,pn,action,account,by) VALUES ('FEE-SPECIAL PRESENTATION','i','-','c','{$bc}','Default');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.statement_refs (ref,dets,pn,action,account,by) VALUES ('SERVICE FEE','i','-','c','{$bc}','Default');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.statement_refs (ref,dets,pn,action,account,by) VALUES ('OVERDRAFT LEDGER FEE','i','-','c','{$bc}','Default');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.statement_refs (ref,dets,pn,action,account,by) VALUES ('INTEREST','i','-','c','{$i}','Default');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.statement_refs (ref,dets,pn,action,account,by) VALUES ('INTEREST','i','+','c','{$ii}','Default');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.statement_refs (ref,dets,pn,action,account,by) VALUES ('TRANSACTION CHARGE ','i','-','c','{$bc}','Default');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.statement_refs (ref,dets,pn,action,account,by) VALUES ('ADMIN CHARGE','i','-','c','{$bc}','Default');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.statement_refs (ref,dets,pn,action,account,by) VALUES ('GARAGE CRD CHARGES','i','-','c','{$bc}','Default');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.statement_refs (ref,dets,pn,action,account,by) VALUES ('STAMP DUTY','i','-','c','{$bc}','Default');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.statement_refs (ref,dets,pn,action,account,by) VALUES ('BANKING CHARGES','i','-','c','{$bc}','Default');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.statement_refs (ref,dets,pn,action,account,by) VALUES ('01 CASH DEP','i','-','c','{$bc}','Default');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "CREATE INDEX stkid_stock_key ON cubit.stock USING btree(stkid);";
    db_exec($sql) or errDie("Unable to index.");
    $sql = "CREATE INDEX accid_accounts_key ON core.accounts USING btree(accid);";
    db_exec($sql) or errDie("Unable to index.");
    $sql = "CREATE INDEX accid_trial_bal_key ON core.trial_bal USING btree(accid);";
    db_exec($sql) or errDie("Unable to index.");
    $sql = "INSERT INTO cubit.vatcodes (code,description,del,zero,vat_amount) VALUES ('01','Normal','Yes','No','14');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.vatcodes (code,description,del,zero,vat_amount) VALUES ('02','Capital Goods','No','No','14');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.vatcodes (code,description,del,zero,vat_amount) VALUES ('03','Capital Goods','No','Yes','0');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.vatcodes (code,description,del,zero,vat_amount) VALUES ('04','Zero VAT','No','Yes','0');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.vatcodes (code,description,del,zero,vat_amount) VALUES ('05','VAT Exempt','No','Yes','0');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.report_types (type,div) VALUES ('Disciplinary Verbal Warning','" . USER_DIV . "');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.report_types (type,div) VALUES ('Disciplinary Written Warning','" . USER_DIV . "');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.report_types (type,div) VALUES ('Dismissal','" . USER_DIV . "');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.report_types (type,div) VALUES ('Corrective Counselling','" . USER_DIV . "');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.report_types (type,div) VALUES ('Performance Counselling','" . USER_DIV . "');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.report_types (type,div) VALUES ('Grievance','" . USER_DIV . "');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.report_types (type,div) VALUES ('Disputes Mediation','" . USER_DIV . "');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.report_types (type,div) VALUES ('Disputes Conciliation','" . USER_DIV . "');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.report_types (type,div) VALUES ('Disputes Arbitration','" . USER_DIV . "');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.login_retries (tries, minutes) VALUES ('0', '0');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.supp_groups (id, groupname) VALUES ('0', '[None]');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.template_settings (template, filename, div) VALUES ('statements', 'pdf/pdf-statement.php', '" . USER_DIV . "');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.template_settings (template, filename, div) VALUES ('invoices', 'invoice-print.php', '" . USER_DIV . "');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.template_settings (template, filename, div) VALUES ('reprints', 'new', '" . USER_DIV . "');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.workshop_settings (setting, value, div) VALUES ('workshop_conditions', 'As per display notice.', '" . USER_DIV . "');";
    db_exec($sql) or errDie("Unable to insert data.");
    $sql = "INSERT INTO cubit.set(type, label, value, descript, div) VALUES('Block main accounts', 'BLOCK', 'use', 'Block main accounts', '" . USER_DIV . "')";
    db_exec($sql) or errDie("Error setting up default setting.");
    $sql = "INSERT INTO exten.ct (days,div) VALUES ('0','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    $sql = "INSERT INTO exten.ct (days,div) VALUES ('7','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    $sql = "INSERT INTO exten.ct (days,div) VALUES ('14','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    $sql = "INSERT INTO exten.ct (days,div) VALUES ('30','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    $sql = "INSERT INTO exten.ct (days,div) VALUES ('60','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    $sql = "INSERT INTO exten.ct (days,div) VALUES ('90','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    $sql = "INSERT INTO exten.ct (days,div) VALUES ('120','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    $sql = "INSERT INTO exten.od (days,div) VALUES ('0','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    $sql = "INSERT INTO exten.od (days,div) VALUES ('7','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    $sql = "INSERT INTO exten.od (days,div) VALUES ('14','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    $sql = "INSERT INTO exten.od (days,div) VALUES ('30','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    $sql = "INSERT INTO exten.od (days,div) VALUES ('60','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    $sql = "INSERT INTO exten.od (days,div) VALUES ('90','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    $sql = "INSERT INTO exten.od (days,div) VALUES ('120','" . USER_DIV . "')";
    db_exec($sql) or errDie("Unable to insert default terms");
    if (is_readable("setup-ratios.php")) {
        include "setup-ratios.php";
    }
    if (!isset($inst_mode) or strlen($inst_mode) < 1) {
        $inst_mode = "hq";
    }
    #record the install type ...
    $sql = "\n\t\tINSERT INTO cubit.settings (\n\t\t\tconstant, label, value, type, datatype, \n\t\t\tminlen, maxlen, div, readonly\n\t\t) VALUES (\n\t\t\t'INST_MODE', 'Cubit Install Mode', '{$inst_mode}', 'company', 'allstring', \n\t\t\t'1', '250', '0', 'f'\n\t\t);";
    db_exec($sql) or errDie("Unable to insert install mode.");
    /* run the addon setups */
    foreach ($CUBIT_MODULES as $modulename) {
        if (is_readable("{$modulename}/setup-addon.php")) {
            include "{$modulename}/setup-addon.php";
        }
    }
    db_conn('core');
    block();
    pglib_transaction("COMMIT");
    $sets = "\n\t\t\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Setup Complete</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Cubit is ready to be used.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<p>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    return $sets;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($budname, "string", 1, 255, "Invalid Budget Name.");
    $v->isOk($budtype, "string", 1, 20, "Invalid Budget type.");
    $v->isOk($budfor, "string", 1, 20, "Invalid Budget for option.");
    $v->isOk($fromprd, "string", 1, 20, "Invalid Budget period.");
    $v->isOk($toprd, "string", 1, 20, "Invalid Budget period.");
    if ($budfor == 'acc') {
        if (isset($accids)) {
            foreach ($accids as $akey => $accid) {
                $v->isOk($accid, "num", 1, 50, "Invalid Account number.");
                foreach ($amts[$accid] as $skey => $amtr) {
                    $v->isOk($amts[$accid][$skey], "float", 1, 20, "Invalid Budget amount.");
                }
            }
        } else {
            $v->isOk("#", "num", 0, 0, "Error : please select at least one account.");
        }
    } elseif ($budfor == 'cost') {
        if (isset($ccids)) {
            foreach ($ccids as $akey => $ccid) {
                $v->isOk($ccid, "num", 1, 50, "Invalid Cost Center.");
                foreach ($amts[$ccid] as $skey => $amtr) {
                    $v->isOk($amts[$ccid][$skey], "float", 1, 20, "Invalid Budget amount.");
                }
            }
        } else {
            $v->isOk("#", "num", 0, 0, "Error : please select at least one cost center.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>{$e['msg']}</li>";
        }
        return details($_POST, $confirm);
    }
    global $BUDFOR, $TYPES, $PERIODS;
    $vbudfor = $BUDFOR[$budfor];
    $vbudtype = $TYPES[$budtype];
    $vfromprd = $PERIODS[$fromprd];
    $vtoprd = $PERIODS[$toprd];
    db_conn("cubit");
    $sql = "SELECT * FROM budgets WHERE budname='{$budname}' AND budfor='{$budfor}' AND budtype='{$budtype}'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve budgets from Cubit.");
    $bud_data = pg_fetch_array($rslt);
    if (!pg_num_rows($rslt)) {
        db_connect();
        $sql = "INSERT INTO budgets(budname, budtype, budfor, fromprd, toprd, edate, div) VALUES('{$budname}', '{$budtype}', '{$budfor}', '{$fromprd}', '{$toprd}', now(), '" . USER_DIV . "')";
        $inRs = db_exec($sql);
        $budid = pglib_lastid("budgets", "budid");
    } else {
        $budid = $bud_data["budid"];
    }
    if ($budfor == 'acc') {
        foreach ($accids as $akey => $id) {
            foreach ($amts[$id] as $sprd => $amt) {
                $sql = "INSERT INTO buditems(budid, id, prd, amt) VALUES('{$budid}', '{$id}', '{$sprd}', '{$amt}')";
                $itRs = db_exec($sql);
            }
        }
    } else {
        foreach ($ccids as $akey => $id) {
            foreach ($amts[$id] as $sprd => $amt) {
                $sql = "INSERT INTO buditems(budid, id, prd, amt) VALUES('{$budid}', '{$id}', '{$sprd}', '{$amt}')";
                $itRs = db_exec($sql);
            }
        }
    }
    // Start layout
    $write = "<center>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=500>\n\t\t<tr>\n\t\t\t<th colspan=2>New Monthly Budget created</th>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td class='bg-odd' colspan=2>New Monthly Budget <b>{$budname}</b> has been created.</td>\n\t\t</tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=25%>\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='bg-odd'>\n\t\t\t<td align=center><a href='budget-view.php'>View Budgets</td>\n\t\t</tr>\n\t\t<tr class='bg-odd'>\n\t\t\t<td align=center><a href='../main.php'>Main Menu</td>\n\t\t</tr>\n\t</table>";
    return $write;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    if (isset($back)) {
        return view($_POST);
    }
    # Validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($brancod, "string", 0, 50, "Invalid branch code.");
    $v->isOk($branname, "string", 1, 255, "Invalid branch name.");
    $v->isOk($brandet, "string", 0, 255, "Invalid branch details.");
    # Display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>{$e['msg']}</li>";
        }
        $confirm .= "</li><p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Check stock code
    db_connect();
    $sql = "SELECT branname FROM branches WHERE lower(branname) = lower('{$branname}')";
    $cRslt = db_exec($sql);
    if (pg_numrows($cRslt) > 0) {
        $error = "<li class=err>Branch name : <b>{$branname}</b> already exists.</li>";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    // Insert into stock
    db_connect();
    $sql = "INSERT INTO branches(brancod, branname, brandet) VALUES('{$brancod}', '{$branname}', '{$brandet}')";
    $rslt = db_exec($sql) or errDie("Unable to insert branch to Cubit.", SELF);
    $div = pglib_lastid("branches", "div");
    /*
    // Insert sequences
    $sql = "INSERT INTO seq(type, last_value, div) VALUES('inv', '0', '$div')";
    $rslt = db_exec($sql) or errDie("Unable to insert branch to Cubit.",SELF);
    $sql = "INSERT INTO seq(type, last_value, div) VALUES('pur', '0', '$div')";
    $rslt = db_exec($sql) or errDie("Unable to insert branch to Cubit.",SELF);
    $sql = "INSERT INTO seq(type, last_value, div) VALUES('note', '0', '$div')";
    $rslt = db_exec($sql) or errDie("Unable to insert branch to Cubit.",SELF);
    */
    # Create Default Accounts
    // Profit/Loss account (999/999)
    $catid = createcat("Profit/Loss", $div, "B");
    if (createacc("9999", "999", "Profit/Loss account", $catid, "B", "n", $div) > 0) {
        return "<li class=err>Failed to create default accounts</li>";
    }
    // Total Income account (199/999)
    $catid = createcat("Total Income", $div, "I");
    if (createacc("1999", "999", "Total Income account", $catid, "I", "n", $div) > 0) {
        return "<li class=err>Failed to create default accounts</li>";
    }
    // Total Expenses account (499/999)
    $catid = createcat("Total Expenses", $div, "E");
    if (createacc("4999", "999", "Total Expenses account", $catid, "E", "n", $div) > 0) {
        return "<li class=err>Failed to create default accounts</li>";
    }
    // Layout
    $write = "\r\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\r\n\t<tr><th>New Branch added to database</th></tr>\r\n\t<tr class=datacell><td>New Branch, {$branname} ({$brancod}) has been successfully added to Cubit.</td></tr>\r\n\t</table>\r\n\t<p>\r\n\t<table border=0 cellpadding='2' cellspacing='1'>\r\n\t\t<tr><th>Quick Links</th></tr>\r\n\t\t<tr class='bg-odd'><td><a href='admin-branview.php'>View Branches</a></td></tr>\r\n\t\t<tr class='bg-odd'><td><a href='main.php'>Main Menu</a></td></tr>\r\n\t</table>";
    return $write;
}
function write()
{
    extract($_REQUEST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $sndate = "{$ninv_year}-{$ninv_month}-{$ninv_day}";
    if (!checkdate($ninv_month, $ninv_day, $ninv_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    pglib_transaction("BEGIN");
    // Get invoice info
    $sql = "SELECT * FROM cubit.nons_invoices WHERE invid='{$invid}' AND div='" . USER_DIV . "'";
    $inv_rslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($inv_rslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($inv_rslt);
    $TOTAL = $inv["subtot"] + $inv["vat"];
    $notenum = pglib_lastid("cubit.nons_inv_notes", "noteid");
    $notenum++;
    // Add to the non stock credit notes
    $sql = "\r\n\t\tINSERT INTO cubit.nons_inv_notes (\r\n\t\t\tinvid, invnum, cusname, cusaddr, cusvatno, chrgvat, \r\n\t\t\tdate, subtot, vat, total, username, prd, notenum, ctyp, \r\n\t\t\tremarks, div\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['chrgvat']}', \r\n\t\t\t'{$sndate}', '{$inv['subtot']}', '{$inv['vat']}', '{$TOTAL}', '" . USER_NAME . "', '" . PRD_DB . "', '{$notenum}', '{$inv['ctyp']}', \r\n\t\t\t'{$inv['remarks']}', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to save credit note.");
    $noteid = pglib_lastid("cubit.nons_inv_notes", "noteid");
    $sql = "SELECT count(id) FROM cubit.nons_inv_items WHERE invid='{$invid}'";
    $count_rslt = db_exec($sql) or errDie("Unable to retrieve amount of items.");
    $item_count = pg_fetch_result($count_rslt, 0);
    $i = 0;
    $page = 0;
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM cubit.nons_inv_items WHERE invid='{$invid}' AND id='{$id}'";
        $item_rslt = db_exec($sql) or errDie("Unable to retrieve item.");
        $item_data = pg_fetch_array($item_rslt);
        if ($item_data['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        // Time for a new page ??
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $products[$page][] = "\r\n\t\t\t<tr valign='top'>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>\r\n\t\t\t\t\t{$ex} {$item_data['description']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>\r\n\t\t\t\t\t{$item_data['qty']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000' align='right' nowrap>\r\n\t\t\t\t\t" . CUR . " {$item_data['unitcost']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$item_data['amt']}&nbsp;</td>\r\n\t\t\t</tr>";
        $i++;
        // Create credit note item
        $sql = "\r\n\t\t\tINSERT INTO cubit.nons_note_items (\r\n\t\t\t\tnoteid, qty, description, amt, unitcost, \r\n\t\t\t\tvatcode\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$noteid}', '{$qtys[$key]}', '{$item_data['description']}', '{$amts[$key]}', '{$item_data['unitcost']}', \r\n\t\t\t\t'{$item_data['vatex']}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to create credit note item.");
        $sql = "SELECT grpid FROM cubit.assets WHERE id='{$item_data['asset_id']}'";
        $group_rslt = db_exec($sql) or errDie("Unable to retrieve group.");
        $group_id = pg_fetch_result($group_rslt, 0);
        $discount = $inv["discount"] / $item_count;
        $amt = $item_data["amt"];
        // Update royalty report and detail report
        $sql = "\r\n\t\t\tINSERT INTO hire.revenue (\r\n\t\t\t\tgroup_id, asset_id, total, discount, credit\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$group_id}', '{$item_data['asset_id']}', '-{$amt}', '-{$discount}', '1'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to update revenue.");
        $i++;
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\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 style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t</tr>";
        }
    }
    // Retrieve customer debt account
    $sql = "\r\n\t\tSELECT debtacc FROM exten.departments \r\n\t\t\tLEFT JOIN cubit.customers ON departments.deptid=customers.deptid\r\n\t\tWHERE cusnum='{$inv['cusid']}'";
    $dept_rslt = db_exec($sql) or errDie("Unable to retrieve departments.");
    $debtacc = pg_fetch_result($dept_rslt, 0);
    $hireacc = $inv["accid"];
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "vat");
    $refnum = getrefnum();
    writetrans($hireacc, $debtacc, $sndate, $refnum, $inv["subtot"], "Non-Stock Invoice No. {$inv['invnum']} Credit Note No. {$noteid} Customer\r\n\t\t{$inv['cusname']}");
    if ($inv["vat"] != 0) {
        writetrans($vatacc, $debtacc, $sndate, $refnum, $inv["vat"], "Non-Stock Invoice No. {$inv['invnum']} Credit Note No. {$noteid} VAT.\r\n\t\tCustomer {$inv['cusname']}");
    }
    // Record on the statement
    $sql = "\r\n\t\tINSERT INTO cubit.stmnt (\r\n\t\t\tcusnum, invid, amount, date, type, \r\n\t\t\tdiv\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['cusid']}', '{$noteid}', '-{$TOTAL}', '{$sndate}', 'Non-Stock Credit Note, for invoice {$inv['invnum']}', \r\n\t\t\t'" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to insert to customer statement.");
    // Update the customer (Make the balance less)
    $sql = "UPDATE cubit.customers SET balance=(balance-'{$TOTAL}') WHERE cusnum='{$inv['cusid']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Update the customer (Make the balance less)
    $sql = "UPDATE cubit.open_stmnt SET balance=(balance-'{$TOTAL}') WHERE cusnum='{$inv['cusid']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Create ledger record
    custledger($inv["cusid"], $hireacc, $sndate, $noteid, "Non-Stock Credit Note {$noteid}", $TOTAL, "c");
    custCT($inv["total"], $inv["cusid"], $inv["odate"]);
    // Update non-stock invoice
    $sql = "UPDATE cubit.nons_invoices SET balance=(balance-'{$TOTAL}') WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to update non-stock invoice.");
    $sql = "\r\n\t\tINSERT INTO cubit.salesrec (\r\n\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\r\n\t\t) VALUES (\r\n\t\t\t'{$sndate}', '{$noteid}', '{$notenum}', '0', '{$inv['vat']}', '{$TOTAL}', 'nnon', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to record in sales.");
    $sql = "\r\n\t\tINSERT INTO cubit.sj (\r\n\t\t\tcid, name, des, date, \r\n\t\t\texl, vat, inc, div\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['cusid']}', '{$inv['cusname']}', 'Credit Note: {$noteid} Invoice {$inv['invnum']}', '{$sndate}', \r\n\t\t\t'-" . ($TOTAL - $inv["vat"]) . "', '{$inv['vat']}', '" . -sprint($TOTAL) . "', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to record in sj.");
    $sql = "UPDATE cubit.nons_invoices SET accepted='note' WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to update invoice.");
    com_invoice($inv["salespn"], -($TOTAL - $inv["vat"]), 0, $inv["invnum"], $sndate);
    $cc = "\r\n\t\t<script>\r\n\t\t\tCostCenter('ct', 'Credit Note', '{$sndate}',\r\n\t\t\t'Non Stock Credit Note No.{$noteid}', '" . ($TOTAL - $inv["vat"]) . "', '');\r\n\t   </script>";
    // Reverse the amounts on the coastal reports -----------------------------
    $sql = "UPDATE hire.assets_hired SET value=0 WHERE invid='{$inv['hire_invid']}'";
    db_exec($sql) or errDie("Unable to update asset hired records.");
    // Vat
    $sql = "SELECT id FROM cubit.vatcodes WHERE code='01'";
    $vd_rslt = db_exec($sql) or errDie("Unable to retrieve vatcodes.");
    $vd_id = pg_fetch_result($vd_rslt, 0);
    vatr($vd_id, $sndate, "OUTPUT", "01", $refnum, "Non-Stock Sales, invoice No.{$inv['invnum']}", $TOTAL, $inv["vat"]);
    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.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank.");
    $bank_data = pg_fetch_array($bank_rslt);
    // Retrieve customer information
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
    $cust_data = pg_fetch_array($cust_rslt);
    if ($inv['cusid'] == "0") {
        $cust_data['surname'] = $inv['cusname'];
        $cust_data['addr1'] = $inv['cusaddr'];
        $cust_data['paddr1'] = $inv['cusaddr'];
    }
    $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;";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $details .= "\r\n\t\t\t<center>\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\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\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t\t\t\t<td align='right'><font size='5'><b>Tax Credit Note</b></font></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\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\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\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\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\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\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\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\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\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\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\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\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Credit Note No:</b> {$noteid}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$inv['invnum']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td align='center'><font size='4'><b>Credit Note To:</b></font></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cust_data['surname']}</b></td>\r\n\t\t\t\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\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\r\n\t\t\t\t\t\t\t\t<td>&nbsp</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\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\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\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\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\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000' align='right'><b>Unit Price</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t{$products_out}\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td>{$remarks}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\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\t\t\t<td><b>Trade Discount:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['discount']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['subtot']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\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\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['vat']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " " . sprint($TOTAL) . "</b></td>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>";
    }
    pglib_transaction("COMMIT");
    $OUTPUT = $details;
    require "../tmpl-print.php";
}
function getMsgType($msg_type)
{
    $rslt = db_exec("SELECT type_id FROM mail_datatypes WHERE name = '{$msg_type}'");
    // does it exist? return it
    if (pg_num_rows($rslt) > 0) {
        return pg_fetch_result($rslt, 0, 0);
    }
    // it doesn't! create it and get the insert id
    if (!pglib_transaction("BEGIN")) {
        return 1;
    }
    if (!db_exec("\n\t\tINSERT INTO mail_datatypes (name,icon)\n\t\tVALUES('{$msg_type}', 'icon_blank.gif')")) {
        return;
    }
    $type_id = pglib_lastid("mail_datatypes", "type_id");
    if (!pglib_transaction("COMMIT")) {
        return 1;
    }
    return $type_id;
}
function write_data($_POST)
{
    $date = date("Y-m-d");
    # get vars
    extract($_POST);
    if (isset($back)) {
        return get_data("");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($surname, "string", 1, 100, "Last name");
    $v->isOk($name, "string", 0, 100, "First name");
    $v->isOk($account_id, "num", 0, 9, "Account ID (hidden)");
    $v->isOk($account_type, "string", 0, 100, "Account type (hidden)");
    $v->isOk($reports_to, "string", 0, 100, "Reports to");
    $v->isOk($reports_to_id, "num", 0, 9, "Reports to ID (hidden)");
    $v->isOk($lead_source, "string", 0, 100, "Lead Source");
    $v->isOk($title, "string", 0, 100, "Title");
    $v->isOk($department, "string", 0, 100, "Department");
    $v->isOk($tell, "string", 0, 100, "Home Phone");
    $v->isOk($cell, "string", 0, 100, "Mobile Phone");
    $v->isOk($fax, "string", 0, 100, "Fax");
    $v->isOk($tell_office, "string", 0, 100, "Office Phone");
    $v->isOk($tell_other, "string", 0, 100, "Other Phone");
    $v->isOk($email, "string", 0, 100, "Email");
    $v->isOk($email_other, "string", 0, 100, "Other Email");
    $v->isOk($assistant, "string", 0, 100, "Assistant");
    $v->isOk($assistant_phone, "string", 0, 100, "Assistant Phone");
    $v->isOk($padd, "string", 0, 100, "Physical Address");
    $v->isOk($padd_city, "string", 0, 100, "Physical Address: City");
    $v->isOk($padd_state, "string", 0, 100, "Physical Address: State/Province");
    $v->isOk($padd_code, "string", 0, 100, "Physical Address: Postal Code");
    $v->isOk($padd_country, "string", 0, 100, "Physical Address: Country");
    $v->isOk($hadd, "string", 0, 100, "Postal Address");
    $v->isOk($hadd_city, "string", 0, 100, "Postal Address: City");
    $v->isOk($hadd_state, "string", 0, 100, "Postal Address: State/Province");
    $v->isOk($hadd_code, "string", 0, 100, "Postal Address: Postal Code");
    $v->isOk($hadd_country, "string", 0, 100, "Postal Address: Country");
    $v->isOk($description, "string", 0, 100, "Description");
    $v->isOk($upload_img, "string", 0, 3, "Upload Image");
    $v->isOk($team_id, "num", 1, 9, "Team");
    $birthdate = "{$bf_year}-{$bf_month}-{$bf_day}";
    if ($v->isOk($birthdate, "string", 1, 100, "Birthdate")) {
        if (!checkdate($bf_month, $bf_day, $bf_year)) {
            $v->addError("_OTHER", "Invalid birthdate. No such date exists.");
        }
    }
    $birthdate_description = date("d F Y", mktime(0, 0, 0, $bf_day, $bf_month, $bf_year));
    $assigned_to = USER_NAME;
    $assigned_to_id = USER_ID;
    // read the reports to name
    $reports_to = "";
    if (!empty($reports_to_id)) {
        $reports_to_id += 0;
        db_conn("cubit");
        $sql = "SELECT * FROM cons WHERE id='{$reports_to_id}' LIMIT 1";
        $rslt = db_exec($sql) or errDie("Error retrieving 'Reports to' value.");
        $dat = pg_fetch_array($rslt);
        if (!empty($dat["name"])) {
            $reports_to .= "{$dat['name']} ";
        }
        $reports_to .= "{$dat['surname']}";
    }
    # display errors, if any
    if ($v->isError()) {
        $err = "The following field value errors occured:<br>";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            if ($e["value"] == "_OTHER") {
                $err .= "<li class='err'>{$e['msg']}</li>";
            } else {
                $err .= "<li class='err'>Invalid characters: {$e['msg']}</li>";
            }
        }
        return get_data($err);
    }
    db_conn('cubit');
    if (!pglib_transaction("BEGIN")) {
        return "<li class='err'>Unable to add contact to database. (TB)</li>";
    }
    if (isset($supid) and strlen($supid) > 0) {
        // supplier ...
        $get_sup = "SELECT supname FROM suppliers WHERE supid = '{$supid}' LIMIT 1";
        $run_sup = db_exec($get_sup) or errDie("Unable to get supplier information.");
        if (pg_numrows($run_sup) > 0) {
            $accountname = pg_fetch_result($run_sup, 0, 0);
        }
    }
    if (isset($cusnum) and strlen($cusnum) > 0) {
        // customer
        $get_cust = "SELECT surname FROM customers WHERE cusnum = '{$cusnum}' LIMIT 1";
        $run_cust = db_exec($get_cust) or errDie("Unable to get customer information.");
        if (pg_numrows($run_cust) > 0) {
            $accountname = pg_fetch_result($run_cust, 0, 0);
        }
    }
    # write to db
    db_conn("cubit");
    $supid += 0;
    $cusnum += 0;
    $account_id += 0;
    $sql = "\n\t\tINSERT INTO cons (\n\t\t\tsurname, name, accountname, account_id, account_type,\n\t\t\tlead_source, title, department, birthdate, reports_to, reports_to_id,\n\t\t\ttell, cell, fax, tell_office, tell_other, email, email_other, assistant,\n\t\t\tassistant_phone, padd, padd_city, padd_state, padd_code,\n\t\t\tpadd_country, hadd, hadd_city, hadd_state, hadd_code,\n\t\t\thadd_country, description, ref, date, con, by, div, supp_id,\n\t\t\tcust_id, assigned_to, assigned_to_id, team_id\n\t\t) VALUES (\n\t\t\t'{$surname}', '{$name}', '{$accountname}', '{$account_id}', '{$account_type}', \n\t\t\t'{$lead_source}', '{$title}', '{$department}', '{$birthdate}', '{$reports_to}', \n\t\t\t'{$reports_to_id}', '{$tell}', '{$cell}', '{$fax}', '{$tell_office}', \n\t\t\t'{$tell_other}', '{$email}', '{$email_other}', '{$assistant}', \n\t\t\t'{$assistant_phone}', '{$padd}', '{$padd_city}', '{$padd_state}', \n\t\t\t'{$padd_code}', '{$padd_country}', '{$hadd}', '{$hadd_city}', '{$hadd_state}', \n\t\t\t'{$hadd_code}', '{$hadd_country}', '{$description}', '{$account_type}', CURRENT_DATE, \n\t\t\t'{$Con}', '" . USER_NAME . "', '" . USER_DIV . "', '{$supid}', \n\t\t\t'{$cusnum}', '{$assigned_to}', '{$assigned_to_id}', '{$team_id}'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to add contact to database.");
    $con_id = pglib_lastid("cons", "id");
    // Write the image (if any)
    if ($upload_img == "yes") {
        if (preg_match("/(image\\/jpeg|image\\/png|image\\/gif)/", $_FILES["img_file"]["type"], $extension)) {
            $img = "";
            $fp = fopen($_FILES["img_file"]["tmp_name"], "rb");
            while (!feof($fp)) {
                $img .= fread($fp, 1024);
            }
            fclose($fp);
            $img = base64_encode($img);
            $sql = "\n\t\t\t\tINSERT INTO cubit.cons_img (\n\t\t\t\t\tcon_id, type, file, size\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$con_id}', '" . $_FILES["img_file"]["type"] . "', '{$img}', '" . $_FILES["img_file"]["size"] . "'\n\t\t\t\t)";
            $ci_rslt = db_exec($sql) or errDie("Unable to add contact image.");
        } else {
            return "<li class='err'>Please note we only accept PNG, GIF and JPEG images.</li>";
        }
    }
    if (!pglib_transaction("COMMIT")) {
        return "<li class='err'>Unable to add contact to database. (TC)</li>";
    }
    if (isset($crm)) {
        header("Location: crm/tokens-new.php?value={$surname}");
        exit;
    }
    $write_data = "\n\t\t<table cellpadding='2' cellspacing='0' class='shtable'>\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Contact added</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$surname} has been added to Cubit.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table cellpadding='2' cellspacing='0' class='shtable'>\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='" . SELF . "'>Add another contact</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='list_cons.php'>List Contacts</a></td>\n\t\t\t</tr>\n\t\t</table>";
    return $write_data;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 9, "Invalid Order ID");
    $v->isOk($ordernum, "string", 0, 20, "Invalid order number.");
    $v->isOk($supid, "num", 1, 20, "Invalid Supplier number.");
    $v->isOk($terms, "num", 1, 5, "Invalid terms days.");
    $v->isOk($npuri_day, "num", 1, 2, "Invalid Date day.");
    $v->isOk($npuri_month, "num", 1, 2, "Invalid Date month.");
    $v->isOk($npuri_year, "num", 1, 5, "Invalid Date year.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    $v->isOk($xrate, "float", 1, 20, "Invalid Exchange Rate.");
    $v->isOk($tax, "float", 0, 20, "Invalid Tax.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $pdate = $npuri_year . "-" . $npuri_month . "-" . $npuri_day;
    if (!checkdate($npuri_month, $npuri_day, $npuri_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    $ddate = $del_year . "-" . $del_month . "-" . $del_day;
    if (!checkdate($del_month, $del_day, $del_year)) {
        $v->isOk($ddate, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            # Nasty Zeros
            $unitcost[$keys] += 0;
            $cunitcost[$keys] += 0;
            $duty[$keys] += 0;
            $dutyp[$keys] += 0;
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 0, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($cunitcost[$keys], "float", 0, 20, "Invalid Foreign currency Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($duty[$keys], "float", 0, 20, "Invalid Duty Charges for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($dutyp[$keys], "float", 0, 20, "Invalid Duty Charges Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($des[$keys], "string", 1, 255, "Invalid Description.");
            $v->isOk($cod[$keys], "string", 0, 255, "Invalid Item Code.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # check amt
    if (isset($amt)) {
        foreach ($amt as $keys => $amount) {
            $v->isOk($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # Get selected supplier  info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get supplier  information");
    $sup = pg_fetch_array($supRslt);
    # Currency
    $currs = getSymbol($sup['fcid']);
    $curr = $currs['symbol'];
    # check if Order has been printed
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : Order number <b>{$pur['purnum']}</b> has already been received.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # fix those nasty zeros
    $xrate += 0;
    if ($xrate == 0) {
        $xrate = 1;
    }
    $shipchrg += 0;
    $tax += 0;
    # insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* -- Start remove old items -- */
    # remove old items
    $sql = "DELETE FROM nons_purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Order items in Cubit.", SELF);
    /* -- End remove old items -- */
    $VATP = TAX_VAT;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            if (isset($remprod)) {
                if (in_array($keys, $remprod)) {
                    # skip product (wonder if $keys still align)
                    $amt[$keys] = 0;
                    continue;
                } else {
                    # Calculate the unitcost
                    if ($cunitcost[$keys] > 0) {
                        $unitcost[$keys] = round($cunitcost[$keys] * $xrate, 2);
                    } else {
                        $cunitcost[$keys] = round($unitcost[$keys] / $xrate, 2);
                    }
                    # Calculate the duty amount
                    if ($duty[$keys] < 1) {
                        if ($dutyp[$keys] > 0) {
                            $duty[$keys] = round($dutyp[$keys] / 100 * $unitcost[$keys], 2);
                        }
                    } else {
                        if ($unitcost[$keys] > 0) {
                            $dutyp[$keys] = round($duty[$keys] * 100 / $unitcost[$keys], 2);
                        } else {
                            $dutyp[$keys] = 0;
                        }
                    }
                    # Calculate amount
                    $amt[$keys] = $qtys[$keys] * $cunitcost[$keys] + $duty[$keys];
                    # insert Order items
                    $sql = "\n\t\t\t\t\t\tINSERT INTO nons_purint_items (\n\t\t\t\t\t\t\tpurid, cod, des, qty, unitcost, cunitcost, duty, dutyp, amt, div\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$purid}', '{$cod[$keys]}', '{$des[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$cunitcost[$keys]}', '{$duty[$keys]}', '{$dutyp[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "'\n\t\t\t\t\t\t)";
                    $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
                }
            } else {
                # Calculate the unitcost
                if ($cunitcost[$keys] > 0) {
                    $unitcost[$keys] = round($cunitcost[$keys] * $xrate, 2);
                } else {
                    $cunitcost[$keys] = round($unitcost[$keys] / $xrate, 2);
                }
                # Calculate the duty amount
                if ($duty[$keys] < 1) {
                    if ($dutyp[$keys] > 0) {
                        $duty[$keys] = round($dutyp[$keys] / 100 * $unitcost[$keys], 2);
                    }
                } else {
                    if ($unitcost[$keys] > 0) {
                        $dutyp[$keys] = round($duty[$keys] * 100 / $unitcost[$keys], 2);
                    } else {
                        $dutyp[$keys] = 0;
                    }
                }
                # Calculate amount
                $amt[$keys] = $qtys[$keys] * $cunitcost[$keys] + $duty[$keys];
                # insert Order items
                $sql = "\n\t\t\t\t\tINSERT INTO nons_purint_items (\n\t\t\t\t\t\tpurid, cod, des, qty, unitcost, cunitcost, \n\t\t\t\t\t\tduty, dutyp, amt, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$cod[$keys]}', '{$des[$keys]}', '{$qtys[$keys]}', '{$unitcost[$keys]}', '{$cunitcost[$keys]}', \n\t\t\t\t\t\t'{$duty[$keys]}', '{$dutyp[$keys]}', '{$amt[$keys]}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            }
            # everything is set place done button
            $_POST["done"] = "&nbsp; | &nbsp;<input name='doneBtn' type='submit' value='Done'>\n\t\t\t&nbsp; | &nbsp;<input name='recv' type='submit' value='Receive'>\n\t\t\t&nbsp; | &nbsp;<input type='submit' name='donePrnt' value='Done, Print and make another'>";
        }
    } else {
        $_POST["done"] = "";
    }
    /* --- Clac --- */
    # Calculate subtot
    if (isset($amt)) {
        $SUBTOT = array_sum($amt);
    } else {
        $SUBTOT = 0.0;
    }
    # shipchrg is in for curr
    $fshipchrg = $shipchrg;
    // $shipchrg = ($shipchrg * $xrate);
    # total
    $TOTAL = sprint($SUBTOT + $shipchrg + $tax);
    # total Duty
    if (isset($duty)) {
        $dutytot = sprint(array_sum($duty));
    } else {
        $dutytot = "0.00";
    }
    # Local Totals
    $LTOTAL = sprint($TOTAL * $xrate);
    $LSUBTOT = sprint($SUBTOT * $xrate);
    /* --- End Clac --- */
    # insert Order to DB
    $sql = "\n\t\tUPDATE nons_purch_int \n\t\tSET supid = '{$supid}',cusid = '{$delvat}', supplier = '{$sup['supname']}', supaddr = '{$sup['supaddr']}', terms = '{$terms}', \n\t\t\tpdate = '{$pdate}', ddate = '{$ddate}', fcid = '{$sup['fcid']}', currency = '{$curr}', curr = '{$curr}', tax = '{$tax}', \n\t\t\txrate = '{$xrate}', fshipchrg = '{$fshipchrg}', shipchrg = '{$shipchrg}', duty = '{$dutytot}', subtot = '{$SUBTOT}', \n\t\t\ttotal = '{$TOTAL}', balance = '{$TOTAL}', fsubtot = '{$LSUBTOT}', fbalance = '{$LTOTAL}', remarks = '{$remarks}' \n\t\tWHERE purid = '{$purid}'";
    $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $lastid = pglib_lastid("nons_purch_int", "purid");
    if (isset($donePrnt)) {
        $sql = "UPDATE nons_purch_int SET done='y' WHERE purid='{$purid}' AND div='" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.");
        $OUTPUT = "\n\t\t\t<script>\n\t\t\t\tprinter('nons-purch-int-print.php?purid={$lastid}');\n\t\t\t\tmove('nons-purch-int-new.php');\n\t\t\t</script>";
        return $OUTPUT;
    }
    if (isset($recv)) {
        header("Location: nons-purch-int-recv.php?purid={$purid}");
        exit;
    } elseif (!isset($doneBtn)) {
        return details($_POST);
    } else {
        # insert Order to DB
        $sql = "UPDATE nons_purch_int SET done = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
        // Final Laytout
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>New International Non-Stock Order</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>International Non-Stock Order from Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t\t\t<td><a href='nons-purch-int-print.php?purid={$lastid}'>Print Order</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='nons-purch-int-view.php'>View International Non-Stock Orders</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
        return $write;
    }
}
function write($_POST)
{
    extract($_POST);
    db_conn('cubit');
    $Sl = "SELECT * FROM import_data";
    $Rt = db_exec($Sl);
    $i = 0;
    $odate = date("Y-m-d");
    if (!isset($department) or strlen($department) < 1) {
        $department = "2";
    }
    while ($fd = pg_fetch_array($Rt)) {
        //$out.="<tr class='".bg_class()."'><td>$fd[des1]</td><td>$fd[des2]</td><td>$fd[des3]</td></tr>";
        $i++;
        db_conn('cubit');
        # Write to db
        $sql = "\n\t\t\tINSERT INTO suppliers (\n\t\t\t\tdeptid, supno, supname, location, fcid, \n\t\t\t\tcurrency, vatnum, supaddr, contname, tel, \n\t\t\t\tfax, email, url, listid, bankname, \n\t\t\t\tbranname, brancode, bankaccno, balance, fbalance, \n\t\t\t\tdiv, lead_source\n\t\t\t) VALUES (\n\t\t\t\t'{$department}', '{$fd['des1']}', '{$fd['des2']}', 'loc', '2', \n\t\t\t\t'R', '{$fd['des4']}', '{$fd['des3']}', '{$fd['des5']}', '{$fd['des6']}', \n\t\t\t\t'{$fd['des7']}', '', '{$fd['des8']}', '2', '', \n\t\t\t\t'', '', '', 0, 0, \n\t\t\t\t'" . USER_DIV . "', ''\n\t\t\t)";
        $supRslt = db_exec($sql) or errDie("Unable to add supplier to the system.", SELF);
        if (pg_cmdtuples($supRslt) < 1) {
            return "<li class='err'>Unable to add supplier to database.</li>";
        }
        if (($supp_id = pglib_lastid("suppliers", "supid")) == 0) {
            return "<li class='err'>Unable to add supplier to contact list.</li>";
        }
        $Date = date("Y-m-d");
        db_conn('audit');
        $Sl = "SELECT * FROM closedprd ORDER BY id";
        $Ri = db_exec($Sl);
        while ($pd = pg_fetch_array($Ri)) {
            db_conn($pd['prdnum']);
            $Sl = "\n\t\t\t\tINSERT INTO suppledger (\n\t\t\t\t\tsupid, contra, edate, sdate, eref, descript, \n\t\t\t\t\tcredit, debit, div, dbalance, cbalance\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$supp_id}', '0', '{$Date}', '{$Date}', '0', 'Balance', \n\t\t\t\t\t'0', '0', '" . USER_DIV . "', '0', '0'\n\t\t\t\t)";
            $Rj = db_exec($Sl) or errDie("Unable to insert cust balances");
        }
    }
    $out = "Done";
    return $out;
}
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 details($_GET)
{
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid = '{$invid}'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found[1]</i>";
    }
    $inv = pg_fetch_array($invRslt);
    // Cash deposit
    if ($inv["deposit_type"] == "CSH" && $inv["deposit_amt"] > 0) {
        $get_ar = array();
        foreach ($_GET as $key => $value) {
            if ($key != "key") {
                $get_ar[] = "{$key}={$value}";
            }
        }
        $get_vars = implode("&", $get_ar);
        $deposit_receipt = "<script>\r\n\t\t\t\t\t\t\t\tprinter(\"" . SELF . "?key=deposit{$get_vars}\")\r\n\t\t\t\t\t\t\t</script>";
    } else {
        $deposit_receipt = "";
    }
    if ($inv['rounding'] > 0) {
        db_conn('core');
        $Sl = "SELECT * FROM salesacc WHERE name='rounding'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set the rounding account, under sales settings.";
        }
        $ad = pg_fetch_array($Ri);
        $rac = $ad['accnum'];
    }
    if ($inv['cusnum'] != "0") {
        #then get the actual customer
        db_connect();
        $get_cus = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' LIMIT 1";
        $run_cus = db_exec($get_cus) or errDie("Unable to get customer information");
        if (pg_numrows($run_cus) < 1) {
            #do nothing
        } else {
            $carr = pg_fetch_array($run_cus);
            $inv['cusname'] = "{$carr['cusname']}";
            $inv['surname'] = "{$carr['surname']}";
        }
    }
    $td = $inv['odate'];
    db_conn('cubit');
    $sql = "SELECT asset_id FROM hire.hire_invitems WHERE invid = '{$inv['invid']}'";
    $crslt = db_exec($sql);
    if ($inv['terms'] == 1) {
        db_conn('core');
        $Sl = "SELECT * FROM salacc WHERE name='cc'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set a link for the POS credit card control account";
        }
        $cd = pg_fetch_array($Ri);
        $cc = $cd['accnum'];
    }
    $change = sprint(sprint($inv['pcash'] + $inv['pcheque'] + $inv['pcc'] + $inv['pcredit']) - sprint($inv['total'] - $inv['rounding']));
    $inv['pcash'] = sprint($inv['pcash'] - $change);
    if ($inv['pcash'] < 0) {
        $inv['pcash'] = 0;
    }
    if (sprint($inv['pcash'] + $inv['pcheque'] + $inv['pcc'] + $inv['pcredit']) != sprint($inv['total'] - $inv['rounding'])) {
        return "<li class=err>The total of all the payments is not equal to the invoice total.<br>\r\n\t\tPlease edit the invoice and try again(You can only overpay with cash)</li>";
    }
    db_connect();
    pglib_transaction("BEGIN");
    $invnum = getHirenum($invid, 1);
    $sql = "UPDATE hire.reprint_invoices SET invnum='{$invnum}' WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to assign hire invoice number.");
    $Sl = "INSERT INTO ncsrec (oldnum,newnum, div) VALUES ('{$invid}','{$invnum}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert into db");
    //unlock(2);
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class=err>Not Found[2]</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM hire.hire_invitems  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $taxex = 0;
    $commision = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM assets WHERE id = '{$stkd['asset_id']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            db_connect();
            //this was set to the stock vatcode ??? must be the pur_item code ...
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "<li class='err'>Please select the vatcode for all your stock.</li>";
            }
            $vd = pg_fetch_array($Ri);
            $sp = "&nbsp;&nbsp;&nbsp;&nbsp;";
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "&nbsp;&nbsp;";
            }
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            # Insert stock record
            $sdate = date("Y-m-d");
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            # put in product
            $products .= "<tr valign=top>\r\n\t\t\t\t<td>{$stk['stkcod']}</td>\r\n\t\t\t\t<td>{$ex} {$sp} {$stk['stkdes']}</td>\r\n\t\t\t\t<td>{$stkd['qty']}</td>\r\n\t\t\t\t<td>" . sprint($stk["selamt"]) . "</td>\r\n\t\t\t\t<td>" . CUR . sprint($stkd["amt"]) . "</td>\r\n\t\t\t</tr>";
            # Get amount exluding vat if including and not exempted
            $VATP = TAX_VAT;
            $amtexvat = sprint($stkd['amt']);
            if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes') {
                $amtexvat = sprint($stkd['amt'] * 100 / (100 + $VATP));
            }
            $commision = $commision + coms($inv['salespn'], $stkd['amt'], $stk['com']);
        } else {
            db_conn('core');
            $Sl = "SELECT * FROM accounts WHERE accid='{$stkd['account']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get account data.");
            $ad = pg_fetch_array($Ri);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            $sp = "";
            # Check Tax Excempt
            if ($vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "";
            }
            # all must be excempted
            if ($inv['chrgvat'] == 'nov') {
                $ex = "#";
            }
            //$commision=$commision+coms($inv['salespn'], $stkd['amt'], $stk['com']);
            # Put in product
            $products .= "<tr valign=top>\r\n\t\t\t\t<td></td>\r\n\t\t\t\t<td>{$ex} {$sp} {$stkd['description']}</td>\r\n\t\t\t\t<td>{$stkd['qty']}</td>\r\n\t\t\t\t<td>" . sprint($stkd["unitcost"]) . "</td>\r\n\t\t\t\t<td>{$stkd['disc']}</td>\r\n\t\t\t\t<td>" . CUR . sprint($stkd["amt"]) . "</td>\r\n\t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOTAL = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $av = $VAT;
    $at = $TOTAL - $VAT;
    $nt = sprint($inv['pcredit']);
    $sd = date("Y-m-d");
    $ro = $inv['rounding'];
    $ro += 0;
    com_invoice($inv['salespn'], $TOTAL - $VAT, $commision, $invnum);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "novat");
    /* - End Hooks - */
    $nsp = 0;
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    db_conn('cubit');
    if ($inv['cusnum'] > 0 && $nt > 0) {
        # Record the payment on the statement
        $sql = "INSERT INTO stmnt(cusnum, invid, docref, amount, date, type, div) VALUES('{$inv['cusnum']}', '{$invnum}', '0', '{$nt}', '{$inv['odate']}', '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('{$inv['cusnum']}', '{$invnum}', '0', '{$nt}', '{$nt}', '{$inv['odate']}', '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 + '{$nt}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        custledger($inv['cusnum'], $dept['incacc'], $inv['odate'], $invnum, "Invoice No. {$invnum}", $nt, "d");
        recordDT($nt, $inv['cusnum'], $inv['odate']);
        db_conn('cubit');
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$sd}','" . USER_NAME . "','{$invnum}','{$nt}','Credit','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    db_conn('cubit');
    if ($inv['terms'] == 1) {
        $Sl = "INSERT INTO crec(userid,username,amount,pdate,inv) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}')";
        $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    } else {
        $Sl = "INSERT INTO posrec(userid,username,amount,pdate,inv) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}')";
        $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    }
    $Sl = "INSERT INTO pr(userid,username,amount,pdate,inv,cust,t) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}','{$inv['cusname']}','{$inv['terms']}')";
    $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    $refnum = getrefnum();
    $fcash = $inv['pcash'];
    $fccp = $inv['pcc'];
    $fcheque = $inv['pcheque'];
    $fcredit = $inv['pcredit'];
    /* --- Updates ---- */
    db_connect();
    $Sql = "UPDATE hire.hire_invoices SET pchange='{$change}',printed = 'y', done ='y',invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
    # save invoice discount
    $sql = "INSERT INTO inv_discs(cusnum, invid, traddisc, itemdisc, inv_date, delchrg, div,total) VALUES('0','{$invnum}','{$inv['delivery']}','{$disc}', '{$inv['odate']}', '{$inv['delivery']}', '" . USER_DIV . "',({$SUBTOT}+{$inv['delivery']}))";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # get selected stock in this invoice
    $sql = "SELECT * FROM hire.hire_invitems  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    if (strlen($inv['comm']) > 0) {
        $Com = "<table><tr><td>" . nl2br($inv['comm']) . "</td></tr></table>";
    } else {
        $Com = "";
    }
    $cc = "<script> sCostCenter('dt', 'Sales', '{$date}', 'POS Invoice No.{$invnum}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', ''); </script>";
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    /* - End Transactoins - */
    /* -- Final Layout -- */
    $details = "<center>\r\n\t{$deposit_receipt} {$cc}\r\n\t<h2>Tax Invoice</h2>\r\n\t<table cellpadding='0' cellspacing='1' border=0 width=750>\r\n\t<tr><td valign=top width=40%>\r\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0>\r\n\t\t\t<tr><td>{$inv['surname']}</td></tr>\r\n\t\t</table>\r\n\t</td><td valign=top width=35%>\r\n\t\t" . COMP_NAME . "<br>\r\n\t\t" . COMP_ADDRESS . "<br>\r\n\t\t" . COMP_TEL . "<br>\r\n\t\t" . COMP_FAX . "<br>\r\n\t\tReg No. " . COMP_REGNO . "<br>\r\n\t</td><td valign=bottom align=right width=25%>\r\n\t\t<table cellpadding='2' cellspacing='0' border=1 bordercolor='#000000'>\r\n\t\t\t<tr><td><b>Hire No.</b></td><td valign=center>H" . getHirenum($inv["invid"], 1) . "</td></tr>\r\n\t\t\t<tr><td><b>Order No.</b></td><td valign=center>{$inv['ordno']}</td></tr>\r\n\t\t\t<tr><td><b>Terms</b></td><td valign=center>Cash</td></tr>\r\n\t\t\t<tr><td><b>Invoice Date</b></td><td valign=center>{$inv['odate']}</td></tr>\r\n\t\t\t<tr><td><b>VAT</b></td><td valign=center>{$inv['chrgvat']}</td></tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td><br></td></tr>\r\n\t<tr><td colspan=3>\r\n\t<table cellpadding='5' cellspacing='0' border=1 width=100% bordercolor='#000000'>\r\n\t\t<tr><th>ITEM NUMBER</th><th width=45%>DESCRIPTION</th><th>QTY</th><th>UNIT PRICE</th><th>AMOUNT</th><tr>\r\n\t\t{$products}\r\n\t</table>\r\n\t</td></tr>\r\n\t<tr><td>\r\n\t\t{$inv['custom_txt']}\r\n\t\t{$Com}\r\n\t</td><td align=right colspan=2>\r\n\t\t<table cellpadding='5' cellspacing='0' border=1 width=50% bordercolor='#000000'>\r\n\t\t\t<tr><td><b>SUBTOTAL</b></td><td align=right>" . CUR . " {$SUBTOT}</td></tr>\r\n\t\t\t<tr><td><b>Trade Discount</b></td><td align=right>" . CUR . " {$inv['discount']}</td></tr>\r\n\t\t\t<tr><td><b>Delivery Charge</b></td><td align=right>" . CUR . " {$inv['delivery']}</td></tr>\r\n\t\t\t<tr><td><b>VAT @ {$VATP}%</b></td><td align=right>" . CUR . " {$VAT}</td></tr>\r\n\t\t\t<tr><th><b>GRAND TOTAL<b></th><td align=right>" . CUR . " {$TOTAL}</td></tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td><br></td></tr>\r\n\t<tr><td>\r\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=1>\r\n\t\t\t<tr><td colspan=2>VAT Exempt indicator = #</td></tr>\r\n\t\t\t<tr><th>VAT No.</th><td align=center>" . COMP_VATNO . "</td></tr>\r\n        </table>\r\n\t</td><td><br></td></tr>\r\n\t</table></center>";
    /* Start moving invoices */
    db_connect();
    # Move invoices that are fully paid
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$invid}'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    $time2 = time();
    while ($invb = pg_fetch_array($invbRslt)) {
        $invb['invnum'] += 0;
        # Insert invoice to period DB
        $sql = "INSERT INTO hire.hire_invoices(invid,invnum, deptid, cusnum, deptname, cusacc, cusname, surname, cusaddr, cusvatno, cordno, ordno, chrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, balance, comm, printed, done, div, username,rounding,delvat,vatnum,pcash,pcheque,pcc,pcredit)";
        $sql .= " VALUES('{$invb['invid']}','{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', '{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', 'y', 'y', '" . USER_DIV . "','" . USER_NAME . "','{$invb['rounding']}','{$invb['delvat']}','{$invb['vatnum']}','{$invb['pcash']}','{$invb['pcheque']}','{$invb['pcc']}','{$invb['pcredit']}')";
        //$rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.",SELF);
        $sql = "SELECT * FROM hire.monthly_invoices WHERE invid='{$invb['invid']}'";
        $hi_rslt = db_exec($sql) or errDie("Unable to retrieve hire invoice.");
        if (pg_num_rows($hi_rslt)) {
            $sql = "UPDATE hire.monthly_invoices SET invnum='{$invb['invnum']}',\r\n\t\t\t\t\t\tdeptid='{$invb['deptid']}', cusnum='{$invb['cusnum']}',\r\n\t\t\t\t\t\tdeptname='{$invb['deptname']}', cusacc='{$invb['cusacc']}',\r\n\t\t\t\t\t\tcusname='{$invb['cusname']}', surname='{$invb['surname']}',\r\n\t\t\t\t\t\tcusaddr='{$invb['cusaddr']}', cusvatno='{$invb['cusvatno']}',\r\n\t\t\t\t\t\tcordno='{$invb['cordno']}', ordno='{$invb['ordno']}',\r\n\t\t\t\t\t\tchrgvat='{$invb['chrgvat']}', terms='{$invb['terms']}',\r\n\t\t\t\t\t\ttraddisc='{$invb['traddisc']}', salespn='{$invb['salespn']}',\r\n\t\t\t\t\t\todate='{$invb['odate']}', delchrg='{$invb['delchrg']}',\r\n\t\t\t\t\t\tsubtot='{$invb['subtot']}', vat='{$invb['vat']}',\r\n\t\t\t\t\t\ttotal='{$invb['total']}', balance='{$invb['balance']}',\r\n\t\t\t\t\t\tcomm='{$invb['comm']}', printed='{$invb['printed']}',\r\n\t\t\t\t\t\tdone='{$invb['done']}', div='{$invb['div']}',\r\n\t\t\t\t\t\tusername='******'username']}', rounding='{$invb['rounding']}',\r\n\t\t\t\t\t\tdelvat='{$invb['delvat']}', vatnum='{$invb['vatnum']}',\r\n\t\t\t\t\t\tpcash='{$invb['pcash']}', pcheque='{$invb['pcheque']}',\r\n\t\t\t\t\t\tpcc='{$invb['pcc']}', pcredit='{$invb['pcredit']}'\r\n\t\t\t\t\tWHERE invid='{$invb['invid']}'";
            db_exec($sql) or errDie("Unable to store monthly invoice.");
            $mi_invid = $invb["invid"];
        } else {
            $sql = "INSERT INTO hire.monthly_invoices(invid, invnum, deptid, cusnum, deptname, cusacc, cusname, surname, cusaddr, cusvatno, cordno, ordno, chrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, balance, comm, printed, done, div, username,rounding,delvat,vatnum,pcash,pcheque,pcc,pcredit, invoiced_month)";
            $sql .= " VALUES('{$invb['invid']}', '{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', '{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', 'y', 'y', '" . USER_DIV . "','" . USER_NAME . "','{$invb['rounding']}','{$invb['delvat']}','{$invb['vatnum']}','{$invb['pcash']}','{$invb['pcheque']}','{$invb['pcc']}','{$invb['pcredit']}', '" . date("m") . "')";
            db_exec($sql) or errDie("Unable to store monthly invoice.");
            db_conn("hire");
            $mi_invid = pglib_lastid("monthly_invoices", "invid");
        }
        $sql = "SELECT * FROM hire.hire_invitems WHERE invid='{$invb['invid']}'";
        $invi_rslt = db_exec($sql) or errDie("Unable to retrieve note items.");
        // 		while ($invi = pg_fetch_array($invi_rslt)) {
        // 			if (isset($monthly) && $monthly) {
        // 				$sql = "DELETE FROM hire.monthly_invitems WHERE invid='$mi_invid'";
        // 				db_exec($sql) or errDie("Unable to remove items.");
        //
        // 				$sql = "INSERT INTO hire.monthly_invitems (invid, asset_id, qty,
        // 							unitcost, amt, disc, discp, serno, div, vatcode, account,
        // 							description, basis, from_date, to_date, hours, weeks,
        // 							collection)
        // 						VALUES ('$mi_invid', '$invi[asset_id]',
        // 							'$invi[qty]', '$invi[unitcost]', '$invi[amt]',
        // 							'$invi[disc]', '$invi[discp]',	'$invi[serno]',
        // 							'".USER_DIV."',	'$invi[vatcode]', '$invi[account]',
        // 							'$invi[description]', '$invi[basis]', '$invi[from_date]',
        // 							'$invi[to_date]', '$invi[hours]', '$invi[weeks]',
        // 							'$invi[collection]')";
        // 				db_exec($sql) or errDie("Unable to create montly item.");
        // 			}
        // 		}
        db_connect();
        $sql = "INSERT INTO movinv(invtype, invnum, prd, docref, div) VALUES('pos', '{$invb['invnum']}', '{$invb['prd']}', '', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.", SELF);
        # get selected stock in this invoice
        db_connect();
        $sql = "SELECT * FROM hire.hire_invitems WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        while ($stkd = pg_fetch_array($stkdRslt)) {
            # insert invoice items
            $stkd['vatcode'] += 0;
            $stkd['account'] += 0;
            $sql = "INSERT INTO hire.hire_invitems(invid, whid, asset_id, qty,\r\n\t\t\t\t\t\tunitcost, amt, disc, discp, serno, div, vatcode, account,\r\n\t\t\t\t\t\tdescription)\r\n\t\t\t\t\tVALUES ('{$invb['invid']}', '{$stkd['whid']}',\r\n\t\t\t\t\t\t'{$stkd['asset_id']}', '{$stkd['qty']}', '{$stkd['unitcost']}',\r\n\t\t\t\t\t\t'{$stkd['amt']}', '{$stkd['disc']}', '{$stkd['discp']}',\r\n\t\t\t\t\t\t'{$stkd['serno']}', '" . USER_DIV . "', '{$stkd['vatcode']}',\r\n\t\t\t\t\t\t'{$stkd['account']}', '{$stkd['description']}')";
            $sql = "INSERT INTO hire.monthly_items (invid, whid, asset_id, qty,\r\n\t\t\t\t\t\tunitcost, amt, disc, discp, serno, div, vatcode, account,\r\n\t\t\t\t\t\tdescription)\r\n\t\t\t\t\tVALUES ('{$invb['invid']}', '{$stkd['whid']}', '{$stkd['asset_id']}',\r\n\t\t\t\t\t\t'{$stkd['qty']}', '{$stkd['unitcost']}', '{$stkd['amt']}',\r\n\t\t\t\t\t\t'{$stkd['disc']}', '{$stkd['discp']}',\t'{$stkd['serno']}',\r\n\t\t\t\t\t\t'" . USER_DIV . "',\t'{$stkd['vatcode']}', '{$stkd['account']}',\r\n\t\t\t\t\t\t '{$stkd['desciption']}')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
        }
    }
    // Update assets
    $sql = "SELECT * FROM hire.hire_invitems WHERE invid='{$inv['invid']}'";
    $item_rslt = db_exec($sql) or errDie("Unable to update items.");
    while ($item_data = pg_fetch_array($item_rslt)) {
        if (!isSerialized($item_data["asset_id"])) {
            $sql = "SELECT serial2 FROM cubit.assets\r\n\t\t\t\t\t\tWHERE id='{$item_data['asset_id']}'";
            $qty_rslt = db_exec($sql) or errDie("Unable to retrieve qty.");
            $qty = pg_fetch_result($qty_rslt, 0);
            $qty = $qty - $item_data["qty"];
            $sql = "UPDATE cubit.assets SET serial2='{$qty}'\r\n\t\t\t\t\t\tWHERE id='{$item_data['asset_id']}'";
            db_exec($sql) or errDie("Unable to update assets.");
            $sql = "SELECT id, units FROM hire.bookings\r\n\t\t\t\t\t\tWHERE cust_id='{$inv['cusnum']}' AND\r\n\t\t\t\t\t\t\tasset_id='{$item_data['asset_id']}'";
            $bk_rslt = db_exec($sql) or errDie("Unable to retrieve booking.");
            $bk_data = pg_fetch_array($bk_rslt);
            // Update booking information.
            if (!empty($bk_data["id"])) {
                if ($bk_data["units"] - $item_data["qty"] <= 0) {
                    $sql = "DELETE FROM hire.bookings WHERE id='{$bk_data['id']}'";
                } else {
                    $new_qty = $bk_data["units"] - $item_data["qty"];
                    $sql = "UPDATE hire.bookings SET units=(units-'{$new_qty}')\r\n\t\t\t\t\t\t\t\tWHERE id='{$bk_data['id']}'";
                }
                db_exec($sql) or errDie("Unable to update bookings.");
            }
            $item_qty = $item_data["qty"];
        } else {
            $sql = "DELETE FROM hire.bookings WHERE cust_id='{$inv['cusnum']}'\r\n\t\t\t\t\t\tAND asset_id='{$item_data['asset_id']}'";
            db_exec($sql) or errDie("Unable to remove booking.");
            $item_qty = 1;
        }
        $discount = $item_data["amt"] / 100 * $inv["traddisc"];
        $sql = "INSERT INTO hire.assets_hired (invid, asset_id, hired_time, qty,\r\n\t\t\t\t\t item_id, cust_id, invnum, basis, value, discount, weekends)\r\n\t\t\t\tVALUES ('{$invid}', '{$item_data['asset_id']}', CURRENT_TIMESTAMP,\r\n\t\t\t\t\t'{$item_qty}', '{$item_data['id']}', '{$inv['cusnum']}',\r\n\t\t\t\t\t'{$inv['invnum']}', '{$item_data['basis']}', '{$item_data['amt']}',\r\n\t\t\t\t\t'{$discount}', '{$item_data['weekends']}')";
        db_exec($sql) or errDie("Unable to hire out item.");
    }
    # Commit updates
    pglib_transaction("COMMIT");
    header("Location: hire-slip.php?invid={$inv['invid']}&prd={$inv['prd']}&cccc=yes");
    exit;
}
function writeLoan($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    $v->isOk($loanid, "num", 1, 20, "Invalid loan ID.");
    $v->isOk($loanamt, "float", 1, 10, "Invalid loan amount.");
    $v->isOk($loanint, "float", 1, 5, "Invalid loan interest.");
    $v->isOk($loanperiod, "num", 1, 3, "Invalid payback period.");
    $v->isOk($loaninstall, "float", 1, 10, "Invalid monthly installment.");
    $v->isOk($fringebenefit, "float", 1, 10, "Invalid fringe benefit amount.");
    $v->isOk($accid, "num", 1, 9, "Invalid bank account selected.");
    $v->isOk($account, "num", 1, 9, "Invalid contra account selected.");
    $v->isOk($loan_account, "num", 1, 9, "Invalid loan account selected.");
    $v->isOk($loan_type, "num", 1, 9, "Invalid loan type selected.");
    $ldate = mkdate($lyear, $lmonth, $lday);
    $v->isOk($ldate, "date", 1, 1, "Invalid loan date.");
    $archdate = mkdate($arch_year, $arch_month, $arch_day);
    $v->isOk($archdate, "date", 1, 1, "Invalid approval/denial date.");
    if (!checkdate($lmonth, $lday, $lyear)) {
        $v->addError("", "Invalid date.");
    }
    if ($account > 0 && isb($account) || isb($loan_account)) {
        $v->addError("", "Main accounts blocked. Please select sub accounts.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return enterLoan($confirmCust);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($ldate) >= strtotime($blocked_date_from) and strtotime($ldate) <= 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>";
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($archdate) >= strtotime($blocked_date_from) and strtotime($archdate) <= 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>";
    }
    # get employee details
    db_connect();
    $sql = "SELECT * FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "'";
    $empRslt = db_exec($sql) or errDie("Unable to select employees from database.");
    if (pg_numrows($empRslt) < 1) {
        return "Invalid employee ID.";
    }
    $myEmp = pg_fetch_array($empRslt);
    if (!isset($deny)) {
        # check for previous loan
        $sql = "SELECT empnum FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "' AND gotloan='t'::bool";
        $chkRslt = db_exec($sql) or errDie("Unable to check existing loans for employee.");
        if (pg_numrows($chkRslt) > 0) {
            return "<li class='err'>Loan already exists for employee number: {$empnum}.</li>";
        }
    }
    $date = date("Y-m-d");
    pglib_transaction("BEGIN");
    $totamount = sprint($loanperiod * $loaninstall);
    $loanint_amt = $totamount - $loanamt;
    $sql = "\n\t\tINSERT INTO emp_loanarchive (\n\t\t\tempnum, loanamt, loaninstall, loanint, loanperiod, loandate, archdate, loan_type, \n\t\t\tdiv, status\n\t\t) VALUES (\n\t\t\t'{$empnum}', '{$totamount}', '{$loaninstall}', '{$loanint}', '{$loanperiod}', '{$ldate}', '{$archdate}', '{$loan_type}', \n\t\t\t'" . USER_DIV . "', '" . (isset($deny) ? "D" : "A") . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to pre archive loan.");
    $loanaid = pglib_lastid('emp_loanarchive', 'id');
    $rem_sql = "DELETE FROM loan_requests WHERE id = '{$loanid}'";
    $run_rem = db_exec($rem_sql) or errDie("Unable to get loan requests information.");
    if (!isset($deny)) {
        $refnum = getrefnum();
        if ($accid > 0) {
            $bankacc = getbankaccid($accid);
        }
        if ($account > 0) {
            $bankacc = $account;
        }
        writetrans($loan_account, $bankacc, $archdate, $refnum, $loanamt, "Loan granted to employee {$myEmp['fnames']} {$myEmp['sname']}.");
        if ($accid > 0) {
            banktrans($accid, "withdrawal", $archdate, "{$myEmp['fnames']} {$myEmp['sname']}", "Loan granted to employee {$myEmp['fnames']} {$myEmp['sname']}.", 0, $loanamt, $loan_account);
        }
        # write to db
        $sql = "\n\t\t\tUPDATE cubit.employees \n\t\t\tSET loanamt = '{$totamount}', loanint = '{$loanint}', loanint_amt = '{$loanint_amt}', loanint_unpaid = '{$loanint_amt}', \n\t\t\t\tloanperiod = '{$loanperiod}', loaninstall = '{$loaninstall}', gotloan = 't'::bool, loanpayslip = '{$loanamt}', \n\t\t\t\tloanfringe = '{$fringebenefit}', loandate = '{$archdate}', expacc_loan = '{$loan_account}', \n\t\t\t\tloanamt_tot = '{$totamount}', loanid = '{$loanaid}' \n\t\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
        $loanRslt = db_exec($sql) or errDie("Unable to add loan to system.", SELF);
        if (pg_cmdtuples($loanRslt) < 1) {
            return "Unable to add loan to system.";
        }
    }
    pglib_transaction("COMMIT");
    $OUT = "<table " . TMPL_tblDflts . ">";
    if (isset($deny)) {
        $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<th>Loan Denied And Request Archived.</th>\n\t\t\t</tr>";
    } else {
        $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<th>Loan Granted And Added To System</th>\n\t\t\t</tr>";
    }
    $OUT .= "\n\t\t<tr class='datacell'>\n\t\t\t<td>Loan information successfully updated.</td>\n\t\t</tr>\n\t\t" . TBL_BR;
    if (!isset($deny)) {
        $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<td><input type='button' onclick=\"document.location='../reporting/loan_approval.php?id={$loanaid}'\" value='Generate Approval Report'></td>\n\t\t\t</tr>";
    }
    $OUT .= "\n\t\t</table><br>" . mkQuickLinks(ql("loan_apply.php", "Add Loan Application"), ql("loan_apply_view.php", "View Loan Applications"), ql("../admin-employee-add.php", "Add Employee"), ql("../admin-employee-view.php", "View Employees"));
    return $OUT;
}
Example #23
0
function enter($_GET, $err = "")
{
    # get vars
    extract($_GET);
    $amount = sprint($amount);
    if (!isset($e_year)) {
        explodeDate($_GET["edate"], $e_year, $e_month, $e_day);
    }
    $edate = mkDateSelect("e", $e_year, $e_month, $e_day);
    db_connect();
    $cc_list = "";
    if (!isset($remids)) {
        $remids = array();
    }
    $search_flag = FALSE;
    $search_val = "";
    if (isset($search) and strlen($search) > 0) {
        unset($changeproject);
        $get_ccid = "SELECT ccid FROM costcenters WHERE centercode = '{$search}' LIMIT 1";
        $run_ccid = db_exec($get_ccid) or errDie("Unable to get cost center information.");
        if (pg_numrows($run_ccid) > 0) {
            if (!isset($project1) or $project1 == "" or $project1 == "0") {
                unset($_GET["search"]);
                return enter($_GET, "<li class='err'>Please Select A Project First</li>");
            }
            $temparr = pg_fetch_array($run_ccid);
            $get_link = "SELECT id FROM costcenters_links WHERE ccid = '{$temparr['ccid']}' AND project1 = '{$project1}' LIMIT 1";
            $run_link = db_exec($get_link) or errDie("Unable to get cost center information.");
            if (pg_numrows($run_link) > 0) {
                $search_flag = TRUE;
                $val = pg_fetch_array($run_link);
                $search_val = $val['id'];
            } else {
                $search_flag = FALSE;
            }
        }
    }
    #compile list of selected centers
    if (isset($new_cc) and $new_cc != "0") {
        $ccids[] = $new_cc;
    }
    foreach ($remids as $each => $own) {
        if ($own == "yes") {
            unset($ccids[$each]);
        }
    }
    if (!isset($writeid)) {
        $writeid = "";
    }
    if (!isset($ccids)) {
        $ccids = "";
    }
    if (!isset($project1)) {
        $project1 = "";
    }
    if (!isset($cdescrip)) {
        $cdescrip = "";
    }
    $showedate = "{$e_year}-{$e_month}-{$e_day}";
    if ((!isset($writeid) or strlen($writeid) < 1) and $writeid != "0") {
        #write all this information to safe location for future retrieval
        $ins_sql = "\n\t\t\t\t\t\tINSERT INTO cc_popup_data \n\t\t\t\t\t\t\t(type,typename,edate,descrip,amount,cdescrip,sdate) \n\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t('{$type}','{$typename}','{$showedate}','{$descrip}','{$amount}','{$cdescrip}','now')\n\t\t\t\t\t";
        $run_ins = db_exec($ins_sql) or errDie("Unable to save cost center information.");
        $writeid = pglib_lastid("cc_popup_data", "id");
    }
    $project = "";
    $showproject = "<tr>";
    if (!isset($project1) or strlen($project1) < 1 or isset($changeproject)) {
        $showproject .= "<td><br></td></tr><tr><th colspan='3'>Select Project</th></tr><tr class='" . bg_class() . "'><td colspan='3'>";
        $showproject .= "<select name='project1' onChange='javascript:document.form1.submit();'>";
        $showproject .= "<option value='' disabled selected>Select Project</option>";
        $get_pros = "SELECT * FROM projects WHERE id != '1'";
        $run_pros = db_exec($get_pros) or errDie("Unable to get project information");
        if (pg_numrows($run_pros) > 0) {
            while ($parr = pg_fetch_array($run_pros)) {
                $showproject .= "<option value='{$parr['id']}'>{$parr['project_name']}</option>";
            }
        }
        $showproject .= "</select>";
        $showproject . "</td>";
        $prosearch = "0";
    } else {
        #show current + offer to change
        $get_pro = "SELECT * FROM projects WHERE id = '{$project1}' LIMIT 1";
        $run_pro = db_exec($get_pro) or errDie("Unable to get project information.");
        if (pg_numrows($run_pro) > 0) {
            $parr = pg_fetch_array($run_pro);
            $showproject .= "\n\t\t\t\t\t\t\t\t" . TBL_BR . "\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th colspan='3'>Cost Centers For Project : {$parr['project_name']}</th>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<input type='hidden' name='project1' value='{$project1}'>\n\t\t\t\t\t\t\t\t\t<td colspan='2'>{$parr['project_name']}</td>\n\t\t\t\t\t\t\t\t\t<td><input type='submit' name='changeproject' value='Change'></td>\n\t\t\t\t\t\t\t\t</tr>";
        }
        $prosearch = "{$project1}";
    }
    $showproject .= "</tr>";
    #get ccids of all cost centers in this 'project'
    $get_ccids = "SELECT id,ccid FROM costcenters_links WHERE project1 = '{$prosearch}'";
    $run_ccids = db_exec($get_ccids) or errDie("Unable to get cost center information.");
    if (pg_numrows($run_ccids) > 0) {
        $pccids = array();
        while ($ccarr = pg_fetch_array($run_ccids)) {
            $pccids[] = $ccarr['id'];
        }
    } else {
        $pccids[] = "";
    }
    #make the new dropdown
    $get_ccs = "SELECT * FROM costcenters_links";
    $run_ccs = db_exec($get_ccs) or errDie("Unable to get cost center information.");
    $cc_drop = "<input type='text' size='5' name='search'><select name='new_cc' onChange='javascript:document.form1.submit();'>";
    $cc_drop .= "<option value='0'>Select A Cost Center</option>";
    while ($cc = pg_fetch_array($run_ccs)) {
        $get_cname = "SELECT centername FROM costcenters WHERE ccid = '{$cc['ccid']}' LIMIT 1";
        $run_cname = db_exec($get_cname) or errDie("Unable to get cost center information.");
        if (pg_numrows($run_cname) == 1) {
            $varr = pg_fetch_array($run_cname);
            $cname = $varr['centername'];
        } else {
            $cname = "";
        }
        #first check if this cost center is in the 'selected' project
        if (in_array($cc['id'], $pccids)) {
            if (!is_array($ccids) or !in_array($cc['id'], $ccids)) {
                if ($search_flag) {
                    $ccids[] = $search_val;
                    $search_flag = FALSE;
                } else {
                    $cc_drop .= "<option value='{$cc['id']}'>{$cname}</option>";
                }
            }
        }
    }
    $cc_drop .= "</select>";
    if (is_array($ccids)) {
        $ccids = array_unique($ccids);
    }
    if (is_array($ccids)) {
        foreach ($ccids as $each => $own) {
            $get_cc = "SELECT ccid FROM costcenters_links WHERE id = '{$own}' LIMIT 1";
            $run_cc = db_exec($get_cc) or errDie("Unable to get cost center information.");
            if (pg_numrows($run_cc) < 1) {
                #problem
            }
            $arr = pg_fetch_array($run_cc);
            if (!isset($ccperc[$each])) {
                $ccperc[$each] = "";
            }
            if (!isset($ccidpro[$each])) {
                $ccidpro[$each] = $project1;
            }
            $get_cname = "SELECT centercode,centername FROM costcenters WHERE ccid = '{$arr['ccid']}' LIMIT 1";
            $run_cname = db_exec($get_cname) or errDie("Unable to get cost center information.");
            if (pg_numrows($run_cname) == 1) {
                $varr = pg_fetch_array($run_cname);
                $cname = $varr['centername'];
                $ccode = $varr['centercode'];
            } else {
                $cname = "";
                $ccode = "";
            }
            $cc_list .= "\n\t\t\t\t\t\t\t<input type='hidden' name='ccids[{$each}]' value='{$own}'>\n\t\t\t\t\t\t\t<input type='hidden' name='ccidpro[{$each}]' value='{$ccidpro[$each]}'>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>({$ccode}) {$cname}</td>\n\t\t\t\t\t\t\t\t<td><input type='text' name='ccperc[{$each}]' size='8' value='{$ccperc[$each]}'></td>\n\t\t\t\t\t\t\t\t<td><input type='checkbox' name='remids[{$each}]' value='yes' onClick='javascript:document.form1.submit();'></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t";
        }
    }
    $enter = "\n\t\t\t<center>\n\t\t\t<h3>Allocate amount to Cost Centers</h3>\n\t\t\t<center>{$err}</center>\n\t\t\t<br>\n\t\t\t<form action='" . SELF . "' method='POST' name='form1'>\n\t\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t\t<input type='hidden' name='type' value='{$type}'>\n\t\t\t\t<input type='hidden' name='typename' value='{$typename}'>\n\t\t\t\t<input type='hidden' name='amount' value='{$amount}'>\n\t\t\t\t<input type='hidden' name='descrip' value='{$descrip}'>\n\t\t\t\t<input type='hidden' name='cdescrip' value='{$cdescrip}'>\n\t\t\t\t<input type='hidden' name='e_year' value='{$e_year}'>\n\t\t\t\t<input type='hidden' name='e_month' value='{$e_month}'>\n\t\t\t\t<input type='hidden' name='e_day' value='{$e_day}'>\n\t\t\t\t<input type='hidden' name='writeid' value='{$writeid}'>\n\t\t\t\t<input type='hidden' name='project1' value='{$project1}'>\n\t\t\t<table " . TMPL_tblDflts . " width='400'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Field</th>\n\t\t\t\t\t<th colspan='2'>Value</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Type</td>\n\t\t\t\t\t<td colspan='2'>{$typename}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t<td colspan='2' nowrap>{$edate}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Total Amount</td>\n\t\t\t\t\t<td colspan='2'>{$amount}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Description</td>\n\t\t\t\t\t<td colspan='2'>{$descrip}</td>\n\t\t\t\t</tr>\n\t\t\t\t{$showproject}\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Cost Center</th>\n\t\t\t\t\t<th>% of Total Amount</th>\n\t\t\t\t\t<th>Remove</th>\n\t\t\t\t</tr>\n\t\t\t\t{$cc_list}\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='3'>{$cc_drop}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2 align='center'><input type='submit' name='done' value='Confirm &raquo;'></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</form>";
    return $enter;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($listname, "string", 1, 255, "Invalid Price list name.");
    if (isset($stkids)) {
        foreach ($stkids as $key => $value) {
            $v->isOk($stkids[$key], "num", 1, 20, "Invalid Stock Item number.");
            $v->isOk($prices[$key], "float", 1, 20, "Invalid Stock Item price.");
        }
    } else {
        return "<li class='err'> there is not stock for the price list.</li>";
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirmCust .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    # connect to db
    db_conn("exten");
    # write to db
    $sql = "INSERT INTO spricelist(listname, div) VALUES ('{$listname}', '" . USER_DIV . "')";
    $catRslt = db_exec($sql) or errDie("Unable to price list to system.", SELF);
    if (pg_cmdtuples($catRslt) < 1) {
        return "<li class='err'>Unable to add price list to database.</li>";
    }
    # get next ordnum
    $listid = pglib_lastid("spricelist", "listid");
    # Insert price list items
    foreach ($stkids as $key => $value) {
        db_connect();
        $sql = "SELECT stkid, prdcls, catid FROM stock WHERE stkid = '{$stkids[$key]}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
        $stk = pg_fetch_array($stkRslt);
        db_conn("exten");
        $sql = "\r\n\t\t\tINSERT INTO splist_prices (\r\n\t\t\t\tlistid, stkid, catid, clasid, price, div\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$listid}', '{$stkids[$key]}', '{$stk['catid']}', '{$stk['prdcls']}', '{$prices[$key]}', '" . USER_DIV . "'\r\n\t\t\t)";
        $rslt = db_exec($sql) or errDie("Unable to insert price list items to Cubit.", SELF);
    }
    // Layout
    $write = "\r\n\t\t<table " . TMPL_tblDflts . " width='50%'>\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Supplier Price list added to system</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='datacell'>\r\n\t\t\t\t<td>New Supplier Price list <b>{$listname}</b>, has been successfully added to the system.</td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t\t<p>\r\n\t\t<table border='0' cellpadding='2' cellspacing='1'>\r\n\t\t\t<tr>\r\n\t\t\t\t<th>Quick Links</th>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='sup-pricelist-view.php'>View Supplier Price Lists</a></td>\r\n\t\t\t</tr>\r\n\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t<td><a href='../main.php'>Main Menu</a></td>\r\n\t\t\t</tr>\r\n\t\t</table>";
    return $write;
}
function create_dummy($deptid)
{
    db_connect();
    # Dummy Vars
    $cusnum = 0;
    $salespn = "";
    $comm = "";
    $salespn = "";
    $chrgvat = getSetting("SELAMT_VAT");
    //	$odate = date("Y-m-d");
    $ordno = "";
    $delchrg = "0.00";
    $cordno = "";
    $terms = 0;
    $traddisc = 0;
    $SUBTOT = 0;
    $vat = 0;
    $total = 0;
    $trans_date_setting = getCSetting("USE_TRANSACTION_DATE");
    if (isset($trans_date_setting) and $trans_date_setting == "yes") {
        $trans_date_value = getCSetting("TRANSACTION_DATE");
        $date_arr = explode("-", $trans_date_value);
        $date_year = $date_arr[0];
        $date_month = $date_arr[1];
        $date_day = $date_arr[2];
    } else {
        $date_year = date("Y");
        $date_month = date("m");
        $date_day = date("d");
    }
    $odate = "{$date_year}-{$date_month}-{$date_day}";
    // $invid = divlastid('inv', USER_DIV);
    # insert invoice to DB
    $sql = "\n\t\tINSERT INTO rec_invoices (\n\t\t\tdeptid, cusnum, cordno, ordno, chrgvat, terms, traddisc, salespn, odate, \n\t\t\tdelchrg, subtot, vat, total, balance, comm, username, done, prd, div\n\t\t) VALUES (\n\t\t\t'{$deptid}', '{$cusnum}',  '{$cordno}', '{$ordno}', '{$chrgvat}', '{$terms}', '{$traddisc}', '{$salespn}', '{$odate}', \n\t\t\t'{$delchrg}', '{$SUBTOT}', '{$vat}' , '{$total}', '{$total}', '{$comm}', '" . USER_NAME . "', 'n', '" . PRD_DB . "', '" . USER_DIV . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice to Cubit.", SELF);
    # get next ordnum
    $invid = pglib_lastid("rec_invoices", "invid");
    return $invid;
}
function hire()
{
    extract($_REQUEST);
    // Invoice ----------------------------------------------------------------
    $deptid = "2";
    $salespn = "";
    $comm = "";
    $salespn = "";
    $chrgvat = getSetting("SELAMT_VAT");
    $odate = date("Y-m-d");
    $ordno = "";
    $delchrg = "0.00";
    $cordno = "";
    $terms = 0;
    $traddisc = 0;
    $SUBTOT = 0;
    $vat = 0;
    $total = 0;
    $vatnum = "";
    $cusacc = "";
    $telno = "";
    $collection = "";
    $custom_txt = "";
    // Retrieve the booking
    $sql = "SELECT * FROM hire.bookings WHERE id='{$id}'";
    $booking_rslt = db_exec($sql) or errDie("Unable to retrieve booking.");
    $booking_data = pg_fetch_array($booking_rslt);
    $cusnum = $booking_data["cust_id"];
    # insert invoice to DB
    $sql = "INSERT INTO hire.hire_invoices(deptid, cusnum, cordno, ordno,\r\n\t\tchrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, total,\r\n\t\tbalance, comm, username, printed, done, prd, vatnum, cusacc, telno, div,\r\n\t\tcollection, custom_txt)\r\n\tVALUES('{$deptid}', '{$cusnum}',  '{$cordno}', '{$ordno}', '{$chrgvat}', '{$terms}',\r\n\t\t'{$traddisc}', '{$salespn}', '{$odate}', '{$delchrg}', '{$SUBTOT}', '{$vat}' ,\r\n\t\t'{$total}', '{$total}', '{$comm}', '" . USER_NAME . "', 'n', 'n', '" . PRD_DB . "',\r\n\t\t'{$vatnum}', '{$cusacc}', '{$telno}', '" . USER_DIV . "', '{$collection}', '{$custom_txt}')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice to Cubit.", SELF);
    # get next ordnum
    db_conn("hire");
    $invid = pglib_lastid("hire_invoices", "invid");
    header("Location:hire-invoice-new.php?invid={$invid}&bk_asset={$booking_data['asset_id']}&bk_id={$booking_data['id']}&bk_from={$booking_data['from_date']}&bk_to={$booking_data['to_date']}");
}
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 write($_POST)
{
    extract($_POST);
    $id += 0;
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($name, "string", 1, 100, "Invalid name.");
    $v->isOk($pos, "string", 0, 100, "Invalid position.");
    $v->isOk($tell, "string", 0, 100, "Invalid tel.");
    $v->isOk($cell, "string", 0, 100, "Invalid cel.");
    $v->isOk($fax, "string", 0, 100, "Invalid fax.");
    $v->isOk($email, "email", 0, 100, "Invalid email.");
    $v->isOk($notes, "string", 0, 200, "Invalid notes.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $confirm . enter($_POST);
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM cons WHERE id='{$id}'";
    $Ry = db_exec($Sl) or errDie("Unable to get con info.");
    if (pg_num_rows($Ry) < 1) {
        return "Invalid contact.";
    }
    $Sl = "INSERT INTO conpers (con,name,pos,tell,cell,fax,email,notes,div) VALUES('{$id}','{$name}','{$pos}','{$tell}','{$cell}','{$fax}','{$email}','{$notes}','" . USER_DIV . "')";
    $Ry = db_exec($Sl) or errDie("Unable to insert conper.");
    $conid = pglib_lastid("conpers", "id");
    if (isset($crm)) {
        header("Location: crm/tokens-new.php?id={$id}&conper={$conid}");
        exit;
    }
    // Write the image (if any)
    if ($upload_img == "yes") {
        if (preg_match("/(image\\/jpeg|image\\/png|image\\/gif)/", $_FILES["img_file"]["type"], $extension)) {
            $img = "";
            $fp = fopen($_FILES["img_file"]["tmp_name"], "rb");
            while (!feof($fp)) {
                $img .= fread($fp, 1024);
            }
            fclose($fp);
            $img = base64_encode($img);
            $sql = "INSERT INTO cubit.scons_img (con_id, type, file, size)\r\n\t\t\tVALUES ('{$con_id}', '" . $_FILES["img_file"]["type"] . "', '{$img}',\r\n\t\t\t\t'" . $_FILES["img_file"]["size"] . "')";
            $ci_rslt = db_exec($sql) or errDie("Unable to add contact image.");
        } else {
            return "<li class='err'>\r\n\t\t\t\tPlease note we only accept PNG, GIF and JPEG images.\r\n\t\t\t</li>";
        }
    }
    $out = "\r\n\t\t\t\t<table " . TMPL_tblDflts . " width='50%'>\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Contact added</th>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='datacell'>\r\n\t\t\t\t\t\t<td>{$name} has been added to Cubit.</td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</table>\r\n\t\t\t\t<p>\r\n\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Quick Links</th>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td><a href='conper-add.php?type=conn&id={$id}'>Add another contact</a></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td><a href='list_cons.php'>Contacts</a></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\r\n\t\t\t\t\t</tr>\r\n\t\t\t\t</table>";
    return $out;
}
$sql = "INSERT INTO cubit.ratio_account_types (rtype, rname)\n\t\tVALUES ('working_capital', 'Working Capital')";
db_exec($sql) or errDie("Unable to create ratio type");
$type_id = pglib_lastid("cubit.ratio_account_types", "id");
$accid = qryAccountsName("Share Capital / Members Contribution");
$accid = $accid["accid"];
$sql = "INSERT INTO cubit.ratio_account_owners (type_id, accid)\n\t\tVALUES ('{$type_id}', '{$accid}')";
db_exec($sql) or errDie("Unable to add ratio account.");
// Setup Long Term Liabilities ------------------------------------------------
$sql = "INSERT INTO cubit.ratio_account_types (rtype, rname)\n\t\tVALUES ('long_term_liabilities', 'Long Term Liabilities')";
db_exec($sql) or errDie("Unable to create ratio type");
$type_id = pglib_lastid("cubit.ratio_account_types", "id");
$accid = qryAccountsName("Shareholder / Director / Members Loan Account");
$accid = $accid["accid"];
$sql = "INSERT INTO cubit.ratio_account_owners (type_id, accid)\n\t\tVALUES ('{$type_id}', '{$accid}')";
db_exec($sql) or errDie("Unable to add ratio account.");
// Setup Owners Equity --------------------------------------------------------
$sql = "INSERT INTO cubit.ratio_account_types (rtype, rname)\n\t\tVALUES ('owners_equity', 'Owners Equity')";
db_exec($sql) or errDie("Unable to create ratio type");
$type_id = pglib_lastid("cubit.ratio_account_types", "id");
$accid = qryAccountsName("Share Capital / Members Contribution");
$accid = $accid["accid"];
$sql = "INSERT INTO cubit.ratio_account_owners (type_id, accid)\n\t\tVALUES ('{$type_id}', '{$accid}')";
db_exec($sql) or errDie("Unable to add ratio account.");
// Setup Interest Expense -----------------------------------------------------
$sql = "INSERT INTO cubit.ratio_account_types (rtype, rname)\n\t\tVALUES ('interest_expense', 'Interest Expense')";
db_exec($sql) or errDie("Unable to create ratio type");
$type_id = pglib_lastid("cubit.ratio_account_types", "id");
$accid = qryAccountsName("Interest Paid");
$accid = $accid["accid"];
$sql = "INSERT INTO cubit.ratio_account_owners (type_id, accid)\n\t\tVALUES ('{$type_id}', '{$accid}')";
db_exec($sql) or errDie("Unable to add ratio account.");
 function errorNetSave()
 {
     global $XMLNS;
     global $ERRNET_ERRORS;
     global $SQL_EXEC;
     global $CUBIT_MODULES;
     if (!defined("ERRORNET_OCCURED")) {
         return -1;
     }
     $xmlns = "xmlns=\"{$XMLNS['errornet']}\"";
     $OUT = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
     $OUT .= "<cubiterror version=\"0.1\" time=\"" . date("l dS \\of F Y h:i:s A") . "\"/>\n";
     /* cubit info */
     $OUT .= "<cubit {$xmlns}\n>\n";
     $OUT .= "<cdata {$xmlns} desc=\"version\">" . CUBIT_VERSION . "</cdata>\n";
     $OUT .= "<cdata {$xmlns} desc=\"build\">" . CUBIT_BUILD . "</cdata>\n";
     $OUT .= "<cdata {$xmlns} desc=\"platform\" value=\"" . PLATFORM . "\">" . xmldata(php_uname()) . "</cdata>\n";
     $OUT .= "<cdata {$xmlns} desc=\"phpversion\">" . phpversion() . "</cdata>\n";
     $OUT .= "<cdata {$xmlns} desc=\"cengineversion\">" . phpversion("cengine") . "</cdata>\n";
     $OUT .= "<cdata {$xmlns} desc=\"debugmode\">" . (defined("DEBUG") && DEBUG == 1 ? "true" : "false") . "</cdata>\n";
     $OUT .= "<cmodules {$xmlns}>\n";
     $OUT .= array2xml("cdata", "num", "{$xmlns}", $CUBIT_MODULES);
     $OUT .= "</cmodules>\n";
     $OUT .= "</cubit>";
     /* sql queries */
     $OUT .= "<sql {$xmlns}>\n";
     $OUT .= array2xml("data", "num", "{$xmlns}", $SQL_EXEC);
     $OUT .= "</sql>";
     /* php configuration */
     $OUT .= "<phpconf {$xmlns}>\n";
     $OUT .= array2xml("data", "name", "{$xmlns}", ini_get_all());
     $OUT .= "</phpconf>\n";
     /* error details */
     $errnum = 1;
     foreach ($ERRNET_ERRORS as $k => $v) {
         $OUT .= "<error {$xmlns} num=\"{$errnum}\">\n";
         $OUT .= "{$v}\n";
         $OUT .= "</error>\n";
         ++$errnum;
     }
     $errdata = base64_encode($OUT);
     db_con("cubit");
     pglib_transact("ROLLBACK");
     $sql = "INSERT INTO errordumps (errtime, errdata)\n\t\t\tVALUES(CURRENT_TIMESTAMP, '{$errdata}')";
     $rslt = db_exec($sql) or errDie("Error storing error dump report.");
     return pglib_lastid("errordumps", "id");
 }