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;
}
# get settings
require "../settings.php";
# decide what to do
if (isset($_POST["key"])) {
    switch ($_POST["key"]) {
        case "confirm":
            $OUTPUT = confirmLoan($_POST);
            break;
        case "write":
            $OUTPUT = writeLoan($_POST);
            break;
        default:
            $OUTPUT = "<li class='err'>Invalid use of module.</li>";
    }
} else {
    $OUTPUT = enterLoan($_GET);
}
# display output
require "../template.php";
# enter loan details (or immediately reject)
function enterLoan($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
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($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($lday, "num", 1, 2, "Invalid day.");
    $v->isOk($lmonth, "num", 1, 2, "Invalid month.");
    $v->isOk($lyear, "num", 4, 4, "Invalid year.");
    $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 (!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);
    }
    # 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);
    # 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: {$myEmp['enum']}.</li>";
    }
    if ($accid > 0) {
        $bankacc = getbankaccid($accid);
    }
    # Debit salaries control acc and credit Bank acc
    $date = date("Y-m-d");
    $ldate = mkdate($lyear, $lmonth, $lday);
    $refnum = getrefnum();
    if ($account > 0) {
        $bankacc = $account;
    }
    //	writetrans($loan_account, $bankacc, $date, $refnum, $loanamt, "Loan granted to employee $myEmp[fnames] $myEmp[sname].");
    if ($accid > 0) {
        # issue bank record
        //		banktrans($accid, "withdrawal", date("d-m-Y"), "$myEmp[fnames] $myEmp[sname]", "Loan granted to employee $myEmp[fnames] $myEmp[sname].", 0, $loanamt, $loan_account);
    }
    $totamount = sprint($loanperiod * $loaninstall);
    $loanint_amt = $totamount - $loanamt;
    # connect to db
    db_connect();
    $ldate = "{$lyear}-{$lmonth}-{$lday}";
    $insert_sql = "\n\t\tINSERT INTO loan_requests (\n\t\t\tempnum, loanamt, loaninstall, loanint, loanperiod, loandate, \n\t\t\tloan_type, div, loan_account, bankacc, date, totamount, \n\t\t\tloanint_amt, fringebenefit, ldate, account, accid\n\t\t) VALUES (\n\t\t\t'{$empnum}', '{$loanamt}', '{$loaninstall}', '{$loanint}', '{$loanperiod}', '{$ldate}', \n\t\t\t'{$loan_type}', '" . USER_DIV . "', '{$loan_account}', '{$bankacc}', '{$date}', '{$totamount}', \n\t\t\t'{$loanint_amt}', '{$fringebenefit}', '{$ldate}', '{$account}', '{$accid}'\n\t\t)";
    $run_insert = db_exec($insert_sql) or errDie("Unable to add loan application request.");
    // 	pglib_transaction("BEGIN");
    //
    // 	$sql = "INSERT INTO emp_loanarchive (empnum, loanamt, loaninstall, loanint, loanperiod,loandate, loan_type, div)
    // 			VALUES('$empnum', '$totamount', '$loaninstall', '$loanint', '$loanperiod', CURRENT_DATE, '$loan_type', '".USER_DIV."')";
    // 	$rslt = db_exec($sql) or errDie("Unable to pre archive loan.");
    //
    // 	$loanid = pglib_lastid('emp_loanarchive', 'id');
    //
    // 	# write to db
    // 	$sql = "UPDATE employees
    // 			SET loanamt='$totamount', loanint='$loanint', loanint_amt='$loanint_amt',
    // 				loanint_unpaid='$loanint_amt', loanperiod='$loanperiod', loaninstall='$loaninstall',
    // 				gotloan='t'::bool, loanpayslip='$loanamt', loanfringe='$fringebenefit', loandate='$ldate',
    // 				expacc_loan='$loan_account', loanamt_tot='$totamount', loanid='$loanid'
    // 			WHERE 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");
    $writeLoan = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Loan granted and added to system</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>New loan application has been successfully added to Cubit.\n\t\t\t\t<a href='../groupware/req_gen.php'>Send</a> an instant message.</td>\n\t\t\t</tr>\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 $writeLoan;
}
function writeLoan($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # 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($loaninstall, "float", 1, 10, "Invalid monthly installment.");
    $v->isOk($fringebenefit, "float", 1, 10, "Invalid fringe benefit amount.");
    $v->isOk($lday, "num", 1, 2, "Invalid day.");
    $v->isOk($lmonth, "num", 1, 2, "Invalid month.");
    $v->isOk($lyear, "num", 4, 4, "Invalid year.");
    $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.");
    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);
    }
    # 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);
    # 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 "Loan already exists for employee number: {$empnum}.";
    }
    if ($accid > 0) {
        $bankacc = getbankaccid($accid);
    }
    # Debit salaries control acc and credit Bank acc
    $date = date("Y-m-d");
    $refnum = getrefnum();
    if ($account > 0) {
        $bankacc = $account;
    }
    writetrans($loan_account, $bankacc, $date, $refnum, $loanamt, "Loan granted to employee {$myEmp['fnames']} {$myEmp['sname']}.");
    if ($accid > 0) {
        # issue bank record
        banktrans($accid, "withdrawal", date("d-m-Y"), "{$myEmp['fnames']} {$myEmp['sname']}", "Loan granted to employee {$myEmp['fnames']} {$myEmp['sname']}.", 0, $loanamt, $loan_account);
    }
    $totamount = sprint($loanperiod * $loaninstall);
    $loanint_amt = $totamount - $loanamt;
    # connect to db
    db_connect();
    $ldate = "{$lyear}-{$lmonth}-{$lday}";
    pglib_transaction("BEGIN");
    $sql = "INSERT INTO emp_loanarchive (empnum, loanamt, loaninstall, loanint, loanperiod,loandate, div)\n\t\t\tVALUES('{$empnum}', '{$totamount}', '{$loaninstall}', '{$loanint}', '{$loanperiod}', CURRENT_DATE, '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to pre archive loan.");
    $loanid = pglib_lastid('emp_loanarchive', 'id');
    # write to db
    $sql = "UPDATE employees\n\t\t\tSET loanamt='{$totamount}', loanint='{$loanint}', loanint_amt='{$loanint_amt}',\n\t\t\t\tloanint_unpaid='{$loanint_amt}', loanperiod='{$loanperiod}', loaninstall='{$loaninstall}',\n\t\t\t\tgotloan='t'::bool, loanpayslip='{$loanamt}', loanfringe='{$fringebenefit}', loandate='{$ldate}',\n\t\t\t\texpacc_loan='{$loan_account}', loanamt_tot='{$totamount}', loanid='{$loanid}'\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");
    $writeLoan = "<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='50%'>\n\t<tr><th>Loan granted and added to system</th></tr>\n\t<tr class=datacell><td>New loan has been successfully added to Cubit.</td></tr>\n\t</table>" . mkQuickLinks(ql("../admin-employee-add.php", "Add Employee"), ql("../admin-employee-view.php", "View Employees"));
    return $writeLoan;
}