function create_dummy($deptid, $cusnum)
{
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to get customer information");
    $cust = pg_fetch_array($custRslt);
    $curr = getSymbol($cust['fcid']);
    $xrate = getRate($cust['fcid']);
    $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}";
    db_connect();
    # Insert purchase to DB
    $sql = "\n\t\tINSERT INTO nons_invoices (\n\t\t\tcusname, cusaddr, cusvatno, chrgvat, fcid, currency, \n\t\t\txrate, odate, sdate, subtot, balance, vat, total, done, username, prd, invnum, typ, ctyp, \n\t\t\ttval, location, div\n\t\t) VALUES (\n\t\t\t'{$cust['cusname']} {$cust['surname']}', '{$cust['addr1']}', '{$cust['vatnum']}', 'yes', '{$cust['fcid']}', '{$curr['symbol']}', \n\t\t\t'{$xrate}', '{$odate}', CURRENT_DATE, 0, 0, 0, 0, 'n', '" . USER_NAME . "', '" . PRD_DB . "', 0, 'inv', 's', \n\t\t\t'{$cusnum}', 'int', '" . USER_DIV . "'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to create template Non-Stock Invoice.", SELF);
    # Get next ordnum
    $invid = lastinvid();
    return $invid;
}
function edit(&$frm)
{
    /* @var $frm cForm */
    $frm->setkey("confirm");
    $frm->settitle("Point of Sale Settings");
    $frm->add_heading("Point of Sale Slips/Printing");
    /* point of sale message at the bottom of the slip */
    $posmsg = getCSetting("POSMSG");
    $frm->add_textarea("Message to Display at bottom of Slip", "posmsg", $posmsg, "1:255");
    return $frm->getfrm_input();
}
function edit(&$frm)
{
    /* @var $frm cForm */
    $frm->setkey("write");
    $frm->settitle("Printing Options");
    $frm->add_heading("Details");
    $yn = array("y" => "Yes", "n" => "No");
    $print_dialog = getCSetting("PRINT_DIALOG");
    $frm->add_select("Automatically Display Print Dialog", "print_dialog", $print_dialog, $yn, "string", "1:1");
    $frm->add_ctrlbtn("Save", "submit", "btn_submit");
    return $frm->getfrm_input();
}
function edit(&$frm)
{
    /* @var $frm cForm */
    $frm->setkey("write");
    $frm->settitle("Purchase Default VAT Setting");
    $frm->add_heading("Setting");
    $yn = array("yes" => "VAT Inclusive", "no" => "VAT Exclusive");
    $vat_setting = getCSetting("PURCH_DEFAULT_VAT_SETTING");
    $frm->add_select("Default Stock Purchase VAT Setting", "vat_setting", $vat_setting, $yn, "string", "2:3");
    $frm->add_ctrlbtn("Save", "submit", "btn_submit");
    return $frm->getfrm_input();
}
function do_setting()
{
    extract($_GET);
    $inv_set = getCSetting("NEWINV_SETTING");
    if (isset($vol) && $vol == "yes") {
        $script = "calc-cust-credit-stockinv.php";
    } else {
        $script = "cust-credit-stockinv.php";
    }
    if ($inv_set == "no") {
        return mkQuickLinks(ql("../{$script}", "Make Another Invoice"), ql("cust-credit-stockinv-newsetting.php?change=yes", "Change Setting To Create A New Invoice After Processing One."), ql("../invoice-view.php", "View Invoices"));
    } else {
        header("Location: ../{$script}");
    }
}
function change_settings($_POST)
{
    extract($_POST);
    $traddisc_check = getCSetting("SET_INV_TRADDISC");
    db_connect();
    if (!isset($traddisc_check) or strlen($traddisc_check) < 1) {
        #setting does not yet exist ... ad it :/
        $add_sql = "INSERT INTO cubit.settings (constant,label,value,type,datatype,minlen,maxlen,div,readonly) VALUES ('SET_INV_TRADDISC','Include/Exclude  Delivery Charge In Trade Discount','exclude','general','string','7','7','0','f');";
        $run_add = db_exec($add_sql) or errDie("Unable to get settings information.");
    } else {
        #update the setting ...
        $upd_sql = "UPDATE settings SET value = '{$traddisc}' WHERE constant = 'SET_INV_TRADDISC'";
        $run_upd = db_exec($upd_sql) or errDie("Unable to update setting information.");
    }
    return show_settings("<li class='err'>Settings Have Been Saved.</li><br>");
}
function save_setting_val($_POST)
{
    extract($_POST);
    db_connect();
    #check for setting
    $check = getCSetting("JOBCARD_OPERATION_STOCK_CHECKBOX");
    if (!isset($check) or strlen($check) < 1) {
        #no setting ... insert
        $sql = "\n\t\t\tINSERT INTO cubit.settings (\n\t\t\t\tconstant, label, value, type, datatype, minlen, maxlen, div, readonly\n\t\t\t) VALUES (\n\t\t\t\t'JOBCARD_OPERATION_STOCK_CHECKBOX', 'Jobcard Operation Add Stock Checkbox Default Setting', '{$operation_setting}', 'general', 'allstring', '6', '14', '0', 'f'\n\t\t\t)";
        $run_sql = db_exec($sql) or errDie("Unable to record setting information.");
    } else {
        $upd_sql = "UPDATE settings SET value = '{$operation_setting}' WHERE constant = 'JOBCARD_OPERATION_STOCK_CHECKBOX'";
        $run_upd = db_exec($upd_sql) or errDie("Unable to update customer statement setting.");
    }
    return get_setting_val("<li class='err'>Jobcard Operation Add Stock Setting Updated.</li><br>");
}
function save_setting_val($_POST)
{
    extract($_POST);
    db_connect();
    #check for setting
    $check = getCSetting("STATEMENT_AGE");
    if (!isset($check) or strlen($check) < 1) {
        #no setting ... insert
        $sql = "\n\t\t\t\tINSERT INTO cubit.settings \n\t\t\t\t\t(constant,label,value,type,datatype,minlen,maxlen,div,readonly) \n\t\t\t\tVALUES \n\t\t\t\t\t('STATEMENT_AGE','Customer Statement','{$state_setting}','general','allstring','6','9','0','f')";
        $run_sql = db_exec($sql) or errDie("Unable to record setting information.");
    } else {
        $upd_sql = "UPDATE settings SET value = '{$state_setting}' WHERE constant = 'STATEMENT_AGE'";
        $run_upd = db_exec($upd_sql) or errDie("Unable to update customer statement setting.");
    }
    return get_setting_val("<li class='err'>Customer Statement Setting Updated.</li><br>");
}
function show_receipt($_GET)
{
    extract($_GET);
    if (!isset($recid) or strlen($recid) < 1) {
        return "<li class='err'>Invalid use of module. Invalid Receipt ID.</li>";
    }
    db_connect();
    $get_rec = "SELECT * FROM cashbook WHERE cashid = '{$recid}' LIMIT 1";
    $run_rec = db_exec($get_rec) or errDie("Unable to get receipt information.");
    if (pg_numrows($run_rec) < 1) {
        return "<li class='err'>Receipt information not found.</li>";
    } else {
        $cash_arr = pg_fetch_array($run_rec);
        #get customer information
        $get_cust = "SELECT accno,surname,paddr1 FROM customers WHERE cusnum = '{$cash_arr['cusnum']}' LIMIT 1";
        $run_cust = db_exec($get_cust) or errDie("Unable to get customer information.");
        if (pg_numrows($run_cust) < 1) {
            $cus_addr = "";
            $cus_accno = "";
        } else {
            $cus_arr = pg_fetch_array($run_cust);
            $cus_addr = $cus_arr['paddr1'];
            $cus_accno = $cus_arr['accno'];
        }
        $inv_ids = explode("|", $cash_arr['rinvids']);
        $inv_amts = explode("|", $cash_arr['amounts']);
        $null1 = array_shift($inv_ids);
        $null2 = array_shift($inv_amts);
        $listing = "";
        $total = 0;
        foreach ($inv_ids as $key => $each) {
            $listing .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$cash_arr['date']}</td>\n\t\t\t\t\t<td>{$cash_arr['reference']}</td>\n\t\t\t\t\t<td>" . CUR . " " . sprint($inv_amts[$key]) . "</td>\n\t\t\t\t</tr>";
            $total = $total + $inv_amts[$key];
        }
        $unalloc = $cash_arr['amount'] - $total;
        if ($unalloc > 0) {
            $listing .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$cash_arr['date']}</td>\n\t\t\t\t\t<td>{$cash_arr['reference']} (Unallocated)</td>\n\t\t\t\t\t<td>" . CUR . " " . sprint($unalloc) . "</td>\n\t\t\t\t</tr>";
            $total += $unalloc;
        }
        $listing .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='right'><b>Total:</b></td>\n\t\t\t\t<td>" . CUR . " " . sprint($total) . "</td>\n\t\t\t</tr>";
        $receiptnumber = $cash_arr['cashid'];
    }
    $comments = getCSetting("DEFAULT_BANK_RECPT_COMMENTS");
    $rborder = "style='border-right: 2px solid #000'";
    $display = "\n\t\t<style>\n\t\t\ttable { border: 2px solid #000 }\n\t\t</style>\n\t\t<table border='0' cellpadding='2' cellspacing='2' width='80%' align='center'>\n\t\t\t<tr>\n\t\t\t\t<td width='30%'></td>\n\t\t\t\t<td align='center'><font size='5'><b>" . COMP_NAME . "</b></font></td>\n\t\t\t\t<td align='right'><font size='4'><b>Customer Receipt</b></font></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table cellpadding='1' cellspacing='0' width='80%' align='center'>\n\t\t\t<tr>\n\t\t\t\t<td {$rborder}>\n\t\t\t\t\t<b>" . COMP_NAME . "</b><br>\n\t\t\t\t\t" . COMP_ADDRESS . "<br>\n\t\t\t\t\t" . COMP_PADDR . "\n\t\t\t\t</td>\n\t\t\t\t<td>\n\t\t\t\t\t<b>Received From:</b><br>\n\t\t\t\t\t{$cash_arr['name']}<br>\n\t\t\t\t\t{$cus_addr}<br>\n\t\t\t\t\t<br>\n\t\t\t\t\t<b>Account Number:</b> {$cus_accno}<br>\n\t\t\t\t\t<b>Receipt Number:</b> {$receiptnumber}\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . " width='80%' align='center'>\n\t\t\t<tr>\n\t\t\t\t<td><b>Date</b></td>\n\t\t\t\t<td><b>Ref Num</b></td>\n\t\t\t\t<td><b>Amount</b></td>\n\t\t\t</tr>\n\t\t\t{$listing}\n\t\t\t" . TBL_BR . "\n\t\t\t" . TBL_BR . "\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . " width='80%' align='center'>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td width='60%'>" . nl2br(base64_decode($comments)) . "</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></td>\n\t\t\t\t<td align='center'>Signature</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<div style='position:absolute;left:11%'>\n\t\t<font size='1'>&#169 Cubit Accounting Software</font>\n\t\t</div>";
    return $display;
}
function get_current_setting()
{
    db_connect();
    $sort_order_setting = getCSetting("ACCOUNT_SORT_ORDER");
    if (!isset($sort_order_setting) or strlen($sort_order_setting) < 1) {
        $sort_order_setting = "number";
    }
    if ($sort_order_setting == "number") {
        $checked1 = "checked='yes'";
        $checked2 = "";
    } else {
        $checked1 = "";
        $checked2 = "checked='yes'";
    }
    $display = "\n\t\t<h2>Accounts Selected Sort Order</h2>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Accounts Sort Order</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='radio' name='sort_order' value='number' {$checked1}> Account Number - Account Name \n\t\t\t\t\t<input type='radio' name='sort_order' value='name' {$checked2}> Account Name - Account Number \n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input type='submit' value='Save Setting'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>";
    return $display;
}
function select($frm)
{
    extract($_REQUEST);
    if (!isset($emp_year)) {
        $emp_year = getCSetting("EMP_TAXYEAR");
    }
    /* @var $frm cForm */
    $frm->setkey("confirm");
    $frm->settitle("Select Active Employee Tax Year");
    $frm->setmsg("The employee's tax year will end on 28 February of the year you select below.<br />\n\t\t<li class='err'>Also note that, no matter which year is chosen below, the 2006/2007 PAYE\n\t\t\ttax tables will be used until current tax legislation is changed..</li>");
    $yrs = array();
    for ($i = 1990; $i < 2028; ++$i) {
        $yrs[$i] = $i;
    }
    $frm->add_heading("Select");
    $frm->add_select("Tax Year", "emp_year", $emp_year, $yrs, "num", "4:4");
    return $frm->getfrm_input();
}
function confirm_info_setting($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($pay_type, "string", 1, 15, "Invalid Payment Method");
    $v->isOk($process_type, "string", 1, 15, "Invalid Payment Process Method");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $confirmCust;
    }
    db_connect();
    pglib_transaction("BEGIN") or errDie("Unable to start transaction.");
    $check = getCSetting("SUPP_PAY_TYPE");
    if (!isset($check) or strlen($check) < 1) {
        #no setting ... insert
        $ins_sql = "INSERT INTO settings (constant,label,value,type,datatype,minlen,maxlen,div,readonly) VALUES ('SUPP_PAY_TYPE','Supplier Payment Type','{$pay_type}','general','allstring','1','20','0','f')";
        $run_ins = db_exec($ins_sql) or errDie("Unable to record supplier payment setting.");
    } else {
        #settings ... update
        $upd_sql = "UPDATE settings SET value = '{$pay_type}' WHERE constant = 'SUPP_PAY_TYPE'";
        $run_upd = db_exec($upd_sql) or errDie("Unable to update supplier pay type setting.");
    }
    $check2 = getCSetting("SUPP_PROCESS_TYPE");
    if (!isset($check2) or strlen($check2) < 1) {
        #no setting ... insert
        $ins_sql = "INSERT INTO settings (constant,label,value,type,datatype,minlen,maxlen,div,readonly) VALUES ('SUPP_PROCESS_TYPE','Supplier Payment Process Type','{$process_type}','general','allstring','1','20','0','f')";
        $run_ins = db_exec($ins_sql) or errDie("Unable to record supplier payment setting.");
    } else {
        #settings ... update
        $upd_sql = "UPDATE settings SET value = '{$process_type}' WHERE constant = 'SUPP_PROCESS_TYPE'";
        $run_upd = db_exec($upd_sql) or errDie("Unable to update supplier pay type setting.");
    }
    pglib_transaction("COMMIT") or errDie("Unable to complete transaction.");
    return get_info_setting($_POST, "<li class='err'>Supplier Settings Updated</li><br>");
}
function write_setting($_POST)
{
    extract($_POST);
    if (!isset($setting) or strlen($setting) < 1) {
        $setting = "";
    }
    db_connect();
    #update setting
    $check = getCSetting("MARKET_MAIL_FROM");
    if (!isset($check) or strlen($check) < 1) {
        #no setting ... insert
        $ins_sql = "\n\t\t\tINSERT INTO settings (\n\t\t\t\tconstant, label, value, type, \n\t\t\t\tdatatype, minlen, maxlen, div, readonly\n\t\t\t) VALUES (\n\t\t\t\t'MARKET_MAIL_FROM', 'Marketing Email From Address', '{$setting}', 'general',\n\t\t\t\t'allstring', '1', '250', '0', 'f'\n\t\t\t);\n\t\t\t\t";
        $run_ins = db_exec($ins_sql) or errDie("Unable to remove marketing from email information.");
    } else {
        #setting ... update
        $upd_sql = "UPDATE settings SET value = '{$setting}' WHERE constant = 'MARKET_MAIL_FROM'";
        $run_upd = db_exec($upd_sql) or errDie("Unable to update marketing email information.");
    }
    return get_show_setting("<li class='err'>Email Setting Updated</li>");
}
function editSettings()
{
    # connect to db
    db_connect();
    /* static settings for dumb sars thing... you might as well just make your percentage 0 */
    $i = 0;
    if (!isset($sdlpayable)) {
        $sdlpayable = getCSetting("SDLPAYABLE");
    }
    if (!isset($emploan_int)) {
        $emploan_int = getCSetting("EMPLOAN_INT");
    }
    $settings = "";
    $settings .= "\n\t<script>\n\thelp_msgs = new Array();\n\n\thelp_msgs[0] =\n\t\t 'When the total annual salaries being paid out by your company is less than '\n\t\t+'R500 000, SARS will notify your company that no SDL needs to be paid. In the event '\n\t\t+'this amount does go above R500 000, you will again be notified otherwise.';\n\n\thelp_msgs[1] =\n\t\t 'This value is used as the default interest to be used when granting a loan to '\n\t\t+'an employee. At the time of granting, it is possible to change it again if '\n\t\t+'needed. Note that this is not and does not change the Official interest rate of 8%. '\n\t\t+'If the interest you charge on the loan is less than the official rate, '\n\t\t+'a fringe benefit equal to the difference of the interest you charged and '\n\t\t+'the possible interest at the official rate will be added to the employee\\'s '\n\t\t+'taxable income for PAYE calculation purposes.';\n\n\tfunction showhelp(obj, item) {\n\t\tXPopupShow(help_msgs[item], obj);\n\t}\n\t</script>\n\t<tr class='" . bg_class() . "'>\n\t\t<!--<td><a href='#top'>Top</a> | <a href='#bottom'>Bottom</a></td>//-->\n\t\t<td align='center'>SDL Payable [<a href='#' onClick='javascript:showhelp(this, 0);'>about</a>]</td>\n\t\t<td>\n\t\t\t<select name='sdlpayable'>\n\t\t\t\t<option value='y' " . ($sdlpayable != 'n' ? "selected" : "") . ">Yes</option>\n\t\t\t\t<option value='n' " . ($sdlpayable == 'n' ? "selected" : "") . ">No</option>\n\t\t\t</select>\n\t\t</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<!--<td><a href='#top'>Top</a> | <a href='#bottom'>Bottom</a></td>//-->\n\t\t<td align='center'>Default Interest on Employee Loans [<a href='#' onClick='javascript:showhelp(this, 1);'>about</a>]</td>\n\t\t<td>\n\t\t\t<input type='text' name='emploan_int' value='{$emploan_int}'>\n\t\t</td>\n\t</tr>";
    # select editable settings from db
    $menu = "";
    $sql = "SELECT * FROM settings WHERE type='accounting' AND (readonly='f'::bool) ORDER BY label";
    $setRslt = db_exec($sql) or errDie("Unable to select settings from database.");
    $num_settings = pg_numrows($setRslt);
    if ($num_settings < 1) {
        errDie("No settings found in database!");
    }
    while ($mySet = pg_fetch_array($setRslt)) {
        //$menu .= (($i+1) % 4) ? "<a href='#$mySet[constant]' class=nav>$mySet[label]</a> | " : "<a href='#$mySet[constant]' class=nav>$mySet[label]</a><p>\n";
        $settings .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<!--<td><a href='#top'>Top</a> | <a href='#bottom'>Bottom</a></td>//-->\n\t\t\t<td align=center><a name='{$mySet['constant']}'></a>{$mySet['label']}</td>\n\t\t\t<td><input type=text size=20 name='{$mySet['constant']}' value='{$mySet['value']}'></td>\n\t\t</tr>\n";
        $i++;
    }
    $Sl = "SELECT * FROM salset";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        $set = "selected";
        $set2 = "";
    } else {
        $set = "";
        $set2 = "selected";
    }
    $sets = "<select name='set'>\n\t<option value='Yes' {$set}>Yes</option>\n\t<option value='No' {$set2}>No</option>\n\t</select>";
    # Set up table & form
    $enterSettings = "<h3>Edit accounting settings</h3>\n<a name=top></a>\n{$menu}\n<p>\n<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n<form action='" . SELF . "' method=post>\n<input type=hidden name=key value=confirm>\n<tr><th>Description</th><th>Value</th></tr>\n{$settings}\n<tr><td colspan=3 align=right><input type=submit value='Confirm &raquo;'></td></tr>\n</form>\n</table>" . mkQuickLinks(ql("../admin-employee-add.php", "Add Employee"), ql("../admin-employee-view.php", "View Employees")) . "\n<a name=bottom></a>\n";
    return $enterSettings;
}
function create_dummy($deptid)
{
    $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}";
    db_connect();
    # Insert purchase to DB
    $sql = "\n\t\tINSERT INTO nons_invoices (\n\t\t\tcusname, cusaddr, cusvatno, chrgvat, sdate, odate, subtot, balance, vat, total, done, username, prd, invnum, \n\t\t\ttyp, div, multiline \n\t\t) VALUES (\n\t\t\t'', '', '', 'yes', CURRENT_DATE, '{$odate}', 0, 0, 0, 0, 'n', '" . USER_NAME . "', '" . PRD_DB . "', 0, \n\t\t\t'quo', '" . USER_DIV . "', 'yes'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to create template Non-Stock Quote.", SELF);
    return lastinvid();
}
function get_current_setting()
{
    db_connect();
    $date_setting = getCSetting("TRANSACTION_DATE");
    $use_date_setting = getCSetting("USE_TRANSACTION_DATE");
    if (!isset($date_setting) or strlen($date_setting) < 1) {
        $date_setting = date("Y-m-d");
    }
    if (!isset($use_date_setting) or strlen($use_date_setting) < 1) {
        $use_date_setting = "no";
    }
    $date_arr = explode("-", $date_setting);
    if ($use_date_setting == "yes") {
        $checked1 = "";
        $checked2 = "checked='yes'";
    } else {
        $checked1 = "checked='yes'";
        $checked2 = "";
    }
    $display = "\n\t\t<h2>Transaction Date To Use</h2>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Transaction Date Setting</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='radio' name='use_date_setting' value='no' {$checked1}> Use System Date \n\t\t\t\t\t<input type='radio' name='use_date_setting' value='yes' {$checked2}> Use This Date \n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<th>Transaction Date To Use</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>" . mkDateSelect("transaction", "{$date_arr['0']}", "{$date_arr['1']}", "{$date_arr['2']}") . "</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input type='submit' value='Save Setting'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>";
    return $display;
}
function write_setting()
{
    extract($_POST);
    db_connect();
    $check1 = getCSetting("BLOCKED_FROM");
    $check2 = getCSetting("BLOCKED_TO");
    if (!isset($check1) or strlen($check1) < 1) {
        $ins_sql = "\n\t\t\tINSERT INTO settings (\n\t\t\t\tconstant, label, value, type, \n\t\t\t\tdatatype, minlen, maxlen, div, readonly\n\t\t\t) VALUES (\n\t\t\t\t'BLOCKED_FROM', 'Blocked Period Date Range From', '{$from_year}-{$from_month}-{$from_day}', 'accounting', \n\t\t\t\t'allstring', '10', '10', '0','f'\n\t\t\t)";
        $run_ins = db_exec($ins_sql) or errDie("Unable to record blocked period information.");
    } else {
        $upd1_sql = "UPDATE settings SET value = '{$from_year}-{$from_month}-{$from_day}' WHERE constant = 'BLOCKED_FROM'";
        $run_upd1 = db_exec($upd1_sql) or errDie("Unable to update blocked period information.");
    }
    if (!isset($check2) or strlen($check2) < 1) {
        $ins_sql = "\n\t\t\tINSERT INTO settings (\n\t\t\t\tconstant, label, value, type, \n\t\t\t\tdatatype, minlen, maxlen, div, readonly\n\t\t\t) VALUES (\n\t\t\t\t'BLOCKED_TO', 'Blocked Period Date Range To', '{$to_year}-{$to_month}-{$to_day}', 'accounting', \n\t\t\t\t'allstring', '10', '10', '0','f'\n\t\t\t)";
        $run_ins = db_exec($ins_sql) or errDie("Unable to record blocked period information.");
    } else {
        $upd2_sql = "UPDATE settings SET value = '{$to_year}-{$to_month}-{$to_day}' WHERE constant = 'BLOCKED_TO'";
        $run_upd2 = db_exec($upd2_sql) or errDie("Unable to update blocked period information.");
    }
    return get_range("<li class='yay'>Setting has been saved.</li><br>");
}
function get_payprdmsg($payprd, $newval = false)
{
    $dispmsg = getCSetting("EMP_SALMSG");
    $isset = strpos($dispmsg, $payprd);
    if ($newval !== false) {
        /* must be enabled, and setting not in there yet */
        if ($newval == "true" && $isset === false) {
            $dispmsg = "{$dispmsg}{$payprd}";
        } else {
            if ($newval == "false" && $isset !== false) {
                $dispmsg = preg_replace("/{$payprd}/", "", $dispmsg);
            }
        }
        setCSetting("EMP_SALMSG", $dispmsg);
        $isset = strpos($dispmsg, $payprd);
    }
    if ($isset === false) {
        $payprd_msg = "";
    } else {
        switch ($payprd) {
            case "d":
                $payprd_msg = "The first step is for the employer to nominate how many\n\t\t\t\t\tworking hours there are in a week (This is done when adding/editing\n\t\t\t\t\tthe employee). Normally this is 40 hours. In a year there are normally\n\t\t\t\t\t2080 working hours (40 * 52). The system is configured so that the\n\t\t\t\t\tnumber of the working day is identified each time that an employee\n\t\t\t\t\tis paid on a daily basis.<br />\n\t\t\t\t\t<br />\n\t\t\t\t\tEXAMPLE 1: If the employee performs work\n\t\t\t\t\ton 15 March 2007 he will commence working on working day number 11. \n\t\t\t\t\tThe employee year starts 1 March 2007 and ends on 28 February 2008.\n\t\t\t\t\tIn this example there would be 10 previous working days of 8 hours each.\n\t\t\t\t\tThus, working hours are split between prior 10 March 2007 and subsequent\n\t\t\t\t\tto that date: 80 Hours prior and 2000 after 14 March.<br />\n\t\t\t\t\t<br />\n\t\t\t\t\tEXAMPLE 2: An employee's taxable income on 3 July 2007, that is,\n\t\t\t\t\ton working day number 89 is R1200. He has taxable income of R105600 in \n\t\t\t\t\tthe previous 88 days, in respect of which his previous employer has \n\t\t\t\t\tdeducted PAYE amounting in total to R24398. The annual equivalent of \n\t\t\t\t\tR105600 plus a potential 172 days with his new employer would be R312000 \n\t\t\t\t\t(105600 + [172*1200]). Tax on this annual equivalent amounts to R72085. \n\t\t\t\t\tThus in respect of 172 day he would have to pay R47687 - or R277.25 per \n\t\t\t\t\tday. If the employee has no previous employment, that is, it is his first \n\t\t\t\t\tjob, the PAYE deduction on 3 July 2007 would be as follows: Tax on his \n\t\t\t\t\tpotential taxable income of R206400 (1200 * 172 days) from his new employer\n\t\t\t\t\twould be R37305 - or R216.89 per day.";
                break;
            case "w":
                $payprd_msg = "The first step is for the employer to nominate how\n\t\t\t\t\tmany working hours there are in a week (This is done when adding/editing\n\t\t\t\t\tthe employee). Normally this is 40 hours. In a year there are 52 weeks.\n\t\t\t\t\tThe system will identify the week number. Note that the first week in the\n\t\t\t\t\t2008 tax year ends on 2 March 2007.<br />\n\t\t\t\t\t<br />\n\t\t\t\t\tEXAMPLE: If the employee commences work in the week ending 16 March 2007\n\t\t\t\t\the will be working in week number 3.<br />\n\t\t\t\t\tIf his taxable income for the whole week number 3 is R6000, and he has\n\t\t\t\t\tR12000 taxable income in week number 1 and 2 with a former employer who\n\t\t\t\t\tdeducted a total PAYE of R2772.50, it means that he would have earned \n\t\t\t\t\tR18000 during the first 3 weeks. The annual equivalent of this amount \n\t\t\t\t\tis R312000 (R18000 * 52 / 3).<br />\n\t\t\t\t\t<br />\n\t\t\t\t\tThe\ttax payable on R312 000 is R72 085. In week 3 the employee must pay a\n\t\t\t\t\tportion of this amount, 3 / 52, which equals R4158.75. PAYE paid in\n\t\t\t\t\tprior periods, period 1 in this example of R2772.50, must be deducted\n\t\t\t\t\tfrom R4158.75 = R1386.25. PAYE to be deducted in week 3 amounts to R1386.25.";
                break;
            case "f":
                $payprd_msg = "The first step is for the employer to nominate how\n\t\t\t\t\tmany working hours there are in a week (This is done when adding/editing\n\t\t\t\t\tthe employee). Normally this is 40 hours. In a year there are 26 fortnights.\n\t\t\t\t\tThe system will identify the fortnight number. Note that the first \n\t\t\t\t\tfortnight in the 2008 tax year ends on 16 March 2007.<br />\n\t\t\t\t\t<br />\n\t\t\t\t\tEXAMPLE: If the employee commences work in the week ending 16 March 2007\n\t\t\t\t\the will be commencing duties in the second fortnightly period, which ends\n\t\t\t\t\ton 30 March 2007.<br />\n\t\t\t\t\tIf his taxable income for the whole fortnight number 1 was R12000, and he\n\t\t\t\t\thas R12000 taxable income in fortnight number 1 with a former employer who\n\t\t\t\t\tdeducted PAYE of R2772.50, it means that he would have earned R24000 \n\t\t\t\t\tduring the first 2 fortnights. The annual equivalent of R12000 every \n\t\t\t\t\tfortnight amounts to R312000 (R12000 * 26).<br />\n\t\t\t\t\t<br />\n\t\t\t\t\tThe\ttax payable on R312 000 is R72 085. In fortnight number 2 the employee \n\t\t\t\t\tmust pay a portion of this amount, 2 / 26, which equals R5545.00. PAYE paid \n\t\t\t\t\tin prior periods, period 1 in this example of R2772.50, must be deducted\n\t\t\t\t\tfrom R5545.00 = R2772.50. PAYE to be deducted in fortnight number 2 amounts\n\t\t\t\t\tto R2772.50.";
                break;
            case "m":
                $payprd_msg = "Monthly";
        }
    }
    if (!empty($payprd_msg)) {
        $payprd_msg = "<li class='err'>{$payprd_msg}</li>";
    }
    return $payprd_msg;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid purchase number.");
    if (!isset($supid) && !isset($deptid)) {
        $v->isOk($supacc, "num", 1, 10, "Invalid Supplier Account number.");
    }
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            if ($qty > $qts[$keys]) {
                $v->isOk($qty, "num", 0, 0, "Error : Quantity for product number : <b>" . ($keys + 1) . "</b> is more that Qty Purchased");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($pur['pdate']) >= strtotime($blocked_date_from) and strtotime($pur['pdate']) <= 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>";
    }
    $pur['pdate'] = $p_year . "-" . $p_month . "-" . $p_day;
    # Get selected supplier info
    db_connect();
    if (isset($supid)) {
        $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql) or errDie("Unable to get supplier");
        if (pg_numrows($supRslt) < 1) {
            $error = "<li class='err'> Supplier not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $sup = pg_fetch_array($supRslt);
            $pur['supplier'] = $sup['supname'];
            $pur['supaddr'] = $sup['supaddr'];
            # Get department info
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$sup['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $supacc = $dept['credacc'];
        }
    } elseif (isset($deptid)) {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Department not Found.";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = $dept['pca'];
        }
    }
    # check if purchase has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    # Insert purchase to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $refnum = getrefnum();
    /*refnum*/
    db_connect();
    if (isset($qtys)) {
        # amount of stock in
        $totstkamt = array();
        $resub = 0;
        # Get subtotal
        foreach ($qtys as $keys => $value) {
            # Skip zeros
            if ($qtys[$keys] < 1) {
                continue;
            }
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        }
        $SUBTOTAL = array_sum($amt);
        $revat = 0;
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            $sql = "SELECT * FROM nons_pur_items WHERE cod = '{$cod[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # Calculate cost amount bought
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
            /* delivery charge */
            # Calculate percentage from subtotal
            $perc[$keys] = $amt[$keys] / $SUBTOTAL * 100;
            # Get percentage from shipping charges
            $shipc[$keys] = $perc[$keys] / 100 * $shipchrg;
            # add delivery charges
            $amt[$keys] += $shipc[$keys];
            /* end delivery charge */
            # the subtotal + delivery charges
            $resub += $amt[$keys];
            # calculate vat
            $svat[$keys] = svat($amt[$keys], $stkd['amt'], $stkd['svat']);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Vat for Non-Stock Purchase No. {$pur['purnum']}", -$amt[$keys], -$svat[$keys]);
            # received vat
            $revat += $svat[$keys];
            # make amount vat free
            if ($pur['vatinc'] == "yes") {
                $amt[$keys] = $amt[$keys] - $svat[$keys];
            }
            # Update Order items
            $sql = "UPDATE nons_pur_items SET rqty = (rqty + '{$qtys[$keys]}') WHERE cod = '{$cod[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            /* ?: refer to :Code Insert:
            			# keep records for transactions
            			if(isset($totstkamt[$stkacc[$keys]])){
            				$totstkamt[$stkacc[$keys]] += $amt[$keys];
            			}else{
            				$totstkamt[$stkacc[$keys]] = $amt[$keys];
            			}
            			*/
            # check if there are any outstanding items
            $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            # if none the set to received
            if (pg_numrows($stkdRslt) < 1) {
                # update surch_int(received = 'y')
                $sql = "UPDATE nons_purchases SET received = 'y', supplier = '{$pur['supplier']}', supaddr = '{$pur['supaddr']}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF);
            }
        }
    }
    # Update purchase on the DB
    if ($pur['part'] == 'y') {
        # Update purchase on the DB
        $sql = "UPDATE nons_purchases SET shipchrg = (shipchrg + '{$shipchrg}'), refno = '{$refno}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    } else {
        # Update purchase on the DB
        $sql = "UPDATE nons_purchases SET shipchrg = '{$shipchrg}', refno = '{$refno}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    }
    /* Transactions */
    /* - Start Hooks - */
    /* - End Hooks - */
    $detadd = "";
    if (isset($supid)) {
        $detadd = " from Supplier {$sup['supname']}";
    }
    $sdate = $pur['pdate'];
    /* ?:refer to :Code Insert:
    		# record transaction  from data
    		foreach($totstkamt as $stkacc => $wamt){
    			# Debit Stock and Credit Suppliers control
    			writetrans($stkacc, $supacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. $pur[purnum] Received $detadd.");
    			pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. $pur[purnum] Received $detadd.", $wamt, "Cash Purchase");
    		}*/
    # Calc Vat amount on (subtot + delchrg)
    $vatamt = $revat;
    # Add vat if not included
    if ($pur['vatinc'] == 'no') {
        $retot = $resub + $vatamt;
    } elseif ($pur['vatinc'] == "novat") {
        $retot = $resub;
        $vatamt = 0;
    } else {
        $retot = $resub;
    }
    # get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    $tot_post = 0;
    if ($vatamt != 0) {
        $tot_post += $vatamt;
        # Debit bank and credit the account involved
        writetrans($vatacc, $supacc, $pdate, $refnum, $vatamt, "Non-Stock Purchase Vat paid on Non-Stock Purchase No. {$pur['purnum']} {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $vatamt, "Cash Purchase Vat");
        # Record the payment on the statement
        db_connect();
        $sdate = $pur['pdate'];
    }
    if (isset($supid)) {
        $DAte = $pur['pdate'];
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$retot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$sup['supid']}','{$DAte}', '{$dept['credacc']}', '{$retot}','Non-Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}','" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        suppledger($sup['supid'], $wh['stkacc'], $DAte, $pur['purid'], "Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'c');
        db_connect();
        # update the supplier age analysis (make balance less)
        /* Make transaction record for age analysis */
        $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, div) VALUES('{$sup['supid']}', '{$pur['purnum']}', '{$DAte}', '{$retot}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    /* End Transactions */
    # commit updating
    // pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    /* Update items found in ther linked purchase */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    db_conn($pur['spurprd']);
    $stab = $pur['spurtype'] == "int" ? "purch_int" : "purchases";
    $itab = $pur['spurtype'] == "int" ? "purint_items" : "pur_items";
    # Get purchase info
    $sql = "SELECT * FROM {$stab} WHERE purnum = '{$pur['spurnum']}' AND div = '" . USER_DIV . "'";
    $spurRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($spurRslt) < 1) {
        return "<li> - purchase Not Found</li>";
    }
    $spur = pg_fetch_array($spurRslt);
    $purs = explode(",", $pur['purs']);
    $TSUB = 0;
    foreach ($purs as $purID) {
        $purID += 0;
        db_connect();
        $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $p = pg_fetch_array($srchRslt);
            $TSUB += $p['subtot'];
            $Sl = "SELECT sum(unitcost) -sum(svat) as non FROM pur_items WHERE purid='{$p['purid']}' AND stkid=0";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $pi = pg_fetch_array($Ri);
            $pi = $pi['non'];
        }
        $sql = "SELECT * FROM movpurch WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $res = pg_fetch_array($srchRslt);
            db_conn($res['prd']);
            $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
            $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
            if (pg_numrows($srchRslt) > 0) {
                $p = pg_fetch_array($srchRslt);
                $TSUB += $p['subtot'];
                $Sl = "SELECT sum(unitcost)-sum(svat) as non FROM pur_items WHERE purid='{$p['purid']}' AND stkid=0";
                $Ri = db_exec($Sl) or errDie("Unable to get data.");
                $pi = pg_fetch_array($Ri);
                $pi = $pi['non'];
            } else {
                db_conn($res['prd']);
                $sql = "SELECT * FROM purch_int WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
                $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
                if (pg_numrows($srchRslt) > 0) {
                    $p = pg_fetch_array($srchRslt);
                    $TSUB += $p['subtot'];
                    // 					$Sl="SELECT sum(unitcost)-sum(svat) as non FROM purint_items WHERE purid='$p[purid]' AND stkid=0";
                    //
                    // 					$Ri=db_exec($Sl) or errDie("Unable to get data.");
                    // 					$pi=pg_fetch_array($Ri);
                    // 					$pi=$pi['non'];
                    $pi = 0;
                }
            }
        }
        if (!isset($pi)) {
            $pi = 0;
        }
        $TSUB -= $pi;
    }
    $purs = explode(",", $pur['purs']);
    foreach ($purs as $purID) {
        $itab = "pur_items";
        $purID += 0;
        //print $purID;
        db_connect();
        $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $pur['spurprd'] = "cubit";
        }
        $sql = "SELECT * FROM movpurch WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $res = pg_fetch_array($srchRslt);
            db_conn($res['prd']);
            $pur['spurprd'] = $res['prd'];
        }
        db_conn($pur['spurprd']);
        $test = $pur['spurprd'];
        $test += 0;
        if ($test != 0) {
            $s = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
            $q = db_exec($s) or errDie("Unable to retrieve purchases from database.");
            if (pg_num_rows($q) > 0) {
                $p = pg_fetch_array($q);
                $purID = $p['purid'];
            } else {
                $s = "SELECT * FROM purch_int WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
                $q = db_exec($s) or errDie("Unable to retrieve purchases from database.");
                if (pg_num_rows($q) > 0) {
                    $p = pg_fetch_array($q);
                    $purID = $p['purid'];
                    $itab = "purint_items";
                }
            }
        }
        # Get selected stock
        $sql = "SELECT * FROM {$itab} WHERE purid = '{$purID}' AND div = '" . USER_DIV . "' AND stkid!=0";
        $sstkdRslt = db_exec($sql);
        while ($sstk = pg_fetch_array($sstkdRslt)) {
            if ($pur['spurtype'] == "int") {
                $csamt = sprint($sstk['amt'] / $TSUB * ($retot - $vatamt));
            } else {
                if ($spur['vatinc'] == "yes") {
                    $csamt = sprint(($sstk['amt'] - $sstk['svat']) / $TSUB * ($retot - $vatamt));
                } else {
                    $csamt = sprint($sstk['amt'] / $TSUB * ($retot - $vatamt));
                }
            }
            db_connect();
            # get selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            /* Code insert */
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT * FROM warehouses WHERE whid = '{$stkt['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $tot_post += $csamt;
            writetrans($wh['stkacc'], $supacc, $pdate, $refnum, $csamt, "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.");
            /* End code insert */
            db_connect();
            if ($stkt['units'] != 0) {
                $sql = "UPDATE stock SET csamt = (csamt + '{$csamt}'), csprice = (csamt/units) WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            } else {
                $sql = "UPDATE stock SET csamt = (csamt + '{$csamt}') WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            $sdate = $pur['pdate'];
            stockrec($stkt['stkid'], $stkt['stkcod'], $stkt['stkdes'], 'dt', $sdate, 0, $csamt, "Cost Increased with Non Stock Purchase No. {$pur['purnum']}");
            # get selected stock
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            # $csprice = round(($stk['csamt']/$stk['units']), 2);
            if ($stkt['units'] > 0) {
                $csprice = round($stkt['csamt'] / $stkt['units'], 2);
            } else {
                $csprice = round($stkt['csprice'], 2);
            }
            # update stock(csprice = (csamt/units))
            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        }
    }
    //exit;
    /*
    		db_conn($pur['spurprd']);
    		# Get selected stock
    		$sql = "SELECT * FROM $itab WHERE purid = '$spur[purid]' AND div = '".USER_DIV."' AND stkid!=0";
    		$sstkdRslt = db_exec($sql);
    		while($sstk = pg_fetch_array($sstkdRslt)){
    			if($pur['spurtype'] == "int"){
    				$csamt = sprint(($sstk['amt']/$TSUB) * ($retot - $vatamt));
    			}else{
    				if($spur['vatinc'] == "yes"){
    					$csamt = sprint((($sstk['amt'] - $sstk['svat'])/$TSUB) * ($retot - $vatamt));
    				}else{
    					$csamt = sprint((($sstk['amt'])/$TSUB) * ($retot - $vatamt));
    				}
    			}
    
    			db_connect();
    			# get selected stock
    			$sql = "SELECT * FROM stock WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$stktRslt = db_exec($sql);
    			$stkt = pg_fetch_array($stktRslt);
    
    			/* Code insert
    				# get warehouse name
    				db_conn("exten");
    				$sql = "SELECT * FROM warehouses WHERE whid = '$stkt[whid]' AND div = '".USER_DIV."'";
    				$whRslt = db_exec($sql);
    				$wh = pg_fetch_array($whRslt);
    
    				$tot_post+=$csamt;
    
    				writetrans($wh['stkacc'], $supacc, date("d-m-Y"), $refnum, $csamt, "Non-Stock Purchase No. $pur[purnum] Received $detadd.");
    			/* End code insert
    
    			db_connect();
    			if($stkt['units'] <> 0){
    				$sql = "UPDATE stock SET csamt = (csamt + '$csamt'), csprice = (csamt/units) WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    				$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    			}else{
    				$sql = "UPDATE stock SET csamt = (csamt + '$csamt') WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    				$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    			}
    			$sdate = $pur['pdate'];
    			stockrec($stkt['stkid'], $stkt['stkcod'], $stkt['stkdes'], 'dt', $sdate, 0, $csamt, "Cost Increased with Non Stock Purchase No. $pur[purnum]");
    
    			# get selected stock
    			db_connect();
    			$sql = "SELECT * FROM stock WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$stktRslt = db_exec($sql);
    			$stkt = pg_fetch_array($stktRslt);
    
    			# $csprice = round(($stk['csamt']/$stk['units']), 2);
    			if($stkt['units'] > 0){
    				$csprice = round(($stkt['csamt']/$stkt['units']), 2);
    			}else{
    				$csprice = round($stkt['csprice'], 2);
    			}
    
    			# update stock(csprice = (csamt/units))
    			$sql = "UPDATE stock SET csprice = '$csprice' WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    		}
    */
    $diff = sprint($retot - $tot_post);
    if ($diff > 0) {
        writetrans($cvacc, $supacc, $sdate, $refnum, $diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']}");
    } elseif ($diff < 0) {
        writetrans($supacc, $cvacc, $sdate, $refnum, -$diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']}");
    }
    /* End Update items found in ther linked purchase */
    /* Start moving if purchase received */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        if (isset($supid)) {
            $ctyp = "sup";
            $typeid = $supid;
        } elseif (isset($deptid)) {
            $ctyp = "led";
            $typeid = $deptid;
        } else {
            $ctyp = "ot";
            $typeid = 0;
        }
        # copy purchase
        db_conn($pur['prd']);
        $pur['spurprd'] += 0;
        $pur['spurnum'] += 0;
        $sql = "INSERT INTO nons_purchases(purid, deptid, supplier, supaddr, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, remarks, refno, received, done, div, purnum,ctyp,typeid,spurprd,spurnum)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}','{$ctyp}','{$typeid}','{$pur['spurprd']}','{$pur['spurnum']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Purchase to Cubit.", SELF);
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert purchase items
            db_conn($pur['prd']);
            $sql = "INSERT INTO nons_pur_items(purid, cod, des, qty, unitcost, amt, ddate, div,svat) VALUES('{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['ddate']}', '" . USER_DIV . "','{$stktc['svat']}')";
            $rslt = db_exec($sql) or errDie("Unable to insert purchase items to Cubit.", SELF);
        }
        db_connect();
        # Remove the purchase from running DB
        $sql = "DELETE FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Remove those purchase items from running DB
        $sql = "DELETE FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving purchase received */
    $cc = "<script> CostCenter('ct', 'Non-Stock Purchase', '{$pdate}', 'Non Stock Purchase No.{$pur['purnum']}', '" . ($retot - $vatamt) . "', ''); </script>";
    // Final Layout
    $write = "\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Non-Stock Purchase received</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>Non-Stock Purchase receipt has been recorded.</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='nons-purchase-view.php'>View purchases</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t</table>";
    return $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 send_email_groups($_POST)
{
    extract($_POST);
    if (!isset($sendgroups) or !is_array($sendgroups)) {
        return show_email_groups("<li class='err'>Please Select At Least 1 Email Batch To Send.</li><br>");
    }
    db_connect();
    $sendgroup = "";
    $listing = "";
    $groupcounter = 0;
    $ran = TRUE;
    foreach ($sendgroups as $groupname) {
        $ran2 = TRUE;
        $sendgroup .= "&sendgroups[]={$groupname}";
        $listing .= "\n\t\t\t<tr>\n\t\t\t\t<td><h3>{$groupname}</h3></td>\n\t\t\t</tr>";
        #determine how many have been sent
        $get_sent = "SELECT count(id) FROM email_queue WHERE groupname = '{$groupname}' AND status = 'sent'";
        $run_sent = db_exec($get_sent) or errDie("Unable to get sent email information.");
        if (pg_numrows($run_sent) < 1) {
            $sent_items = 0;
        } else {
            $sent_items = pg_fetch_result($run_sent, 0, 0);
        }
        $get_sent = "SELECT count(id) FROM email_queue WHERE groupname = '{$groupname}' AND status = 'failed' AND status2 = 'active'";
        $run_sent = db_exec($get_sent) or errDie("Unable to get sent email information.");
        if (pg_numrows($run_sent) < 1) {
            $unsent_items = 0;
        } else {
            $unsent_items = pg_fetch_result($run_sent, 0, 0);
        }
        $listing .= "\n\t\t\t<tr>\n\t\t\t\t<th>{$sent_items} Emails Have Been Sent</th>\n\t\t\t\t<th colspan='3'>{$unsent_items} Emails Remain</th>\n\t\t\t</tr>";
        #get list of 5 queue items to display
        $get_list = "SELECT * FROM email_queue WHERE groupname = '{$groupname}' AND status = 'failed' AND status2 = 'active' OFFSET {$groupcounter} LIMIT 10";
        $run_list = db_exec($get_list) or errDie("Unable to get list of emails to be sent.");
        if (pg_numrows($run_list) < 1) {
            //			$listing .= "
            //				<tr class='".bg_class()."'>
            //					<td colspan='2'>All Emails Have Been Sent.</td>
            //				</tr>
            //				".TBL_BR;
            //			return show_email_groups("<li class='err'>Requested Email(s) Have Been Sent.</li><br>");
            print "\n\t\t\t\t\t<script>\n\t\t\t\t\t\tdocument.location='email-queue-manage.php';\n\t\t\t\t\t</script>";
        } else {
            $listing .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Email Address</th>\n\t\t\t\t\t<th>Subject</th>\n\t\t\t\t\t<th>Date Added</th>\n\t\t\t\t\t<th>Status</th>\n\t\t\t\t</tr>";
            while ($larr = pg_fetch_array($run_list)) {
                if ($ran && $ran2) {
                    $larr['status'] = "Sending";
                    $ran2 = FALSE;
                } else {
                    $larr['status'] = "Queued";
                }
                $listing .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>{$larr['emailaddress']}</td>\n\t\t\t\t\t\t<td>{$larr['subject']}</td>\n\t\t\t\t\t\t<td>{$larr['date_added']}</td>\n\t\t\t\t\t\t<td>{$larr['status']}</td>\n\t\t\t\t\t</tr>";
            }
        }
        //		$count = 0;
        #only update 1 email message
        $get_emails = "SELECT * FROM email_queue WHERE groupname = '{$groupname}' AND status = 'failed' AND status2 = 'active' ORDER BY id LIMIT 1";
        $run_emails = db_exec($get_emails) or errDie("Unable to get group information.");
        while ($larr = pg_fetch_array($run_emails)) {
            if ($ran) {
                $bodydata = $larr['message'];
                $subject = $larr['subject'];
                $es = qryEmailSettings();
                $body = $bodydata;
                #generate removal tail code
                $tail = "<br><br> \n\nIf you would like to stop receiving these emails, please leave the following link intact, and reply to this email.\n<a href='http://" . $_SERVER['SERVER_ADDR'] . "/unsub-email.php?email={$larr['emailaddress']}'>http://" . $_SERVER['SERVER_ADDR'] . "/unsub-email.php?email={$larr['emailaddress']}</a>";
                if ($larr['send_format'] != "html") {
                    $tail = strip_tags($tail);
                }
                $body = $body . $tail;
                $send_cc = "";
                $send_bcc = "";
                $smtp_data['signature'] = $es['sig'];
                $smtp_data['smtp_from'] = getCSetting("MARKET_MAIL_FROM");
                //$es['fromname'];
                $smtp_data['smtp_reply'] = $es['reply'];
                $smtp_data['smtp_host'] = $es['smtp_host'];
                $smtp_data['smtp_auth'] = $es['smtp_auth'];
                $smtp_data['smtp_user'] = $es['smtp_user'];
                $smtp_data['smtp_pass'] = $es['smtp_pass'];
                // build msg body
                $body = "{$body}\n\n{$smtp_data['signature']}";
                // determine whether or not here is an attachment
                //$has_attachment = is_uploaded_file($attachment["tmp_name"]);
                if ($larr['attachment'] != 0) {
                    $has_attachment = TRUE;
                } else {
                    $has_attachment = false;
                }
                //				$has_attachment = false;
                // modify message and create content_type header depending on whether or not an attachment was posted
                if ($has_attachment == false) {
                    $content_type = "text/{$larr['send_format']};charset=US-ASCII";
                    $transfer_encoding = "8bit";
                } else {
                    // has attachment
                    $get_attach = "SELECT * FROM email_attachments WHERE id = '{$larr['attachment']}' LIMIT 1";
                    $run_attach = db_exec($get_attach) or errDie("Unable to get email attachment information.");
                    if (pg_numrows($run_attach) < 1) {
                        return "Email attachment not found.";
                    }
                    $aarr = pg_fetch_array($run_attach);
                    $content_type = "multipart/mixed";
                    // create the main body
                    $body_text = "Content-Type: text/{$larr['send_format']}; charset=US-ASCII\n";
                    $body_text .= "Content-Transfer-Encoding: base64\n";
                    $body_text .= "\n" . chunk_split(base64_encode($body));
                    // get the attachment data
                    $attachment = array();
                    //					$attachment["data"] = state($id,$fromdate,$todate,$type);
                    $attachment["name"] = $aarr['attach_filename'];
                    //"statement.pdf";
                    // delete the temporary file
                    $attachment["data"] = chunk_split($aarr["attach_data"]);
                    //chunk_split(base64_encode($attachment["data"]));
                    $attachment["headers"] = "Content-Type: {$aarr['attach_mime']}; name=\"{$attachment['name']}\"\n";
                    $attachment["headers"] .= "Content-Transfer-Encoding: base64\n";
                    $attachment["headers"] .= "Content-Disposition: attachment; filename=\"{$attachment['name']}\"\n";
                    $attachment["data"] = "{$attachment['headers']}\n{$attachment['data']}";
                    // generate a unique boundary ( md5 of filename + ":=" + filesize )
                    $boundary = md5($attachment["name"]) . "=:" . strlen($attachment["data"]);
                    $content_type .= "; boundary=\"{$boundary}\"";
                    // put together the body
                    $body = "\n--{$boundary}\n{$body_text}\n\n--{$boundary}\n{$attachment['data']}\n\n--{$boundary}--\n";
                }
                // build headers
                $headers = array();
                $headers[] = "From: " . getCSetting("MARKET_MAIL_FROM");
                //$smtp_data[smtp_from]";
                $headers[] = "To: {$larr['emailaddress']}";
                $headers[] = "Reply-To: " . getCSetting("MARKET_MAIL_FROM");
                //$smtp_data[smtp_reply]";
                $headers[] = "X-Mailer: Cubit Mail";
                $headers[] = "Return-Path: " . getCSetting("MARKET_MAIL_FROM");
                //$smtp_data[smtp_reply]";
                $headers[] = "Content-Type: {$content_type}";
                $headers[] = "cc: {$send_cc}";
                $headers[] = "bcc: {$send_bcc}";
                // create the mime header if should
                if ($has_attachment == TRUE) {
                    $headers[] = "MIME-Version: 1.0";
                }
                // create the header variable (it is done this way, to make management of headers easier, since there
                // may be no tabs and unnecesary whitespace in mail headers)
                //$headers[] = "\n"; // add another new line to finish the headers
                $headers = implode("\n", $headers);
                //return "done";
                // send the message
                $sendmail =& new clsSMTPMail();
                $OUTPUT = $sendmail->sendMessages($smtp_data["smtp_host"], 25, $smtp_data["smtp_auth"], $smtp_data["smtp_user"], $smtp_data["smtp_pass"], $larr['emailaddress'], $smtp_data["smtp_from"], "{$subject}", $body, $headers);
                if ($sendmail->bool_success) {
                    #email system reports success!
                    #update this entry ..
                    $upd_sql = "UPDATE email_queue SET status = 'sent' WHERE id = '{$larr['id']}'";
                    $run_upd = db_exec($upd_sql) or errDie("Unable to update email queue information.");
                    $ran = FALSE;
                } else {
                    #problem sending mail ...
                    #if email system reports network problem, loop, else mark ...
                    $upd_sql = "UPDATE email_queue SET status = 'failed', status2 = 'failed', failed_reason = '{$OUTPUT}' WHERE id = '{$larr['id']}'";
                    $run_upd = db_exec($upd_sql) or errDie("Unable to update email queue information.");
                    $ran = FALSE;
                }
            }
            //			$count++;
        }
        //		print "group sent ...";
    }
    $display = "\n\t\t\t\t\t<script>\n\t\t\t\t\t\twindow.setTimeout(' window.location=\"email-queue-failures.php?key=confirm{$sendgroup}\"; ',3000);\n\t\t\t\t\t</script>\n\t\t\t\t\t<h2>Email Management</h2>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t{$listing}\n\t\t\t\t\t</table>\n\t\t\t\t";
    return $display;
}
function confirm_setting_info($_POST)
{
    extract($_POST);
    if (!isset($show_account) or !is_array($show_account)) {
        return get_setting_info($_POST, "<li class='err'>Please Select At Least 1 Account To Display.</li><br>");
    }
    if (!isset($vatacc)) {
        $vatacc = 0;
    }
    db_connect();
    #clear old entries
    $rem_sql = "DELETE FROM credit_note_accounts";
    $run_rem = db_exec($rem_sql) or errDie("Unable to get credit note accounts information.");
    foreach ($show_account as $each => $own) {
        $add_sql = "INSERT INTO credit_note_accounts (accid) VALUES ({$each})";
        $run_add = db_exec($add_sql) or errDie("Unable to get credit note account information.");
    }
    #update vat account to use
    $check_vatacc = getCSetting("CRED_NOTE_VAT_ACC");
    if (!isset($check_vatacc) or strlen($check_vatacc) < 1) {
        #no previous setting ... insert
        $ins_sql = "\n\t\t\tINSERT INTO cubit.settings (\n\t\t\t\tconstant, label, value, type, datatype, \n\t\t\t\tminlen, maxlen, div, readonly\n\t\t\t) VALUES (\n\t\t\t\t'CRED_NOTE_VAT_ACC', 'Credit Note VAT Account', '{$vatacc}', 'general', 'allstring', \n\t\t\t\t'1', '10', '0', 'f'\n\t\t\t)";
        $run_ins = db_exec($ins_sql) or errDie("Unable to record vat account setting.");
    } else {
        #exists ... update
        $upd_sql = "UPDATE settings SET value = '{$vatacc}' WHERE constant = 'CRED_NOTE_VAT_ACC'";
        $run_upd = db_exec($upd_sql) or errDie("Unable to update vat account setting.");
    }
    //	return get_setting_info($_POST, "<li class='err'>Account Settings Updated.</li><br>");
    header("Location: ../general-creditnote.php");
}
function confirm($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $date = $date_year . "-" . $date_month . "-" . $date_day;
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    $v->isOk($account, "num", 1, 50, "Invalid Account to be used as contra.[{$key}]");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= 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>";
    }
    foreach ($accid as $key => $value) {
        $dtamount[$key] += 0;
        $ctamount[$key] += 0;
        if ($dtamount[$key] > 0 || $ctamount[$key] > 0) {
            $v->isOk($accid[$key], "num", 1, 50, "Invalid Account to be Debited.[{$key}]");
            $v->isOk($dtamount[$key], "float", 1, 20, "Invalid Debit Amount.[{$key}]");
            $v->isOk($ctamount[$key], "float", 1, 20, "Invalid Credit Amount.[{$key}]");
            $v->isOk($descript[$key], "string", 0, 255, "Invalid Details.[{$key}]");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # get contra account
    $accRs = get("core", "*", "accounts", "accid", $account);
    if (pg_numrows($accRs) < 1) {
        return "<li> Accounts to be debited does not exist.</li>";
    }
    $account_info = pg_fetch_array($accRs);
    # accnums
    foreach ($accid as $key => $value) {
        if ($dtamount[$key] > 0 || $ctamount[$key] > 0) {
            # get account to be debited
            $accRss = get("core", "*", "accounts", "accid", $accid[$key]);
            if (pg_numrows($accRs) < 1) {
                return "<li> Accounts to be debited does not exist.</li>";
            }
            $accs[$key] = pg_fetch_array($accRss);
        }
    }
    $confirm = "\n\t\t<center>\n\t\t<h3>Add Multiple Journal transactions to batch</h3>\n\t\t<h4>Confirm entry</h4>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='date_year' value='{$date_year}'>\n\t\t\t<input type='hidden' name='date_month' value='{$date_month}'>\n\t\t\t<input type='hidden' name='date_day' value='{$date_day}'>\n\t\t\t<input type='hidden' name='refnum' value='{$refnum}'>\n\t\t\t<input type='hidden' name='account' value='{$account}'>\n\t\t\t<input type='hidden' name='total' value='{$total}'>\n\t\t\t<input type='hidden' name='key' value='write'>\n\t\t<table " . TMPL_tblDflts . " width='590'>\n\t\t\t<tr>\n\t\t\t\t<th>Transaction Date</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$date_year}-{$date_month}-{$date_day}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Select Contra Account</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$account_info['accname']}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Reference Number</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$refnum}</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t</table>\n\t\t<table " . TMPL_tblDflts . " width='590'>\n\t\t\t<tr>\n\t\t\t\t<th>Account</th>\n\t\t\t\t<th>Description</th>\n\t\t\t\t<th>Debit</th>\n\t\t\t\t<th>Credit</th>\n\t\t\t</tr>";
    $trans = "";
    foreach ($accid as $key => $value) {
        if ($dtamount[$key] > 0 || $ctamount[$key] > 0) {
            $accRss = get("core", "*", "accounts", "accid", $accid[$key]);
            if (pg_numrows($accRs) < 1) {
                return "<li> Accounts to be debited does not exist.</li>";
            }
            $acc_each[$key] = pg_fetch_array($accRss);
            $trans .= "\n\t\t\t\t<input type='hidden' name='accid[]' value='{$accid[$key]}'>\n\t\t\t\t<input type='hidden' name='descript[]' value ='{$descript[$key]}'>\n\t\t\t\t<input type='hidden' name='dtamount[]' value='{$dtamount[$key]}'>\n\t\t\t\t<input type='hidden' name='ctamount[]' value='{$ctamount[$key]}'>\n\t\t\t\t<tr bgcolor=" . bgcolorg() . ">\n\t\t\t\t\t<td valign='center'>" . $acc_each[$key]['accname'] . "</td>\n\t\t\t\t\t<td>{$descript[$key]}</td>\n\t\t\t\t\t<td nowrap>" . CUR . " " . sprint($dtamount[$key]) . "</td>\n\t\t\t\t\t<td nowrap>" . CUR . " " . sprint($ctamount[$key]) . "</td>\n\t\t\t\t</tr>";
        }
    }
    if (strlen($trans) < 5) {
        return slctacc($_POST, "<li class='err'>Please enter full transaction details</li><br>");
    }
    $confirm .= "\n\t\t\t{$trans}\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t\t<td align='right' colspan='3'><input type='submit' value='Write &raquo'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>\n\t\t<table border='0' cellpadding='2' cellspacing='1' width=15%>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td align='center'><a href='../reporting/index-reports.php'>Financials</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td align='center'><a href='batch-view.php'>View batch file</td>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td align='center'><a href='trans-new.php'>Journal Transaction</td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $confirm;
}
function recipe()
{
    extract($_REQUEST);
    $fields = array();
    $fields["m_stock_id"] = 0;
    $fields["filter_store"] = 0;
    $fields["filter_class"] = 0;
    $fields["filter_cat"] = 0;
    $fields["each_filter_store"] = 0;
    $fields["each_filter_class"] = 0;
    $fields["each_filter_cat"] = 0;
    $fields["search_string"] = "";
    $fields["each_search_string"] = "";
    extract($fields, EXTR_SKIP);
    $check_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
    if (isset($check_setting) and $check_setting == "yes") {
        if (isset($filter_class) and $filter_class != "0") {
            $Wh .= " AND prdcls = '{$filter_class}'";
        }
        if (isset($filter_cat) and $filter_cat != "0") {
            $Wh .= " AND catid = '{$filter_cat}'";
        }
    }
    if (isset($filter_store) and $filter_store != "0") {
        $Wh .= " AND stock.whid = '{$filter_store}'";
    }
    if (isset($search) or isset($m_stock_id) and $m_stock_id > 0) {
        $dosearch = "TRUE";
    } else {
        $dosearch = "FALSE";
    }
    // Create the main stock item dropdown
    $sql = "\n\t\tSELECT stkid, stkcod, stkdes, whname\n\t\tFROM cubit.stock\n\t\t\tLEFT JOIN exten.warehouses ON stock.whid=warehouses.whid\n\t\tWHERE {$dosearch} {$Wh} AND (stkcod ILIKE '%{$search_string}%' OR stkdes = '%{$search_string}%') \n\t\tORDER BY stkcod ASC";
    $m_stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
    $m_stock_sel = "<select name='m_stock_id' onchange='javascript:document.form.submit()' style='width: 100%'>";
    $m_stock_sel .= "<option value='0'>[None / Display All Stores]</option>";
    while ($m_stock_data = pg_fetch_array($m_stock_rslt)) {
        if ($m_stock_id == $m_stock_data["stkid"]) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $m_stock_sel .= "\n\t\t\t<option value='{$m_stock_data['stkid']}' {$sel}>\n\t\t\t\t({$m_stock_data['whname']}) ({$m_stock_data['stkcod']}) {$m_stock_data['stkdes']}\n\t\t\t</option>";
    }
    $m_stock_sel .= "</select>";
    // Just a dummy message to make the user feel good about his/herself :)
    if (isset($save) && $save) {
        $msg = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='3'><li>The recipe has been successfully saved.</li></td>\n\t\t\t</tr>";
    } else {
        $msg = "";
    }
    $optional_filter_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
    if (isset($optional_filter_setting) and $optional_filter_setting == "yes") {
        db_connect();
        $catsql = "SELECT catid, cat, catcod FROM stockcat WHERE div = '" . USER_DIV . "' ORDER BY cat ASC";
        $catRslt = db_exec($catsql);
        if (pg_numrows($catRslt) < 1) {
            $cat_drop = "<input type='hidden' name='filter_cat' value='0'>";
        } else {
            $cat_drop = "<select name='filter_cat'>";
            $cat_drop .= "<option value='0'>All Categories</option>";
            while ($cat = pg_fetch_array($catRslt)) {
                if (isset($filter_cat) and $filter_cat == $cat['catid']) {
                    $cat_drop .= "<option value='{$cat['catid']}' selected>({$cat['catcod']}) {$cat['cat']}</option>";
                } else {
                    $cat_drop .= "<option value='{$cat['catid']}'>({$cat['catcod']}) {$cat['cat']}</option>";
                }
            }
            $cat_drop .= "</select>";
        }
        # Select classification
        $classsql = "SELECT * FROM stockclass WHERE div = '" . USER_DIV . "' ORDER BY classname ASC";
        $clasRslt = db_exec($classsql);
        if (pg_numrows($clasRslt) < 1) {
            $class_drop = "<input type='hidden' name='filter_class' value='0'>";
        } else {
            $class_drop = "<select name='filter_class' style='width: 167'>";
            $class_drop .= "<option value='0'>All Classifications</option>";
            while ($clas = pg_fetch_array($clasRslt)) {
                if (isset($filter_class) and $filter_class == $clas['clasid']) {
                    $class_drop .= "<option value='{$clas['clasid']}' selected>{$clas['classname']}</option>";
                } else {
                    $class_drop .= "<option value='{$clas['clasid']}'>{$clas['classname']}</option>";
                }
            }
            $class_drop .= "</select>";
        }
        $display_optional_filters = "\n\t\t\t<tr>\n\t\t\t\t<th>Select Category</th>\n\t\t\t\t<th>Select Classification</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'>{$cat_drop}</td>\n\t\t\t\t<td align='center'>{$class_drop}</td>\n\t\t\t</tr>";
    }
    db_conn("exten");
    $sql = "SELECT whid, whname, whno FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
    $whRslt = db_exec($sql);
    if (pg_numrows($whRslt) < 1) {
        $store_drop = "<input type='hidden' name='filter_store' value='0'>";
    } else {
        if (!isset($filter_store)) {
            # check if setting exists
            db_connect();
            $sql = "SELECT value FROM set WHERE label = 'DEF_WH' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to check database for existing settings.");
            if (pg_numrows($Rslt) > 0) {
                $set = pg_fetch_array($Rslt);
                $whid = $set['value'];
            }
        }
        $store_drop = "<select name='filter_store'>";
        $store_drop .= "<option value='0'>All Stores</option>";
        while ($wh = pg_fetch_array($whRslt)) {
            if (isset($filter_store) and $filter_store == $wh['whid']) {
                $store_drop .= "<option value='{$wh['whid']}' selected>({$wh['whno']}) {$wh['whname']}</option>";
            } else {
                $store_drop .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
            }
        }
        $store_drop .= "</select>";
    }
    $OUTPUT = "\n\t\t<center>\n\t\t<h3>Create Recipe</h3>\n\t\t<form method='POST' action='" . SELF . "' name='form'>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t{$msg}\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Search Stock</th>\n\t\t\t</tr>\n\t\t\t{$display_optional_filters}\n\t\t\t<tr>\n\t\t\t\t<th>Store</th>\n\t\t\t\t<th>Search Code/Description</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'>{$store_drop}</td>\n\t\t\t\t<td align='center'><input type='text' name='search_string' value='{$search_string}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center' colspan='2'><input type='submit' name='search' value='Search'></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th colspan='4'>Stock Item</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='4'>{$m_stock_sel}</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>\n\t\t<table " . TMPL_tblDflts . ">";
    if ($m_stock_id) {
        $check_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
        if (isset($check_setting) and $check_setting == "yes") {
            db_connect();
            $catsql = "SELECT catid, cat, catcod FROM stockcat WHERE div = '" . USER_DIV . "' ORDER BY cat ASC";
            $catRslt = db_exec($catsql);
            if (pg_numrows($catRslt) < 1) {
                $each_cat_drop = "<input type='hidden' name='each_filter_cat' value='0'>";
            } else {
                $each_cat_drop = "<select name='each_filter_cat'>";
                $each_cat_drop .= "<option value='0'>All Categories</option>";
                while ($cat = pg_fetch_array($catRslt)) {
                    if (isset($each_filter_cat) and $each_filter_cat == $cat['catid']) {
                        $each_cat_drop .= "<option value='{$cat['catid']}' selected>({$cat['catcod']}) {$cat['cat']}</option>";
                    } else {
                        $each_cat_drop .= "<option value='{$cat['catid']}'>({$cat['catcod']}) {$cat['cat']}</option>";
                    }
                }
                $each_cat_drop .= "</select>";
            }
            # Select classification
            $classsql = "SELECT * FROM stockclass WHERE div = '" . USER_DIV . "' ORDER BY classname ASC";
            $clasRslt = db_exec($classsql);
            if (pg_numrows($clasRslt) < 1) {
                $each_class_drop = "<input type='hidden' name='each_filter_class' value='0'>";
            } else {
                $each_class_drop = "<select name='each_filter_class' style='width: 167'>";
                $each_class_drop .= "<option value='0'>All Classifications</option>";
                while ($clas = pg_fetch_array($clasRslt)) {
                    if (isset($each_filter_class) and $each_filter_class == $clas['clasid']) {
                        $each_class_drop .= "<option value='{$clas['clasid']}' selected>{$clas['classname']}</option>";
                    } else {
                        $each_class_drop .= "<option value='{$clas['clasid']}'>{$clas['classname']}</option>";
                    }
                }
                $each_class_drop .= "</select>";
            }
            $display_optional_filters_each1 = "\n\t\t\t\t<th>Select Category</th>\n\t\t\t\t<th>Select Classification</th>";
            $display_optional_filters_each2 = "\n\t\t\t\t<td align='center'>{$each_cat_drop}</td>\n\t\t\t\t<td align='center'>{$each_class_drop}</td>";
        }
        db_conn("exten");
        $sql = "SELECT whid, whname, whno FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
        $whRslt = db_exec($sql);
        if (pg_numrows($whRslt) < 1) {
            $store_drop = "<input type='hidden' name='filter_store' value='0'>";
        } else {
            if (!isset($filter_store)) {
                # check if setting exists
                db_connect();
                $sql = "SELECT value FROM set WHERE label = 'DEF_WH' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to check database for existing settings.");
                if (pg_numrows($Rslt) > 0) {
                    $set = pg_fetch_array($Rslt);
                    $whid = $set['value'];
                }
            }
            $each_store_drop = "<select name='each_filter_store'>";
            $each_store_drop .= "<option value='0'>All Stores</option>";
            while ($wh = pg_fetch_array($whRslt)) {
                if (isset($each_filter_store) and $each_filter_store == $wh['whid']) {
                    $each_store_drop .= "<option value='{$wh['whid']}' selected>({$wh['whno']}) {$wh['whname']}</option>";
                } else {
                    $each_store_drop .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
                }
            }
            $each_store_drop .= "</select>";
        }
        if (isset($check_setting) and $check_setting == "yes") {
            if (isset($each_filter_class) and $each_filter_class != "0") {
                $Wh2 .= " AND prdcls = '{$each_filter_class}'";
            }
            if (isset($each_filter_cat) and $each_filter_cat != "0") {
                $Wh2 .= " AND catid = '{$each_filter_cat}'";
            }
        }
        if (isset($each_filter_store) and $each_filter_store != "0") {
            $Wh2 .= " AND stock.whid = '{$each_filter_store}'";
        }
        if (isset($search_each)) {
            $do_each = "TRUE";
        } else {
            $do_each = "FALSE";
        }
        // Create the stock dropdown
        $sql = "\n\t\t\tSELECT stkid, stkcod, stkdes \n\t\t\tFROM cubit.stock \n\t\t\tWHERE \n\t\t\t\t{$do_each} AND stkid!='{$m_stock_id}' {$Wh2} AND \n\t\t\t\t(stkcod ILIKE '%{$each_search_string}%' OR stkdes ILIKE '%{$each_search_string}%') \n\t\t\tORDER BY stkcod ASC";
        $s_stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
        $s_stock_sel = "<select name='s_stock_id' style='width: 100%'>";
        $s_stock_sel .= "<option value='0'>[None]</option>";
        while ($s_stock_data = pg_fetch_array($s_stock_rslt)) {
            $s_stock_sel .= "\n\t\t\t\t<option value='{$s_stock_data['stkid']}'>\n\t\t\t\t\t({$s_stock_data['stkcod']}) {$s_stock_data['stkdes']}\n\t\t\t\t</option>";
        }
        // Retrieve recipe for this item
        $sql = "SELECT * FROM cubit.recipies WHERE m_stock_id='{$m_stock_id}' ORDER BY id DESC";
        $recipe_rslt = db_exec($sql) or errDie("Unable to retrieve recipe.");
        $recipe_out = "";
        $cost_total = 0;
        while ($recipe_data = pg_fetch_array($recipe_rslt)) {
            // Retrieve stock
            $sql = "SELECT stkid, stkcod, stkdes, csprice FROM cubit.stock WHERE stkid='{$recipe_data['s_stock_id']}'";
            $stock_rslt = db_exec($sql) or errDie("Unable to retrieve stock.");
            $stock_data = pg_fetch_array($stock_rslt);
            $cost = $stock_data["csprice"] * $recipe_data["qty"];
            $cost_total += $cost;
            $recipe_out .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>({$stock_data['stkcod']}) {$stock_data['stkdes']}</td>\n\t\t\t\t\t<td align='center'>{$recipe_data['qty']}</td>\n\t\t\t\t\t<td align='right'>" . sprint($cost) . "</td>\n\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t<input type='checkbox' name='rem[{$recipe_data['id']}]'\n\t\t\t\t\t\tvalue='{$recipe_data['id']}'\n\t\t\t\t\t\tonchange='javascript:document.form2.submit()' />\n\t\t\t\t\t</td>\n\t\t\t\t</tr>";
        }
        $OUTPUT .= "\n\t\t\t<form method='post' action='" . SELF . "' name='form2'>\n\t\t\t<input type='hidden' name='key' value='remove' />\n\t\t\t<input type='hidden' name='m_stock_id' value='{$m_stock_id}' />\n\t\t\t<input type='hidden' name='filter_store' value='{$filter_store}'>\n\t\t\t<input type='hidden' name='filter_class' value='{$filter_class}'>\n\t\t\t<input type='hidden' name='filter_cat' value='{$filter_cat}'>\n\t\t\t<input type='hidden' name='search_string' value='{$search_string}'>\n\t\t\t<tr>\n\t\t\t\t<th colspan='4'>Stock Used in Manufacturing</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='4'>\n\t\t\t\t\t<table cellpadding='0' cellspacing='1'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t{$display_optional_filters_each1}\n\t\t\t\t\t\t\t<th>Store</th>\n\t\t\t\t\t\t\t<th>Search Code/Description</th>\n\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t{$display_optional_filters_each2}\n\t\t\t\t\t\t\t<td>{$each_store_drop}</td>\n\t\t\t\t\t\t\t<td><input type='text' name='each_search_string' value='{$each_search_string}'></td>\n\t\t\t\t\t\t\t<td><input type='submit' name='search_each' value='Search'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Stock</th>\n\t\t\t\t<th>Qty</th>\n\t\t\t\t<th>Cost</th>\n\t\t\t\t<th>Add<br />Remove</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$s_stock_sel}</td>\n\t\t\t\t<td><input type='text' name='qty' size='4' value='0' style='text-align: center'></td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t<td><input type='submit' name='key' value='Add' style='width: 100%'></td>\n\t\t\t</tr>\n\t\t\t{$recipe_out}\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='2'>Total</td>\n\t\t\t\t<td align='right'>" . sprint($cost_total) . "</td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>\n\t\t<form method='POST' action='" . SELF . "'>\n\t\t\t<input type='hidden' name='key' value='recipe' />\n\t\t\t<input type='hidden' name='save' value='1' />\n\t\t\t<input type='hidden' name='m_stock_id' value='{$m_stock_id}' />\n\t\t\t<input type='submit' value='Save &raquo' />\n\t\t</form>\n\t\t</center>";
    } else {
        $OUTPUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><li>Please select a stock item to continue</li></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</center>";
    }
    return $OUTPUT;
}
function create_dummy($deptid, $supid)
{
    # 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);
    # Dummy Vars
    $remarks = "";
    $supaddr = "";
    $terms = "0";
    $total = 0;
    $subtot = 0;
    //	$pdate = date("Y-m-d");
    $ddate = date("Y-m-d");
    $shipchrg = "0.00";
    $fcid = $sup['fcid'];
    $curr = getSymbol($fcid);
    $xrate = getRate($fcid);
    $purnum = divlastid("pur", USER_DIV);
    $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");
    }
    $pdate = "{$date_year}-{$date_month}-{$date_day}";
    # Insert Order to DB
    $sql = "\n\t\tINSERT INTO nons_purch_int (\n\t\t\tdeptid, supid, supplier, supaddr, terms, pdate, ddate, shipchrg, xrate, fcid, \n\t\t\tcurr, subtot, total, balance, tax, remarks, received, done, prd, \n\t\t\tdiv, purnum\n\t\t) VALUES (\n\t\t\t'{$deptid}', '{$supid}', '',  '{$supaddr}', '{$terms}', '{$pdate}', '{$ddate}', '{$shipchrg}', '{$xrate}', '{$fcid}', \n\t\t\t'{$curr['symbol']}', '{$subtot}', '{$total}', '{$total}', '0', '{$remarks}', 'n', 'n', '" . PRD_DB . "', \n\t\t\t'" . USER_DIV . "', '{$purnum}'\n\t\t)";
    $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Order to Cubit.", SELF);
    # Get next ordnum
    $purid = pglib_lastid("nons_purch_int", "purid");
    return $purid;
}
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;
}
function confirmLoan($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    $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($lday, "num", 1, 2, "Invalid day.");
    $v->isOk($lmonth, "num", 1, 2, "Invalid month.");
    $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.");
    if (empty($loanperiod)) {
        $v->addError("", "You need to enter a payback period.");
    }
    $lyear = getYearOfEmpMon($lmonth);
    if (!checkdate($lmonth, $lday, $lyear)) {
        $v->addError("", "Invalid date.");
    }
    # 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);
    }
    # connect to db
    db_connect();
    # get employee info
    $sql = "SELECT sname, fnames, empnum, enum FROM employees WHERE empnum='{$empnum}' AND div = '" . USER_DIV . "'";
    $empRslt = db_exec($sql) or errDie("Unable to select employee info from database.");
    if (pg_numrows($empRslt) < 1) {
        return "Invalid employee number: {$empnum}.";
    }
    $myEmp = pg_fetch_array($empRslt);
    $fringeset = getCSetting("EMPLOAN_FRINGEINT");
    # calculate monthly installments
    #why does the int amount get multiplied by the repayment years ? you only pay interest ONCE
    //	$loaninstall = sprint (((($loanamt * $loanint/100) * ($loanperiod/12)) + $loanamt) / $loanperiod);
    //	$fringeinstall = sprint (((($loanamt * $fringeset/100) * ($loanperiod/12)) + $loanamt) / $loanperiod);
    $loaninstall = sprint(($loanamt * $loanint / 100 * 1 + $loanamt) / $loanperiod);
    $fringeinstall = sprint(($loanamt * $fringeset / 100 * 1 + $loanamt) / $loanperiod);
    $totaldue = $loaninstall * $loanperiod;
    $totalinterest = $totaldue - $loanamt;
    $fringebenefit = sprint($fringeinstall * $loanperiod - $loanamt - $totalinterest);
    # format loanamt (2 decimal places)
    $loanamt = sprintf("%01.2f", $loanamt);
    if ($account != 0 && $accid != 0 || $account == 0 && $accid == 0) {
        return enterLoan("<li class='err'>Please select a bank account OR a general ledger account.</li>");
    }
    /* get bank acc/contra acc info */
    if ($account > 0) {
        db_conn('core');
        $sql = "SELECT * FROM accounts WHERE accid='{$account}'";
        $accRslt = db_exec($sql);
        if (pg_numrows($accRslt) < 1) {
            return "<li>There are No accounts in Cubit.</li>";
        }
        $acc = pg_fetch_array($accRslt);
        $ac = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Account</td>\n\t\t\t\t<td>{$acc['accname']}</td>\n\t\t\t</tr>";
    } else {
        # Get bank account name
        $sql = "SELECT * FROM bankacct WHERE bankid = '{$accid}' AND div = '" . USER_DIV . "'";
        $bankRslt = db_exec($sql);
        $bank = pg_fetch_array($bankRslt);
        $ac = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Bank Account</td>\n\t\t\t\t<td>{$bank['bankname']} - {$bank['accname']}</td>\n\t\t\t</tr>";
    }
    /* loan acc info */
    db_conn('core');
    $sql = "SELECT * FROM accounts WHERE accid='{$loan_account}'";
    $accRslt = db_exec($sql);
    if (pg_numrows($accRslt) < 1) {
        return enterLoan("<li class='err'>Invalid Loan Account Selected.</li><br>");
    }
    $acc = pg_fetch_array($accRslt);
    $loanac = "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Account</td>\n\t\t\t<td>{$acc['accname']}</td>\n\t\t</tr>";
    /* date description */
    $datedesc = date("j F Y", mktime(0, 0, 0, $lmonth, $lday, $lyear));
    db_connect();
    #get loan type description
    $get_loan_type = "SELECT * FROM loan_types WHERE id = '{$loan_type}' LIMIT 1";
    $run_loan_type = db_exec($get_loan_type) or errDie("Unable to get loan type information.");
    if (pg_numrows($run_loan_type) < 1) {
        $showloantype = "Unknown Loan Type";
    } else {
        $larr = pg_fetch_array($run_loan_type);
        $showloantype = $larr['loan_type'];
    }
    $confirmLoan = "\n\t\t<h3>Confirm new loan application</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='write'>\n\t\t\t<input type='hidden' name='empnum' value='{$empnum}'>\n\t\t\t<input type='hidden' name='lday' value='{$lday}'>\n\t\t\t<input type='hidden' name='lmonth' value='{$lmonth}'>\n\t\t\t<input type='hidden' name='lyear' value='{$lyear}'>\n\t\t\t<input type='hidden' name='loanamt' value='{$loanamt}'>\n\t\t\t<input type='hidden' name='loanint' value='{$loanint}'>\n\t\t\t<input type='hidden' name='loanperiod' value='{$loanperiod}'>\n\t\t\t<input type='hidden' name='loaninstall' value='{$loaninstall}'>\n\t\t\t<input type='hidden' name='fringebenefit' value='{$fringebenefit}'>\n\t\t\t<input type='hidden' name='accid' value='{$accid}'>\n\t\t\t<input type='hidden' name='account' value='{$account}'>\n\t\t\t<input type='hidden' name='loan_account' value='{$loan_account}'>\n\t\t\t<input type='hidden' name='loan_type' value='{$loan_type}'>\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>Employee</td>\n\t\t\t\t<td align='center'>{$myEmp['sname']}, {$myEmp['fnames']} ({$myEmp['enum']})</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Loan Date</td>\n\t\t\t\t<td align='center'>{$datedesc}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Loan Type</td>\n\t\t\t\t<td align='center'>{$showloantype}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Loan amount</td>\n\t\t\t\t<td align='center'>" . CUR . " {$loanamt}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Interest on loan</td>\n\t\t\t\t<td align='center'>{$loanint} %</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Payback period</td>\n\t\t\t\t<td align='center'>{$loanperiod} months</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Monthly installment amount</td>\n\t\t\t\t<td align='center'>" . CUR . " {$loaninstall}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Installment amount (at 11% Interest)</td>\n\t\t\t\t<td align='center'>" . CUR . " {$fringeinstall}</td>\n\t\t\t</tr>\n\t\t\t{$loanac}\n\t\t\t{$ac}\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='right'><input type='submit' value='Write &raquo;'></td>\n\t\t\t\t<td valign='left'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>" . 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 $confirmLoan;
}
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return enter($_POST);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 20, "Invalid Bank ID.");
    foreach ($amount as $key => $value) {
        # check all vars
        $v->isOk($to[$key], "string", 1, 255, "Invalid receipient/depositor.");
        $v->isOk($trantype[$key], "string", 1, 20, "Invalid transaction type.");
        $v->isOk($descript[$key], "string", 0, 255, "Invalid description.");
        $v->isOk($ref[$key], "string", 0, 255, "Invalid reference <b>[{$key}]</b>.");
        $v->isOk($cheqnum[$key], "num", 0, 20, "Invalid cheque number <b>[{$key}]</b>.");
        $v->isOk($amount[$key], "float", 1, 8, "Invalid amount <b>[{$key}]</b>.");
        $v->isOk($accinv[$key], "num", 1, 20, "Invalid account involved <b>[{$key}]</b>.");
        $v->isOk($date[$key], "date", 1, 15, "Invalid date <b>[{$key}]</b>.");
        if (strtotime($date[$key]) >= strtotime($blocked_date_from) and strtotime($date[$key]) <= 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>";
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Processes
    db_connect();
    # Begin Transaction
    pglib_transaction("BEGIN");
    # Some info
    $bankacc = getbankaccid($bankid);
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    foreach ($amount as $key => $amt) {
        $totamt = $amount[$key];
        if ($chrgvat[$key] == "exc") {
            $totamt += $vat[$key];
        } elseif ($chrgvat[$key] == "inc") {
            $amount[$key] -= $vat[$key];
        } else {
            $vat[$key] = "No VAT";
        }
        if ($cheqnum[$key] == '') {
            $cheqnum[$key] = 0;
        }
        if (!isset($batch)) {
            $refnum = getrefnum();
            if (strtolower($trantype[$key]) == 'deposit') {
                $vatacc = gethook("accnum", "salesacc", "name", "VAT", "1");
                writetrans($bankacc, $accinv[$key], $date[$key], $refnum, $amount[$key], $descript[$key]);
                if ($vat[$key] != 0) {
                    # DT(Bank), CT(VAT)
                    $vat[$key] += 0;
                    writetrans($bankacc, $vatacc, $date[$key], $refnum, $vat[$key], $descript[$key] . " VAT");
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode[$key]}'";
                    $Rt = db_exec($Sl) or errDie("Unable to get data.");
                    $vd = pg_fetch_array($Rt);
                    vatr($vatcode[$key], $date[$key], "OUTPUT", $vd['code'], $refnum, $descript[$key] . " VAT", $totamt, $vat[$key]);
                }
            } else {
                $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                writetrans($accinv[$key], $bankacc, $date[$key], $refnum, $amount[$key], $descript[$key]);
                if ($vat[$key] != 0) {
                    # DT(Bank), CT(VAT)
                    $vat[$key] += 0;
                    writetrans($vatacc, $bankacc, $date[$key], $refnum, $vat[$key], $descript[$key] . " VAT");
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode[$key]}'";
                    $Rt = db_exec($Sl) or errDie("Unable to get data.");
                    $vd = pg_fetch_array($Rt);
                    vatr($vatcode[$key], $date[$key], "INPUT", $vd['code'], $refnum, $descript[$key] . " VAT", -$totamt, -$vat[$key]);
                }
            }
            $vat[$key] += 0;
            db_connect();
            $sql = "\n\t\t\t\tINSERT INTO cashbook (\n\t\t\t\t\tbankid, trantype, date, name, descript, cheqnum, \n\t\t\t\t\tamount, banked, accinv, div,chrgvat,vat,reference\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$bankid}', lower('{$trantype[$key]}'), '{$date[$key]}', '{$to[$key]}', '{$descript[$key]}', '{$cheqnum[$key]}', \n\t\t\t\t\t'{$totamt}', 'no', '{$accinv[$key]}', '" . USER_DIV . "','{$chrgvat[$key]}', '{$vat[$key]}','{$ref[$key]}'\n\t\t\t\t)";
            $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        } else {
            db_connect();
            $vat[$key] += 0;
            $sql = "\n\t\t\t\tINSERT INTO batch_cashbook (\n\t\t\t\t\tbankid, trantype, date, name, descript, cheqnum, \n\t\t\t\t\tamount, banked, accinv, div, chrgvat, vat, vatcode, \n\t\t\t\t\treference\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$bankid}', lower('{$trantype[$key]}'), '{$date[$key]}', '{$to[$key]}', '{$descript[$key]}', '{$cheqnum[$key]}', \n\t\t\t\t\t'{$totamt}', 'no', '{$accinv[$key]}', '" . USER_DIV . "','{$chrgvat[$key]}','{$vat[$key]}','{$vatcode[$key]}', \n\t\t\t\t\t'{$ref[$key]}'\n\t\t\t\t)";
            $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        }
    }
    # Get bank details
    $bankAccRslt = get("cubit", "*", "bankacct", "bankid", $bankid);
    $bankacc = pg_fetch_array($bankAccRslt);
    pglib_transaction("COMMIT");
    if (!isset($batch)) {
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Statement Recorded</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>New Statement Details for account, <b>{$bankacc['accname']} ({$bankacc['accnum']})</b><br>held at <b>{$bankacc['bankname']}</b>, was successfully added to Cubit.</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    } else {
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Batch entries recorded</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>New batch items for account, <b>{$bankacc['accname']} ({$bankacc['accnum']})</b><br>held at <b>{$bankacc['bankname']}</b>, was successfully added to Cubit.</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    # Main table (layout with menu)
    $OUTPUT = "\n\t\t<center>\n\t\t<table width='90%'>\n\t\t\t<tr valign='top'>\n\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t<td align='center'>" . mkQuickLinks(ql("bank-pay-add.php", "Add Bank Payment"), ql("bank-recpt-add.php", "Add Bank Receipt"), ql("cashbook-view.php", "View Cash Book"), ql("batch-cashbook-view.php", "View Batch Cashbook")) . "\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
function details($_GET)
{
    $showvat = TRUE;
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $v->isOk($prd, "num", 1, 2, "Invalid prd.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>{$e['msg']}</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get invoice info
    db_conn($prd);
    $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    # 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</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    /* --- Start some checks --- */
    # check if invoice has been printed
    if ($inv['printed'] == "n") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has not been printed.</li>";
        return $error;
    }
    # check if stock was selected(yes = put done button)
    db_conn($prd);
    $sql = "SELECT stkid FROM pinv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
    $crslt = db_exec($sql);
    if (pg_numrows($crslt) < 1) {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has no items.</li>";
        return $error;
    }
    /* --- End some checks --- */
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    $sql = "SELECT * FROM pinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # get warehouse name
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # get selected stock in this warehouse
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
        $tcosamt += $cosamt;
        $sp = "&nbsp;&nbsp;&nbsp;&nbsp;";
        # Check Tax Excempt
        if ($stk['exvat'] == 'yes') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        # keep track of discounts
        $disc += $stkd['disc'];
        if ($stkd['account'] != 0) {
            $stk['stkcod'] = $stkd['description'];
            $stk['stkdes'] = "";
        }
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        $vd = pg_fetch_array($Ri);
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        # put in product
        $stkd['unitcost'] = $stkd['unitcost'] - $stkd['disc'];
        $products .= "\n\t\t<tr>\n\t\t\t<td><font size='1'>&nbsp;&nbsp;{$stk['stkcod']}</font></td>\n\t\t\t<td><font size='1'>" . sprint($stkd["unitcost"]) . "</font></td>\n\t\t\t<td><font size='1'>{$stkd['qty']}</font></td>\n\t\t\t<td align=right><font size='1'>" . sprint($stkd["amt"]) . "</font></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td colspan='4'><font size='1'>{$stk['stkdes']}</font></td>\n\t\t</tr>";
    }
    /* --- Start Some calculations --- */
    # subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    if (strlen($inv['traddisc']) > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * $SUBTOT);
    } else {
        $traddiscm = "0.00";
    }
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    pglib_transaction("BEGIN");
    # Update number of prints
    $inv['prints']++;
    db_conn($prd);
    $Sql = "UPDATE pinvoices SET prints = '{$inv['prints']}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    if (strlen($inv['comm']) > 0) {
        $Com = "\n\t\t\t\t<table>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>" . nl2br($inv['comm']) . "</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    } else {
        $Com = "";
    }
    $time = date("H:i");
    if (isset($cccc)) {
        $cc = "<script> sCostCenter('dt', 'Sales', '{$inv['odate']}', 'Invoice No.{$inv['invnum']} for Customer {$inv['cusname']} {$inv['surname']}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$inv['invnum']}', '{$tcosamt}', ''); </script>";
    } else {
        $cc = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='PSALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sp = "\n\t\t<tr>\n\t\t\t<td width='50%' align='right'><font size='1'>SALES PERSON:</font></td>\n\t\t\t<td width='50%'><font size='1'>{$inv['salespn']}</font></td>\n\t\t</tr>";
    } else {
        $sp = "";
    }
    $Sl = "SELECT * FROM pc WHERE inv='{$inv['invnum']}'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) > 0) {
        $pd = pg_fetch_array($Ri);
        $pc = "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Change</td>\n\t\t\t\t\t<td align='right'><b>" . CUR . " {$pd['amount']}</b></td>\n\t\t\t\t</tr>";
        $change = $pd['amount'];
    } else {
        $pc = "";
        $change = 0;
    }
    $Sl = "SELECT * FROM payrec WHERE inv='{$inv['invnum']}' AND method='Cash'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) > 0) {
        $pd = pg_fetch_array($Ri);
        $pd['amount'] = sprint($pd['amount'] + $change);
        $pcash = "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>Paid Cash</td>\n\t\t\t\t\t\t<td align='right'><b>" . CUR . " {$pd['amount']}</b></td>\n\t\t\t\t\t</tr>";
    } else {
        $pcash = "";
    }
    $Sl = "SELECT * FROM payrec WHERE inv='{$inv['invnum']}' AND method='Cheque'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) > 0) {
        $pd = pg_fetch_array($Ri);
        $pcheque = "\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>Paid Cheque</td>\n\t\t\t\t\t\t\t<td align='right'><b>" . CUR . " {$pd['amount']}</b></td>\n\t\t\t\t\t\t</tr>";
    } else {
        $pcheque = "";
    }
    $Sl = "SELECT * FROM payrec WHERE inv='{$inv['invnum']}' AND method='Credit Card'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) > 0) {
        $pd = pg_fetch_array($Ri);
        $pcc = "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>Paid Credit Card</td>\n\t\t\t\t\t\t<td align='right'><b>" . CUR . " {$pd['amount']}</b></td>\n\t\t\t\t\t</tr>";
    } else {
        $pcc = "";
    }
    $Sl = "SELECT * FROM payrec WHERE inv='{$inv['invnum']}' AND method='Credit'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) > 0) {
        $pd = pg_fetch_array($Ri);
        $pcc .= "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>On Credit</td>\n\t\t\t\t\t\t<td align='right'><b>" . CUR . " {$pd['amount']}</b></td>\n\t\t\t\t\t</tr>\n\t\t\t\t";
    } else {
        $pcc .= "";
    }
    // 	$Sl="SELECT * FROM varrec WHERE inv='$inv[invnum]'";
    // 	$Ri=db_exec($Sl);
    //
    // 	if(pg_num_rows($Ri)>0) {
    // 		$rd=pg_fetch_array($Ri);
    //
    // 		$rounding="<tr><td>Rounding</td><td align=right>".CUR." $rd[amount]</td></tr>";
    // 	} else {
    // 		$rounding="";
    // 	}
    if ($inv['rounding'] > 0) {
        $due = sprint($inv['total'] - $inv['rounding']);
        $rounding = "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Rounding</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$inv['rounding']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Amount Due</td>\n\t\t\t\t\t<td align='right'>" . CUR . " {$due}</td>\n\t\t\t\t</tr>";
    } else {
        $rounding = "";
    }
    $cusinfo = "";
    if ($inv['cusnum'] > 0) {
        db_conn('cubit');
        $Sl = "SELECT * FROM customers WHERE cusnum='{$inv['cusnum']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $cd = pg_fetch_array($Ri);
        $inv['cusname'] = $cd['surname'] . " (VAT No. {$cd['vatnum']})<br>";
        $cusinfo .= "Tel: {$inv['telno']}<br>";
        $cusinfo .= "Order No: {$inv['cordno']}";
    } else {
        if (strlen($inv['vatnum']) > 1) {
            $inv['cusname'] = "{$inv['cusname']} (VAT No. {$inv['vatnum']})<br>";
            $cusinfo .= "Order No: {$inv['cordno']}";
        }
    }
    db_conn('cubit');
    $Sl = "SELECT img2 FROM compinfo";
    $Ri = db_exec($Sl);
    $id = pg_fetch_array($Ri);
    if (strlen($id['img2']) > 0) {
        $logo = "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td valign='top' width='100%' align='center'><img src='compinfo/getimg2.php' width='230' height='47'></td>\n\t\t\t\t\t</tr>\n\t\t\t\t";
    } else {
        $logo = "";
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    if (($posmsg = nl2br(getCSetting("POSMSG"))) === false) {
        $posmsg = "THANK YOU FOR YOUR PURCHASE";
    }
    if ($inv["pslip_sordid"] > 0) {
        $barcode = "<img src='manufact/" . pick_slip_barcode($inv["pslip_sordid"], 1) . "' />";
    } else {
        $barcode = "";
    }
    $nb_top = "border-top: none;";
    $nb_left = "border-left: none;";
    $nb_right = "border-right: none;";
    $nb_bot = "border-bottom: none;";
    $details = "{$cc}\n\t<table cellpadding='0' cellspacing='1' border=0 width='220'>\n\t<tr><td><hr style='border: 1px solid black; {$nb_bot}'></td></tr>\n\t<tr><td align='center'><font size='1'>TAX INVOICE</font></td></tr>\n\t<tr><td align='center'>{$barcode}</td></tr>\n\t<tr><td><hr style='border: 1px solid black; {$nb_top}'></td></tr>\n\t{$logo}\n\t<tr><td valign=top width='100%'>\n\t\t<font size='1'>" . COMP_NAME . "</font><br>\n\t\t<font size='1'>" . COMP_ADDRESS . "</font><br>\n\t\t<br>\n\t\t<font size='1'>TEL: " . COMP_TEL . "</font><br>\n\t\t<font size='1'>FAX: " . COMP_FAX . "</font><br>\n\t\t<br>\n\t\t<font size='1'>Registration Number: " . COMP_REGNO . "</font><br>\n\t\t<font size='1'>VAT Registration Number: " . COMP_VATNO . "</font><br>\n\t</td></tr>\n\t<tr><td><hr style='border: 1px solid black; {$nb_bot} {$nb_left} {$nb_right}'></td></tr>\n\t<tr><td>\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr><td align='center'><font size='1'>{$inv['cusname']}</font></td></tr>\n\t\t\t<tr><td align='left'><font size='1'>{$cusinfo}</font></td></tr>\n\t\t</table>\n\t</td></tr>\n\t<tr><td>\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<td align='left' width='33.33%'><font size='1'>Inv: {$inv['invnum']}</font></td>\n\t\t\t\t<td width='33.33%'><font size='1'>{$time}</font></td>\n\t\t\t\t<td width='33.33%' align='right'><font size='1'>{$inv['odate']}</font></td>\n\t\t\t</tr>\n\t\t</table>\n\t</td></tr>\n\t<tr><td><hr style='border: 1px solid black; {$nb_bot} {$nb_left} {$nb_right}'></td></tr>\n\t<tr><td>\n\t<table cellpadding='4' cellspacing='0' border='0' width='100%' bordercolor='#000000'>\n\t\t<tr>\n\t\t\t<td><font size='1'>CODE</font></td>\n\t\t\t<td><font size='1'>UNIT PRICE</font></td>\n\t\t\t<td><font size='1'>QTY</font></td>\n\t\t\t<td><font size='1'>TOTAL</font></td>\n\t\t<tr>\n\t\t{$products}\n\t</table>\n\t</td></tr>\n\t<tr><td align=right>\n\t\t<table cellpadding='2' cellspacing='0' border=0 width='100%' bordercolor='#000000'>\n\t\t\t<tr><td colspan='2'><hr style='border: 1px solid black; {$nb_bot} {$nb_left} {$nb_right}'></td></tr>\n\t\t\t<tr><td><font size='1'>SUBTOTAL</font></td><td align='right'><font size='1'>" . CUR . " {$SUBTOT}</font></td></tr>\n\t\t\t<tr><td><font size='1'>Trade Discount</font></td><td align='right'><font size='1'>" . CUR . " {$traddiscm}</font></td></tr>\n\t\t\t<tr><td><font size='1'>Delivery Charge</font></td><td align='right'><font size='1'>" . CUR . " {$inv['delchrg']}</font></td></tr>\n\t\t\t<tr><td><font size='1'>VAT {$vat14}</font></td><td align='right'><font size='1'>" . CUR . " {$VAT}</font></td></tr>\n\t\t\t<tr><td><font size='1'>GRAND TOTAL</font></td><td align='right'><b><font size='1'>" . CUR . " {$TOTAL}</font></b></td></tr>\n\t\t\t<font size='1'>{$rounding}</font>\n\t\t\t<font size='1'>{$pcash}</font>\n\t\t\t<font size='1'>{$pcheque}</font>\n\t\t\t<font size='1'>{$pcc}</font>\n\t\t\t<font size='1'>{$pc}</font>\n\t\t\t<tr><td colspan='2'><hr style='border: 1px solid black; {$nb_bot} {$nb_left} {$nb_right}'></td></tr>\n\t\t\t<tr><td colspan='2'><hr style='border: 1px solid black; {$nb_bot}'></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='center'>\n\t\t\t\t<table cellpadding='2' cellspacing='0'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='50%' align='right'><font size='1'>CASHIER:</font></td>\n\t\t\t\t\t<td width='50%'><font size='1'>{$inv['username']}</font></td>\n\t\t\t\t</tr>\n\t\t\t\t{$sp}\n\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td colspan='2'><hr style='border: 1px solid black; {$nb_top}'></td></tr>\n\t\t\t<tr><td colspan='2'><font size='1'>{$posmsg}</font></td></tr>\n\t\t\t<tr><td>\n\t\t\t\t<font size='1'>{$Com}</font>\n\t\t\t</td></tr>\n\t\t</table>\n\t</td></tr>\n\t</table>";
    $OUTPUT = $details;
    require "tmpl-print.php";
}
function enter($errors = "")
{
    global $_POST;
    extract($_POST);
    require "locale_codes.php";
    // Retrieve list of locales from the locales directory
    db_conn("cubit");
    $sql = "SELECT locale FROM users WHERE username='******'";
    $localeRslt = db_exec($sql) or errDie("Unable to retrieve user locale settings from Cubit.");
    $locale_user = pg_fetch_result($localeRslt, 0);
    define("LOCALE_DIR", "./locale");
    $h_dir = opendir(LOCALE_DIR);
    $ar_dir = array();
    while (false !== ($dir = readdir($h_dir))) {
        $ar_dir[] = $dir;
    }
    $locale_sel = "<select name='locale' style='width: 180px'>";
    foreach ($ar_dir as $locale_code) {
        if (is_dir(LOCALE_DIR . "/" . $locale_code) && preg_match("/[a-z]{2,2}_[A-Z]{2,2}/", $locale_code)) {
            if ($locale_code == $locale_user) {
                $selected = "selected";
            } else {
                $selected = "";
            }
            $ar_locale = explode("_", $locale_code);
            // Retrieve the name of the langauge
            foreach ($ar_languages as $lang_name => $lang_code) {
                if ($ar_locale[0] == $lang_code) {
                    $language = $lang_name;
                }
            }
            // Retrieve the name of the country
            foreach ($ar_countries as $country_name => $country_code) {
                if ($ar_locale[1] == $country_code) {
                    $country = $country_name;
                }
            }
            $locale_sel .= "<option value='{$locale_code}' {$selected}>{$language} ({$country})</option>";
        }
    }
    $locale_sel .= "</select>";
    // Admin Settings
    db_conn("cubit");
    $sql = "SELECT admin FROM users WHERE username='******'";
    $admRslt = db_exec($sql) or errDie("Unable to retrieve user information from Cubit.");
    $adm = pg_fetch_result($admRslt, 0);
    if ($adm == 1) {
        // Retrieve a list of all of the current company's usernames
        db_conn("cubit");
        $sql = "SELECT * FROM users ORDER BY username ASC";
        $usersRslt = db_exec($sql) or errDie("Unable to retrieve a list of usernames from Cubit.");
        $usernames = "<select name='username' style='width: 180px'>";
        while ($usrData = pg_fetch_array($usersRslt)) {
            if ($usrData["username"] == USER_NAME) {
                $selected = "selected";
            } else {
                $selected = "";
            }
            $usernames .= "<option value='{$usrData['userid']}' {$selected}>{$usrData['username']}</option>";
        }
        $usernames .= "</select>";
        // Create a dropdown from the list of locales
        //$ar_dir = scandir(LOCALE_DIR);
        $ar_dir = array();
        $h_localdir = opendir(LOCALE_DIR);
        while (false !== ($file = readdir($h_localdir))) {
            $ar_dir[] = $file;
        }
        $dlocale_sel = "<select name='dlocale' style='width: 180px'>";
        $defloc = getCSetting("LOCALE_DEFAULT");
        foreach ($ar_dir as $dlocale_code) {
            if (is_dir(LOCALE_DIR . "/" . $dlocale_code) && preg_match("/[a-z]{2,3}_[A-Z]{2,3}/", $dlocale_code)) {
                $ar_dlocale = explode("_", $dlocale_code);
                // Retrieve the name of the langauge
                foreach ($ar_languages as $lang_name => $lang_code) {
                    if ($ar_dlocale[0] == $lang_code) {
                        $dlanguage = $lang_name;
                    }
                }
                // Retrieve the name of the country
                foreach ($ar_countries as $country_name => $country_code) {
                    if ($ar_dlocale[1] == $country_code) {
                        $dcountry = $country_name;
                    }
                }
                if ($defloc == $dlocale_code) {
                    $selected = "selected";
                } else {
                    $selected = "";
                }
                $dlocale_sel .= "<option value='{$dlocale_code}' {$selected}>{$dlanguage} ({$dcountry})</option>";
            }
        }
        $dlocale_sel .= "</select>";
        /* timezone setting */
        $timezone = getCSetting("LOCALE_TIMEZONE");
        $tzs = qryTimezone(false, "timezone, continent AS optgroup");
        $tzlist = db_mksel($tzs, "timezone", $timezone, "#timezone", "#timezone");
        $adm_settings = "\n\t\t<tr class='" . bg_class() . "'>\n\t\t  <td>Username</td>\n\t\t  <td>{$usernames}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t  <td>" . COMP_NNAME . "'s default locale</td>\n\t\t  <td>{$dlocale_sel}</td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t    <td>Timezone</td>\n\t\t    <td>{$tzlist}</td>\n\t\t</tr>";
    }
    /* locale enabled ? */
    db_conn("cubit");
    $sql = "SELECT locale_enable FROM users WHERE username='******'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve locale setting.");
    $locale_enable = pg_fetch_result($rslt, 0);
    if ($locale_enable != "disabled") {
        $locen_che = "checked";
    } else {
        $locen_che = "";
    }
    // Layout
    $OUTPUT = "\n\t<h3>Locale Settings</h3>\n\t{$errors}\n\t<form method='post' action='" . SELF . "'>\n\t<input type='hidden' name='key' value='confirm'>\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th colspan=2>Settings</th>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Locale Enabled</td>\n\t\t<td><input type='checkbox' name='enable' value='enabled' {$locen_che}></td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t<td>User's Locale</td>\n\t\t<td>{$locale_sel}</td>\n\t</tr>\n\t{$adm_settings}\n\t<tr>\n\t\t<td colspan=2 align=right><input type=submit value='Confirm &raquo'></td>\n\t</tr>\n\t</table>\n\t</form>" . mkQuickLinks(ql("locale-translate.php", "Translate Cubit"), ql("locale-settings.php", "Locale Settings"));
    return $OUTPUT;
}