function confirm($VARS, $cashid)
{
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cashid, "num", 1, 20, "Invalid Reference number.");
    # 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;
    }
    // Connect to database
    Db_Connect();
    $sql = "SELECT * FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.1", SELF);
    $numrows = pg_numrows($accntRslt);
    if ($numrows < 1) {
        $OUTPUT = "<li clss='err'>The deposit with reference number, <b>{$cashid}</b> was not found in Cubit.</li>";
        return $OUTPUT;
    }
    $accnt = pg_fetch_array($accntRslt);
    array_merge($accnt, $VARS);
    extract($accnt);
    if (!isset($date_day)) {
        $date_day = extractDay($date);
    }
    if (!isset($date_month)) {
        $date_month = extractMonth($date);
    }
    if (!isset($date_year)) {
        $date_year = extractYear($date);
    }
    $AccRslt = get("cubit", "*", "bankacct", "bankid", $accnt['bankid']);
    $bank = pg_fetch_array($AccRslt);
    if ($accnt['location'] == "int" || $bank['btype'] == 'int') {
        header("Location: cheq-return-int.php?cashid={$cashid}");
    }
    $confirm = "\n\t\t\t<h3>Confirm Entry</h3>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t<input type='hidden' name='key' value='bank'>\n\t\t\t\t<input type='hidden' name='cashid' value='{$accnt['cashid']}'>";
    if (strlen($accnt['accids']) > 0) {
        $accinv['accname'] = "Multiple Accounts";
    } else {
        # get account name for the account involved
        $AccRslt = get("core", "accname", "accounts", "accid", $accnt['accinv']);
        $accinv = pg_fetch_array($AccRslt);
    }
    $AccRslt = get("cubit", "*", "bankacct", "bankid", $accnt['bankid']);
    $bank = pg_fetch_array($AccRslt);
    $accnt['amount'] = sprint($accnt['amount']);
    $confirm .= "\n\t<tr>\n\t\t<th>Field</th>\n\t\t<th>Value</th>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Bank Name</td>\n\t\t<td>{$bank['bankname']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Account Number</td>\n\t\t<td>{$bank['accnum']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Transaction Type</td>\n\t\t<td>{$accnt['trantype']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Date of Transaction</td>\n\t\t<td>{$accnt['date']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Date of Return</td>\n\t\t<td>" . mkDateSelect("date", $date_year, $date_month, $date_day) . "</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Paid to/Received from</td>\n\t\t<td>{$accnt['name']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Description</td>\n\t\t<td>{$accnt['descript']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Amount</td>\n\t\t<td>" . CUR . " {$accnt['amount']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Transaction Contra Account</td>\n\t\t<td>{$accinv['accname']}</td>\n\t</tr>\n\t<tr><td><br></td></tr>\n\t<tr>\n\t\t<td></td>\n\t\t<td align='right'><input type='submit' value='Write &raquo'></td>\n\t</tr>\n\t</form></table>\n\t<p>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $confirm;
}
function show_report()
{
    global $_GET;
    if (!isset($_GET["id"]) or strlen($_GET["id"]) < 1) {
        return "<li class='err'>Invalid Use Of Module. Invalid Loan.</li>";
    }
    db_connect();
    $get_loan = "SELECT * FROM emp_loanarchive WHERE id = '{$_GET['id']}' LIMIT 1";
    $run_loan = db_exec($get_loan) or errDie("Unable to get loan information.");
    if (pg_numrows($run_loan) < 1) {
        return "<li class='err'>Could Not Get Loan Information.</li>";
    } else {
        $larr = pg_fetch_array($run_loan);
    }
    #get employee details ...
    $get_emp = "SELECT * FROM employees WHERE empnum = '{$larr['empnum']}' LIMIT 1";
    $run_emp = db_exec($get_emp) or errDie("Unable to get employee details.");
    if (pg_numrows($run_emp) < 1) {
        $showempname = "";
    } else {
        $earr = pg_fetch_array($run_emp);
        $showempname = "{$earr['fnames']} {$earr['sname']}";
    }
    #get loan type details ...
    $get_ltype = "SELECT * FROM loan_types WHERE id = '{$larr['loan_type']}' LIMIT 1";
    $run_ltype = db_exec($get_ltype) or errDie("Unable to get loan type details.");
    if (pg_numrows($run_ltype) < 1) {
        $showloantype = "";
    } else {
        $tarr = pg_fetch_array($run_ltype);
        $showloantype = $tarr['loan_type'];
    }
    $ld_mon = extractMonth($larr["loandate"]);
    $ld_year = extractYear($larr["loandate"]);
    $repays = array();
    //$repays[] = "<tr>" . "<td>" . date("F Y") . "</td><td>" . CUR . " $larr[loaninstall]</td></tr>";
    for ($i = 0; $i < $larr['loanperiod']; $i++) {
        $repays[] = "\n\t\t<tr>\n\t\t\t<td>" . date("F Y", mktime(0, 0, 0, $ld_mon + $i, 1, $ld_year)) . "</td>\n\t\t\t<td>" . CUR . " {$larr['loaninstall']}</td>\n\t\t</tr>";
    }
    $showrepays = "";
    foreach ($repays as $each) {
        $showrepays .= "{$each}";
    }
    $display = "\n\t\t\t<center>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='center' colspan='2'><font size='4'><b>Loan For Employee: {$showempname}</b></font></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Loan Issued Date</td>\n\t\t\t\t\t<td>{$larr['archdate']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Loan Type</td>\n\t\t\t\t\t<td>{$showloantype}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Loan Amount</td>\n\t\t\t\t\t<td>{$showloanamt}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Loan Interest Rate</td>\n\t\t\t\t\t<td>{$larr['loanint']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Loan Total</td>\n\t\t\t\t\t<td>" . CUR . " {$larr['loanamt']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Repayment Period</td>\n\t\t\t\t\t<td>{$larr['loanperiod']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>Repayment Periods</th>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<table " . TMPL_tblDflts . " width='20%'>\n\t\t\t\t{$showrepays}\n\t\t\t</table>\n\t\t\t</center>\n\t\t";
    return $display;
}
function genslip($empnum, $fromdate, $todate)
{
    $Sl = "SELECT * FROM employees WHERE empnum='{$empnum}'";
    $Ry = db_exec($Sl) or errDie("Unable to select employees from database.");
    if (pg_numrows($Ry) < 1) {
        $Sl = "SELECT * FROM lemployees WHERE empnum='{$empnum}'";
        $Ry = db_exec($Sl) or errDie("Unable to select employees from database.");
    }
    $emp = pg_fetch_array($Ry);
    $pay['showex'] = "Yes";
    $date = $todate;
    //$pw = "saldate>='$fromdate' AND saldate<='$todate'";
    $from_month = extractMonth($fromdate);
    $to_month = extractMonth($todate);
    if ($to_month < $from_month) {
        $pw = "month::int>='{$from_month}' OR month::int <= '{$to_month}'";
    } else {
        $pw = "month::int>='{$from_month}' AND month::int <= '{$to_month}'";
    }
    $pw = "({$pw}) AND (saldate>='{$fromdate}' AND saldate<='{$todate}')";
    /* paye balance */
    $sql = "SELECT sum(paye) AS sum FROM salpaid WHERE ({$pw}) AND empnum='{$empnum}' AND cyear='" . EMP_YEAR . "'";
    $Ry = db_exec($sql) or errDie("Unable to get paye");
    $pdata = pg_fetch_array($Ry);
    $paid = $pdata['sum'];
    $sql = "SELECT sum(paye) AS sum FROM salr WHERE ({$pw}) AND empnum='{$empnum}' AND cyear='" . EMP_YEAR . "'";
    $Ry = db_exec($sql) or errDie("Unable to get paye");
    $pdata = pg_fetch_array($Ry);
    $upaid = $pdata['sum'];
    $tottax = sprint($paid - $upaid);
    /* salary balance */
    $sql = "SELECT sum(salary) FROM salpaid WHERE ({$pw}) AND empnum='{$empnum}' AND cyear='" . EMP_YEAR . "'";
    $Ry = db_exec($sql) or errDie("Unable to get paye");
    $pdata = pg_fetch_array($Ry);
    $sql = "SELECT sum(salary) FROM salr WHERE ({$pw}) AND empnum='{$empnum}' AND cyear='" . EMP_YEAR . "'";
    $Ry = db_exec($sql) or errDie("Unable to get paye");
    $prdata = pg_fetch_array($Ry);
    $pay['salary'] = $pdata['sum'] - $prdata["sum"];
    $emp['basic_sal'] = sprint($emp['basic_sal']);
    /* pay slip ids */
    $psids = array();
    $sql = "\n\t\tSELECT id, novert, hovert FROM cubit.salpaid WHERE ({$pw}) AND empnum='{$empnum}' AND cyear='" . EMP_YEAR . "' \n\t\tUNION \n\t\tSELECT -id, -novert, -hovert FROM cubit.salr WHERE ({$pw}) AND empnum='{$empnum}' AND cyear='" . EMP_YEAR . "'";
    $rslt = db_exec($sql) or errDie("Error reading payslip ids");
    $novert = 0;
    $hovert = 0;
    while ($row = pg_fetch_assoc($rslt)) {
        $psids[] = "payslip='{$row['id']}'";
        $novert += $row["novert"];
        $hovert += $row["hovert"];
    }
    if (count($psids) <= 0) {
        $psids[] = "true";
    }
    $pwc = "(" . implode(" OR ", $psids) . ")";
    $dates = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<td width='50%'>Date</td>\n\t\t\t\t<td width='50%'>{$date}</td>\n\t\t\t</tr>\n\t\t</table>";
    $i = 0;
    $epw = "date >= '{$fromdate}' AND date <= '{$todate}'";
    $fepw = "fdate >= '{$fromdate}' AND fdate <= '{$todate}'";
    $incomes = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<td width='80%' align='center'>Description</td>\n\t\t\t\t<td align='center'>Amount</td>\n\t\t\t</tr>";
    db_conn('cubit');
    $sql = "SELECT DISTINCT description, type FROM emp_inc WHERE ({$pwc}) AND emp='{$empnum}' AND ({$epw}) ORDER BY description";
    $Ri = db_exec($sql) or errDie("Unable to get data.");
    $tot_incomes = 0;
    while ($data = pg_fetch_array($Ri)) {
        $sql = "SELECT sum(amount) FROM emp_inc WHERE description='{$data['description']}' AND ({$pwc}) AND emp='{$empnum}' AND ({$epw})";
        $Rl = db_exec($sql) or errDie("Unable to get data.");
        $sdata = pg_fetch_array($Rl);
        $incomes .= "\n\t\t\t<tr>\n\t\t\t\t<td>{$data['description']}</td>\n\t\t\t\t<td align='right'>" . CUR . " {$sdata['sum']}</td>\n\t\t\t</tr>";
        $i++;
        if ($data["description"] != "Fringe Benefits Total") {
            $tot_incomes = $tot_incomes + $sdata['sum'];
        }
        if ($data["type"] == "INCO") {
            if ($novert > 0) {
                $incomes .= "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='2'>&nbsp;&nbsp;&nbsp; {$novert} Hours Normal Overtime</td>\n\t\t\t\t\t</tr>";
                ++$i;
            }
            if ($hovert > 0) {
                $incomes .= "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='2'>&nbsp;&nbsp;&nbsp; {$hovert} Hours Holiday Overtime</td>\n\t\t\t\t\t</tr>";
                ++$i;
            }
        }
    }
    while ($i < 7) {
        $incomes .= "<tr><td><br></td></tr>";
        $i++;
    }
    $incomes .= "</table>";
    $i = 0;
    $benefits = "<table " . TMPL_tblDflts . " width='100%'>";
    while ($i < 4) {
        $benefits .= "<tr><td><br></td></tr>";
        $i++;
    }
    $benefits .= "</table>";
    $i = 0;
    $comp_parts = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<td align='center'>Description</td>\n\t\t\t\t<td align='center'>Amount</td>\n\t\t\t</tr>";
    $Sl = "SELECT DISTINCT(description) FROM emp_com WHERE ({$pwc}) AND emp='{$empnum}'  AND description !='SDL' AND ({$epw}) ORDER BY description";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    while ($data = pg_fetch_array($Ri)) {
        $Sl = "SELECT SUM(amount) FROM emp_com WHERE description='{$data['description']}' AND ({$pwc}) AND emp='{$empnum}' AND description !='SDL' AND ({$epw})";
        $Rl = db_exec($Sl) or errDie("Unable to get data.");
        $sdata = pg_fetch_array($Rl);
        $comp_parts .= "\n\t\t\t<tr>\n\t\t\t\t<td width='80%'>{$data['description']}</td>\n\t\t\t\t<td width='20%' align='right'>" . CUR . " {$sdata['sum']}</td>\n\t\t\t</tr>";
        $i++;
    }
    while ($i < 7) {
        $comp_parts .= "<tr><td><br></td></tr>";
        $i++;
    }
    $comp_parts .= "</table>";
    $i = 0;
    $deductions = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<td width='90%' align='center'>Description</td>\n\t\t\t\t<td align='center'>Amount</td>\n\t\t\t</tr>";
    $Sl = "SELECT DISTINCT(description),type FROM emp_ded WHERE ({$pwc}) AND emp='{$empnum}' AND ({$epw}) ORDER BY description";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    $tot_deductions = 0;
    while ($data = pg_fetch_array($Ri)) {
        $Sl = "SELECT SUM(amount) FROM emp_ded WHERE description='{$data['description']}' AND ({$pwc}) AND emp='{$empnum}' AND ({$epw})";
        $Rl = db_exec($Sl) or errDie("Unable to get data.");
        $sdata = pg_fetch_array($Rl);
        if ($data["type"] == "PAYE" && $emp["basic_sal_annum"] <= 65000) {
            $data["description"] = "SITE";
        }
        $deductions .= "\n\t\t\t<tr>\n\t\t\t\t<td>{$data['description']}</td>\n\t\t\t\t<td align='right' nowrap='t'>" . CUR . " {$sdata['sum']}</td>\n\t\t\t</tr>";
        $i++;
        $tot_deductions = $tot_deductions + $sdata['sum'];
    }
    while ($i < 6) {
        $deductions .= TBL_BR;
        $i++;
    }
    $deductions .= "</table>";
    $fringe = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<td width='90%' align=center>Description</td>\n\t\t\t\t<td align='center'>Amount</td>\n\t\t\t</tr>";
    $sql = "SELECT description,SUM(amount) AS amount FROM emp_frin WHERE ({$pwc}) AND emp='{$empnum}' AND ({$fepw}) GROUP BY description ORDER BY description";
    $rslt = db_exec($sql) or errDie("Unable to get data.");
    $i = 0;
    $tot_fringe = 0;
    while ($data = pg_fetch_array($rslt)) {
        $data["amount"] = sprint(abs($data["amount"]));
        $fringe .= "\n\t\t\t<tr>\n\t\t\t\t<td>{$data['description']}</td>\n\t\t\t\t<td align='right' nowrap='t'>" . CUR . " {$data['amount']}</td>\n\t\t\t</tr>";
        $i++;
        $tot_fringe += $data['amount'];
    }
    while ($i < 6) {
        $fringe .= TBL_BR;
        $i++;
    }
    $fringe .= "</table>";
    $exstras = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<td width='25%'>LEAVE DAYS DUE</td>\n\t\t\t\t<td width='25%'></td>\n\t\t\t\t<td width='25%'><b>NETT PAY</b></td>\n\t\t\t\t<td width='25%'><b>" . CUR . " " . sprint($pay["salary"]) . "</b></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td width='25%'>Total Employee's Tax</td>\n\t\t\t\t<td width='25%'>{$tottax}</td>\n\t\t\t\t<td width='25%'></td>\n\t\t\t\t<td width='25%'></td>\n\t\t\t</tr>\n\t\t</table>";
    $pay["salary"] = sprint($pay["salary"]);
    db_conn('cubit');
    $period = "";
    $tot_incomes = sprint($tot_incomes);
    $tot_deductions = sprint($tot_deductions);
    vsprint($tot_fringe);
    $grossdata = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<td width='50%' align='center'><b>GROSS EARNINGS</b></td>\n\t\t\t\t<td width='50%' align='right'>" . CUR . " {$tot_incomes}</td>\n\t\t\t</tr>\n\t\t</table>";
    explodeDate($fromdate, $from_year, $from_month, $from_day);
    explodeDate($todate, $to_year, $to_month, $to_day);
    if ($from_year == $to_year && $from_month == $to_month) {
        $title = "Salary Advice";
        if ($emp["payprd"] == "m") {
            $salprd = getMonthName($to_month) . " " . getYearOfEmpMon($to_month);
        } else {
            if ($emp["payprd"] == "d" && $fromdate == $todate) {
                $salprd = $pay["week"] . getMonthName($to_month) . " " . getYearOfEmpMon($to_month);
            } else {
                if ($emp["payprd"] == "w") {
                    $stdate = mktime(0, 0, 0, $to_month, 1, getYearOfEmpMon($to_month));
                    $endate = mktime(0, 0, 0, $to_month + 1, -1, getYearOfEmpMon($to_month));
                    $paydate = mktimefd($todate);
                    $i = 1;
                    while ($stdate <= $endate) {
                        if (date("w", $stdate) == 5) {
                            if (date("W", $stdate) == date("W", $paydate_f) && date("W", $stdate) == date("W", $paydate_t)) {
                                $salprd = date("j", $stdate) . " " . getMonthName($to_month) . " " . getYearOfEmpMon($to_month);
                                break;
                            }
                            ++$i;
                        }
                        /* next day */
                        $stdate += 24 * 60 * 60;
                    }
                } else {
                    if ($emp["payprd"] == "f") {
                        $stdate = mktime(0, 0, 0, $to_month, 1, getYearOfEmpMon($to_month));
                        $endate = mktime(0, 0, 0, $to_month + 1, -1, getYearOfEmpMon($to_month));
                        $paydate_f = mktimefd($fromdate);
                        $paydate_t = mktimefd($todate);
                        $c = 0;
                        $fnd_week_f = 0;
                        $fnd_week_t = 0;
                        while ($stdate <= $endate) {
                            //date("W", $stdate) == date("W", $paydate)
                            if (date("w", $stdate) == 5) {
                                if (date("W", $stdate) == date("W", $paydate_f)) {
                                    $fnd_week_f = 1;
                                }
                                if (date("W", $stdate) == date("W", $paydate_t)) {
                                    $fnd_week_t = 1;
                                }
                                if ((++$c % 2 == 0 || $c == 5) && ($fnd_week_f || $fnd_week_t)) {
                                    if ($fnd_week_f == 1 && $paydate_f <= $stdate + 48 * 3600) {
                                        $fnd_week_f = 2;
                                        $salprd_f = date("j", $stdate) . " " . getMonthName($from_month) . " " . getYearOfEmpMon($from_month);
                                    }
                                    if ($fnd_week_t == 1 && $paydate_t <= $stdate + 48 * 3600) {
                                        $fnd_week_t = 2;
                                        $salprd_t = date("j", $stdate) . " " . getMonthName($to_month) . " " . getYearOfEmpMon($to_month);
                                    }
                                    /* now check that they are the same, and if so set the display */
                                    if ($fnd_week_f + ($fnd_week_t = 4)) {
                                        if ($salprd_f == $salprd_t) {
                                            $salprd = $salprd_f;
                                        }
                                        break;
                                    }
                                }
                            }
                            /* next day */
                            $stdate += 24 * 60 * 60;
                        }
                    }
                }
            }
        }
    }
    if (!isset($salprd)) {
        $salprd = $title = "{$fromdate} TO {$todate}";
    }
    $OUT = "\n\t\t<center>\n\t\t<h2>" . COMP_NAME . "<br>{$title}</h2>\n\t\t<table border=1 " . TMPL_tblDflts . " width='750'>\n\t\t\t<tr>\n\t\t\t\t<td width='50%' align='center'><b>Employee Details:</b></td>\n\t\t\t\t<td>{$dates}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>Name:</td>\n\t\t\t\t\t\t\t<td>{$emp['sname']}, {$emp['fnames']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>Number:</td>\n\t\t\t\t\t\t\t<td>{$emp['enum']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>ID:</td>\n\t\t\t\t\t\t\t<td>{$emp['idnum']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>Tax No:</td>\n\t\t\t\t\t\t\t<td>{$emp['taxref']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>Rate:</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$emp['basic_sal']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>Designation:</td>\n\t\t\t\t\t\t\t<td>{$emp['designation']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>Gender:</td>\n\t\t\t\t\t\t\t<td>{$emp['sex']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>Marital Status:</td>\n\t\t\t\t\t\t\t<td>{$emp['marital']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top'>\n            \t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td width='50%'>Period</td>\n\t\t\t\t\t\t\t<td width='50%'>{$salprd}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t<table border=1 " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='center' colspan='2'><b>Company Details:</b></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>Address:</td>\n\t\t\t\t\t\t\t<td>" . COMP_ADDRESS . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>Tel:</td>\n\t\t\t\t\t\t\t<td>" . COMP_TEL . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>Fax:</td>\n\t\t\t\t\t\t\t<td>" . COMP_FAX . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>Reg No:</td>\n\t\t\t\t\t\t\t<td>" . COMP_REGNO . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>PAYE Ref:</td>\n\t\t\t\t\t\t\t<td>" . COMP_PAYE . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='center'><b>COMPANY CONTRIBUTIONS</b></td>\n\t\t\t\t<td align='center'><b>INCOME</b></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>{$comp_parts}</td>\n\t\t\t\t<td>{$incomes}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='center'></td>\n\t\t\t\t<td>{$grossdata}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='center'><b>DEDUCTIONS</b></td>\n\t\t\t\t<td align='center'><b>FRINGE BENEFITS</b></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>{$deductions}</td>\n\t\t\t\t<td>{$fringe}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td width='50%'><b>TOTAL DEDUCTIONS</b></td>\n\t\t\t\t\t\t\t<td width='50%' align='right'>" . CUR . " {$tot_deductions}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td width='50%' nowrap='t'><b>TOTAL FRINGE BENEFITS</b></td>\n\t\t\t\t\t\t\t<td width='50%' align='right'>" . CUR . " {$tot_fringe}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>{$exstras}</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUT;
}
function generateMonthView_small_mail($view_diary)
{
    global $_GET;
    extract($_GET);
    $pyear = extractYear(mkdatet($year - 1, $month, 1));
    $pmonth = extractMonth(mkdatet($year, $month - 1, 1));
    $nyear = extractYear(mkdatet($year + 1, $month, 1));
    $nmonth = extractMonth(mkdatet($year, $month + 1, 1));
    $OUTPUT = "\n\t\t<table width=190 cellspacing=0>\n\t\t\t<tr>\n\t\t\t\t<td height=20 align=center " . TMPL_calSmallMonthTitleStyle . ">\n\t\t\t\t\t<a href='" . SELF . "?month={$month}&year={$pyear}'><img border='0' src='left_year.gif'></a>\n\t\t\t\t\t<a href='" . SELF . "?month={$pmonth}&year={$year}'><img border='0' src='left_month.gif'></a>\n\t\t\t\t\t<b><a class='month_text' href='javascript:ajaxLink(\"iframe.php\", \"script=diary-index.php&key=month&month={$month}&year={$year}\");'>" . getMonthName($month) . " {$year}</a></b>\n\t\t\t\t\t<a href='" . SELF . "?month={$nmonth}&year={$year}'><img border='0' src='right_month.gif'></a>\n\t\t\t\t\t<a href='" . SELF . "?month={$month}&year={$nyear}'><img border='0' src='right_year.gif'></a>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align=center " . TMPL_calSmallMonthBodyStyle . " colspan='5'>";
    // generate the titles of the weekdays
    $OUTPUT .= "\n\t\t\t<table width='184' cellspacing=0>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width=23>&nbsp;</td>\n\t\t\t\t\t<td width=23 align=center><b>M</b></td>\n\t\t\t\t\t<td width=23 align=center><b>T</b></td>\n\t\t\t\t\t<td width=23 align=center><b>W</b></td>\n\t\t\t\t\t<td width=23 align=center><b>T</b></td>\n\t\t\t\t\t<td width=23 align=center><b>F</b></td>\n\t\t\t\t\t<td width=23 align=center bgcolor=" . TMPL_calFillSaturday . "><b>S</b></td>\n\t\t\t\t\t<td width=23 align=center bgcolor=" . TMPL_calFillSunday . "><b>S</b></td>\n\t\t\t\t</tr>";
    // get the weekday number of the first of this month
    $first_wd = getWeekdayNum(1, $month, $year);
    // the following code will generate the first entries on the calendar, which is for the previous month (if any)
    // month and year of previous month
    if ($month == 1) {
        $tmp_month = 12;
        $tmp_year = $year - 1;
    } else {
        $tmp_month = $month - 1;
        $tmp_year = $year;
    }
    // date of last monday in previous month (where the entries will start)
    if ($first_wd > 1) {
        $tmp_day = getDaysInMonth($tmp_month, $tmp_year) - ($first_wd - 2);
    } else {
        $tmp_day = 1;
        $tmp_month = $month;
        $tmp_year = $year;
    }
    // create a view variables
    $selected_month = $smonth;
    // create the previous month's entries
    $c_weeknum = getWeekNumber($tmp_day, $tmp_month, $tmp_year);
    $selected_weeknum = getWeekNumber($sday, $smonth, $syear);
    // if today's week number = the current generated week's number, hightlight the row, as so with the selected week,
    if ($c_weeknum == getTodayWeekNumber() && $tmp_year == date("Y") && $month == date("m") || getTodayWeekNumber() == 0 && $month == date("m") && $year == date("Y")) {
        // today's week
        $OUTPUT .= "<tr bgcolor='" . TMPL_calSmallMonthCurrentWeek . "'>";
        $ROW_COLORED = 1;
    } else {
        if ($month == $smonth && $c_weeknum == $selected_weeknum || $c_weeknum == 52 && $selected_weeknum == 0) {
            // selected week, the last check is for the first week in jan
            $OUTPUT .= "<tr bgcolor='" . TMPL_calSmallMonthSelectedWeek . "'>";
            $ROW_COLORED = 1;
        } else {
            // other dates
            $OUTPUT .= "<tr>";
            $ROW_COLORED = 0;
        }
    }
    if ($first_wd != 1) {
        // only if there is a day in this week of previous month, print the week number
        $OUTPUT .= "<td width=23 " . TMPL_calSmallMonthWeekNumberStyle . " align=center>{$c_weeknum}</td>";
    }
    for ($c_wd = 1; $c_wd < $first_wd; $c_wd++, $tmp_day++) {
        // fill differently for saturday and sunday (only when row wasn't already highlighted)
        if ($c_wd == 6 && !$ROW_COLORED) {
            $dayfill = "bgcolor=" . TMPL_calFillSaturday;
        } else {
            if ($c_wd == 7) {
                $dayfill = "bgcolor=" . TMPL_calFillSunday;
            } else {
                $dayfill = "";
            }
        }
        //		** 2006-05-08 **
        // 		$OUTPUT.="<td $dayfill width=23 align=center>
        // 							<a id='calSmallMonthOMLink' href='#' onClick='parent.rightframe.document.location.href=\"diary-index.php?mday=$tmp_day&month=$tmp_month&year=$tmp_year\"'>$tmp_day</a>
        // 						</td>";
        $OUTPUT .= "<td {$dayfill} width='23' align='center'>\n\t\t\t<a id='calSmallMonthOMLink' href='javascript:ajaxLink(\"iframe.php\", \"script=diary-index.php&mday={$tmp_day}&month={$tmp_month}&year={$tmp_year}\");'>{$tmp_day}</a></td>";
    }
    // start creating this month's entries
    $cm_days = getDaysInMonth($month, $year);
    for ($c_day = 1; $c_day <= $cm_days; $c_day++) {
        $c_weeknum = getWeekNumber($c_day, $month, $year);
        if ($c_wd == 1) {
            // start a new row (it's MONDAY!!!!!)
            // if today's week number = the current generated week's number, hightlight the row, as so with the selected week
            if ($c_weeknum == getTodayWeekNumber() && $year == date("Y") && $month == date("m")) {
                // today's week
                $OUTPUT .= "<tr bgcolor='" . TMPL_calSmallMonthCurrentWeek . "'>";
                $ROW_COLORED = 1;
            } else {
                if ($month == $smonth && $c_weeknum == $selected_weeknum) {
                    // selected week
                    $OUTPUT .= "<tr bgcolor='" . TMPL_calSmallMonthSelectedWeek . "'>";
                    $ROW_COLORED = 1;
                } else {
                    // other dates
                    $OUTPUT .= "<tr>";
                    $ROW_COLORED = 0;
                }
            }
            // attach the week number
            $OUTPUT .= "<td align=center width=23 " . TMPL_calSmallMonthWeekNumberStyle . ">{$c_weeknum}</td>";
        }
        // change the fill color if it it 2day's date we are printing, or the selected date
        if ($c_day == $sday && $month == $smonth && $year == $syear) {
            // selected date
            $dayfill = "bgcolor=" . TMPL_calSmallMonthSelectedDay;
            $a_id = "calSmallMonthCMLinkSelected";
        } else {
            if (date("d") == $c_day && date("m") == $month && date("Y") == $year) {
                // 2day's date
                $dayfill = "bgcolor=" . TMPL_calSmallMonthCurrentDay;
                $a_id = "calSmallMonthCMLinkToday";
            } else {
                // other dates
                // fill differently for saturday and sunday (only when the row has not already been colored)
                if ($c_wd == 6 && !$ROW_COLORED) {
                    $dayfill = "bgcolor=" . TMPL_calFillSaturday;
                } else {
                    if ($c_wd == 7 && !$ROW_COLORED) {
                        $dayfill = "bgcolor=" . TMPL_calFillSunday;
                    } else {
                        $dayfill = "";
                    }
                }
                $a_id = "calSmallMonthCMLink";
            }
        }
        //		** 2006-05-08 **
        // 		$OUTPUT.="<td width=23 $dayfill align=center>
        // 							<a id='$a_id' href='#' onClick='parent.rightframe.document.location.href=\"diary-index.php?mday=$c_day&month=$month&year=$year&view_diary=$view_diary\"'>$c_day</a>
        // 						</td>";
        $OUTPUT .= "<td width='23' {$dayfill} align='center'>\n\t\t\t<a id='{$a_id}' href='javascript:ajaxLink(\"iframe.php\", \"script=diary-index.php&mday={$c_day}&month={$month}&year={$year}\");'>{$c_day}</a></td>";
        if ($c_wd == 7) {
            // end the output
            $OUTPUT .= "</tr>";
        }
        $c_wd == 7 ? $c_wd = 1 : $c_wd++;
    }
    // next month variables
    if ($month == 12) {
        $tmp_month = 1;
        $tmp_year = $year + 1;
    } else {
        $tmp_month = $month + 1;
        $tmp_year = $year;
    }
    // finish with the next months entries
    for ($c_day = 1; $c_wd <= 7 && $c_wd > 1; $c_wd++, $c_day++) {
        // fill differently for saturday and sunday
        if ($c_wd == 6 && !$ROW_COLORED) {
            $dayfill = "bgcolor=" . TMPL_calFillSaturday;
        } else {
            if ($c_wd == 7 && !$ROW_COLORED) {
                $dayfill = "bgcolor=" . TMPL_calFillSunday;
            } else {
                $dayfill = "";
            }
        }
        //		** 2006-05-08 **
        // 		$OUTPUT.="<td $dayfill width=23 align=center>
        // 							<a id='calSmallMonthOMLink' href='#' inClick='parent.rightframe.document.location.href=\"diary-index.php?mday=$c_day&month=$tmp_month&year=$tmp_year\"'>$c_day</a>
        // 						</td>";
        $OUTPUT .= "<td {$dayfill} width='23' align='center'>\n\t\t\t<a id='calSmallMonthOMLink' href='javascript:ajaxLink(\"iframe.php?script=diary-index.php\", \"mday={$c_day}&month={$tmp_month}&year={$tmp_year}\");'>{$c_day}</a>";
    }
    // finish the tables and return
    $OUTPUT .= "\n\t\t\t\t</tr>\n\t\t\t</table>\n\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
function invoice()
{
    if (isset($_REQUEST["btn_back"])) {
        return enter();
    }
    extract($_REQUEST);
    // Retrieve asset
    $sql = "SELECT * FROM cubit.assets WHERE id='{$asset_id}'";
    $asset_rslt = db_exec($sql) or errDie("Unable to retrieve asset.");
    $asset_data = pg_fetch_array($asset_rslt);
    // Retrieve asset group
    $sql = "SELECT * FROM cubit.assetgrp WHERE grpid='{$asset_data['grpid']}'";
    $grp_rslt = db_exec($sql) or errDie("Unable to retrieve asset group.");
    $grp_data = pg_fetch_array($grp_rslt);
    // Retrieve customer
    $sql = "SELECT * FROM cubit.customers WHERE cusnum='{$cust_id}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
    $cust_data = pg_fetch_array($cust_rslt);
    if ($cust_id > 0) {
        $ctyp = "s";
        $tval = $cust_id;
    } else {
        if ($cust_id == "-1") {
            $ctyp = "c";
            $tval = "2";
            $cust_data["surname"] = "Cash Sale";
        } else {
            if ($cust_id == "-2") {
                $ctyp = "ac";
                $tval = "";
                $cust_data["surname"] = "Cash Sale";
            } else {
                return enter("<li class='err'>Invalid sale option selected.</li>");
            }
        }
    }
    $acc = "0";
    $vatchrg = $vatinc == "exc" ? "no" : "yes";
    $vcd = qryVatcode($vatcode);
    $va = vatcalca($price * $qty, $vatchrg, "no", 0, $vcd["vat_amount"]);
    pglib_transaction("BEGIN");
    if ($cust_data["surname"] == "Cash Sale") {
        $cust_data["paddr1"] = "";
        $cust_data["vatnum"] = "";
    }
    $sql = "INSERT INTO cubit.nons_invoices(cusname, cusaddr, cusvatno, chrgvat,\r\n\t\t\t\tsdate, odate, subtot, balance, vat, total, done, username, prd,\r\n\t\t\t\tinvnum, typ, ctyp, tval, div, accid, salespn)\r\n\t\t\tVALUES ('{$cust_data['surname']}', '{$cust_data['paddr1']}',\r\n\t\t\t\t'{$cust_data['vatnum']}', '{$vatchrg}', CURRENT_DATE, '{$date}', '{$va['subtotal']}', 0,\r\n\t\t\t\t'{$va['vat']}', '{$va['total']}', 'n', '" . USER_NAME . "', '" . extractMonth($date) . "', 0, \r\n\t\t\t\t'inv', '{$ctyp}', '{$tval}', '" . USER_DIV . "', '{$acc}', 'General')";
    db_exec($sql) or errDie("Unable to create invoice");
    $ni_id = lastinvid();
    $asset_saleacc = gethook("accnum", "salesacc", "name", "saleofassets");
    $price_all = $price * $qty;
    $sql = "INSERT INTO cubit.nons_inv_items (invid, qty, description, div,\r\n\t\t\t\tamt, unitcost, accid, rqty, vatex, cunitcost, asset_id)\r\n\t\t\tVALUES ('{$ni_id}', '{$qty}', '{$asset_data['des']}', '" . USER_DIV . "',\r\n\t\t\t\t'{$price_all}', '{$price}', '{$asset_saleacc}', '0', \r\n\t\t\t\t'{$vatcode}', '0', '{$asset_id}')";
    db_exec($sql) or errDie("Unable to create invoice.");
    pglib_transaction("COMMIT");
    header("Location: asset-invoice-print.php?invid={$ni_id}&printpage=t");
    exit;
}
 /**
  * returns html for a date selection
  *
  * the form fields to update must have in id in the form of
  * ${idpfx}_day, ${idpfx}_month, ${idpfx}_year in the order day, month, year
  * respectively.
  *
  * @ignore
  * @param string idpfx prefix for form fields to update
  * @return string html
  */
 function dateSelection($idpfx)
 {
     global $GWPP;
     /* all the different date parts with default values -> false */
     $date_fields = array("day", "month", "year", "sday", "smonth", "syear");
     foreach ($date_fields as $k) {
         if (!isset($_REQUEST[$k])) {
             ${$k} = false;
         } else {
             ${$k} = $_REQUEST[$k];
         }
     }
     /* why check only date === false but set all of them to date()
     		values? what if they have values you gonna overwrite?
     		because I dont want bugs like day isset, month not, year isset
     		causing some weird month to be shown */
     if ($day === false) {
         $day = date("d");
         $month = date("m");
         $year = date("Y");
     }
     if ($sday === false) {
         $sday = $day;
         $smonth = $month;
         $syear = $year;
     }
     /* forcibly fix the date */
     explodeDate(date("Y-m-d", mktime(0, 0, 0, $smonth, $sday, $syear)), $syear, $smonth, $sday);
     /* previous year */
     $pyear = extractYear(mkdatet($year - 1, $month, 1));
     /* previous month */
     $pmonth = extractMonth(mkdatet($year, $month - 1, 1));
     $pmyear = extractYear(mkdatet($year, $month - 1, 1));
     /* next month */
     $nmonth = extractMonth(mkdatet($year, $month + 1, 1));
     $nmyear = extractYear(mkdatet($year, $month + 1, 1));
     /* next year */
     $nyear = extractYear(mkdatet($year + 1, $month, 1));
     /* month/year selections */
     $dateselmove = "dateSelMoveBySelect(\"{$idpfx}\", \"{$day}\", \"{$sday}\", \"{$smonth}\", \"{$syear}\", \"{$GWPP}\");";
     $move_month = mksel_month("datesel_move_month", $month, "onchange='{$dateselmove}'", true);
     $move_year = mksel_year("datesel_move_year", $year, "onchange='{$dateselmove}'");
     $title_style = "onMouseUp='moveXLayer(false);' onMouseDown='moveXLayer(true);'";
     $OUTPUT = "\n\t<div id='datesel_container' style='background: #fdeb89; border: 1px dashed black;' >\n\t<div id='datesel_loading' style='position: absolute; visibility: hidden;'>\n\t\t<p style='margin-left: 25px; margin-top: 60px;'>\n\t\t\t<strong>Loading. Please Wait...</strong>\n\t\t</p>\n\t</div>\n\t<div id='datesel_calender'>\n\t<table>\n\t<tr>\n\t\t<td nowrap='t' align='left'>\n\t\t\t{$move_month} {$move_year}\n\t\t\t<!--<input type='button' onclick='{$dateselmove}' value='Go'/>-->\n\t\t</td>\n\t\t<td align='right' nowrap='t' onMouseUp='moveXLayer(false);' onMouseDown='moveXLayer(true);'>\n\t\t\t<b><a id='xpopup_cls' href='javascript: XPopupHideAct()'>[X]&nbsp;&nbsp;</a></b>\n\t\t</td>\n\t</tr>\n\t<tr><td colspan='2'>\n\n\t<table width='190' cellspacing='0'>\n\t<tr>\n\t\t<td {$title_style} " . TMPL_calSmallMonthTitleStyleLeft . ">\n\t\t\t<a href='javascript: dateSelMove(\"{$idpfx}\", \"{$day}\", \"{$month}\", \"{$pyear}\", \"{$sday}\", \"{$smonth}\", \"{$syear}\", \"{$GWPP}\");'><img border='0' src='{$GWPP}/left_year.gif' /></a>\n\t\t\t<a href='javascript: dateSelMove(\"{$idpfx}\", \"{$day}\", \"{$pmonth}\", \"{$pmyear}\", \"{$sday}\", \"{$smonth}\", \"{$syear}\", \"{$GWPP}\");'><img border='0' src='{$GWPP}/left_month.gif' /></a>\n\t\t</td>\n\t\t<td {$title_style} " . TMPL_calSmallMonthTitleStyleCenter . ">\n\t\t\t" . getMonthName($month) . " {$year}\n\t\t</td>\n\t\t<td {$title_style} " . TMPL_calSmallMonthTitleStyleRight . ">\n\t\t\t<a href='javascript: dateSelMove(\"{$idpfx}\", \"{$day}\", \"{$nmonth}\", \"{$nmyear}\", \"{$sday}\", \"{$smonth}\", \"{$syear}\", \"{$GWPP}\");'><img border='0' src='{$GWPP}/right_month.gif' /></a>\n\t\t\t<a href='javascript: dateSelMove(\"{$idpfx}\", \"{$day}\", \"{$month}\", \"{$nyear}\", \"{$sday}\", \"{$smonth}\", \"{$syear}\", \"{$GWPP}\");'><img border='0' src='{$GWPP}/right_year.gif' /></a>\n\t\t</td>\n\t</tr>\n\t<tr>\n\t\t<td align='center' " . TMPL_calSmallMonthBodyStyle . " colspan='5'>";
     // generate the titles of the weekdays
     $OUTPUT .= "\n\t\t<table width='184' cellspacing='0'>\n\t\t\t<tr>\n\t\t\t\t<td width='23'>&nbsp;</td>\n\t\t\t\t<td width='23' align='center'><b>M</b></td>\n\t\t\t\t<td width='23' align='center'><b>T</b></td>\n\t\t\t\t<td width='23' align='center'><b>W</b></td>\n\t\t\t\t<td width='23' align='center'><b>T</b></td>\n\t\t\t\t<td width='23' align='center'><b>F</b></td>\n\t\t\t\t<td width='23' align='center' bgcolor=" . TMPL_calFillSaturday . "><b>S</b></td>\n\t\t\t\t<td width='23' align='center' bgcolor=" . TMPL_calFillSunday . "><b>S</b></td>\n\t\t\t</tr>";
     // get the weekday number of the first of this month
     $first_wd = getWeekdayNum(1, $month, $year);
     // the following code will generate the first entries on the calendar, which is for the previous month (if any)
     // month and year of previous month
     if ($month == 1) {
         $tmp_month = 12;
         $tmp_year = $year - 1;
     } else {
         $tmp_month = $month - 1;
         $tmp_year = $year;
     }
     // date of last monday in previous month (where the entries will start)
     if ($first_wd > 1) {
         $tmp_day = getDaysInMonth($tmp_month, $tmp_year) - ($first_wd - 2);
     } else {
         $tmp_day = 1;
         $tmp_month = $month;
         $tmp_year = $year;
     }
     // create a view variables
     $selected_month = $smonth;
     // create the previous month's entries
     $c_weeknum = getWeekNumber($tmp_day, $tmp_month, $tmp_year);
     $selected_weeknum = getWeekNumber($sday, $smonth, $syear);
     // if today's week number = the current generated week's number, hightlight the row, as so with the selected week,
     if ($c_weeknum == getTodayWeekNumber() && $tmp_year == date("Y") && $month == date("m") || getTodayWeekNumber() == 0 && $month == date("m") && $year == date("Y")) {
         // today's week
         $OUTPUT .= "<tr bgcolor='" . TMPL_calSmallMonthCurrentWeek . "'>";
         $ROW_COLORED = 1;
     } else {
         if ($year == $syear && $month == $smonth && $c_weeknum == $selected_weeknum || $c_weeknum == 52 && $selected_weeknum == 0) {
             // selected week, the last check is for the first week in jan
             $OUTPUT .= "<tr bgcolor='" . TMPL_calSmallMonthSelectedWeek . "'>";
             $ROW_COLORED = 1;
         } else {
             // other dates
             $OUTPUT .= "<tr>";
             $ROW_COLORED = 0;
         }
     }
     if ($first_wd != 1) {
         // only if there is a day in this week of previous month, print the week number
         $OUTPUT .= "<td width='23' " . TMPL_calSmallMonthWeekNumberStyle . " align='center'>{$c_weeknum}</td>";
     }
     for ($c_wd = 1; $c_wd < $first_wd; $c_wd++, $tmp_day++) {
         // fill differently for saturday and sunday (only when row wasn't already highlighted)
         if ($c_wd == 6 && !$ROW_COLORED) {
             $dayfill = "bgcolor='" . TMPL_calFillSaturday . "'";
         } else {
             if ($c_wd == 7) {
                 $dayfill = "bgcolor='" . TMPL_calFillSunday . "'";
             } else {
                 $dayfill = "";
             }
         }
         $OUTPUT .= "\n\t\t\t<td {$dayfill} width='23' align='center'>\n\t\t\t\t<a id='calSmallMonthOMLink' href='javascript: dateSelUpdate(\"{$idpfx}\", \"{$tmp_day}\", \"{$tmp_month}\", \"{$tmp_year}\");'>{$tmp_day}</a>\n\t\t\t</td>";
     }
     // start creating this month's entries
     $cm_days = getDaysInMonth($month, $year);
     for ($c_day = 1; $c_day <= $cm_days; $c_day++) {
         $c_weeknum = getWeekNumber($c_day, $month, $year);
         if ($c_wd == 1) {
             // start a new row (it's MONDAY!!!!!)
             // if today's week number = the current generated week's number, hightlight the row, as so with the selected week
             if ($c_weeknum == getTodayWeekNumber() && $year == date("Y") && $month == date("m")) {
                 // today's week
                 $OUTPUT .= "<tr bgcolor='" . TMPL_calSmallMonthCurrentWeek . "'>";
                 $ROW_COLORED = 1;
             } else {
                 if ($year == $syear && $month == $smonth && $c_weeknum == $selected_weeknum) {
                     // selected week
                     $OUTPUT .= "<tr bgcolor='" . TMPL_calSmallMonthSelectedWeek . "'>";
                     $ROW_COLORED = 1;
                 } else {
                     // other dates
                     $OUTPUT .= "<tr>";
                     $ROW_COLORED = 0;
                 }
             }
             // attach the week number
             $OUTPUT .= "<td align='center' width='23' " . TMPL_calSmallMonthWeekNumberStyle . ">{$c_weeknum}</td>";
         }
         /* change the fill color if it it 2day's date we are printing */
         if ($c_day == $sday && $month == $smonth && $year == $syear) {
             // selected date
             $dayfill = "bgcolor=" . TMPL_calSmallMonthSelectedDay;
             $a_id = "calSmallMonthCMLinkSelected";
         } else {
             if (date("d") == $c_day && date("m") == $month && date("Y") == $year) {
                 // 2day's date
                 $dayfill = "bgcolor='" . TMPL_calSmallMonthCurrentDay . "'";
                 $a_id = "calSmallMonthCMLinkToday";
             } else {
                 // other dates
                 // fill differently for saturday and sunday (only when the row has not already been colored)
                 if ($c_wd == 6 && !$ROW_COLORED) {
                     $dayfill = "bgcolor='" . TMPL_calFillSaturday . "'";
                 } else {
                     if ($c_wd == 7 && !$ROW_COLORED) {
                         $dayfill = "bgcolor='" . TMPL_calFillSunday . "'";
                     } else {
                         $dayfill = "";
                     }
                 }
                 $a_id = "calSmallMonthCMLink";
             }
         }
         $OUTPUT .= "\n\t\t\t<td width='23' {$dayfill} align='center'>\n\t\t\t\t<a id='{$a_id}' href='javascript: dateSelUpdate(\"{$idpfx}\", \"{$c_day}\", \"{$month}\", \"{$year}\");'>{$c_day}</a>\n\t\t\t</td>";
         /* end of output */
         if ($c_wd == 7) {
             $OUTPUT .= "</tr>";
         }
         $c_wd = $c_wd == 7 ? 1 : $c_wd + 1;
     }
     // next month variables
     if ($month == 12) {
         $tmp_month = 1;
         $tmp_year = $year + 1;
     } else {
         $tmp_month = $month + 1;
         $tmp_year = $year;
     }
     // finish with the next months entries
     for ($c_day = 1; $c_wd <= 7 && $c_wd > 1; $c_wd++, $c_day++) {
         // fill differently for saturday and sunday
         if ($c_wd == 6 && !$ROW_COLORED) {
             $dayfill = "bgcolor='" . TMPL_calFillSaturday . "'";
         } else {
             if ($c_wd == 7 && !$ROW_COLORED) {
                 $dayfill = "bgcolor='" . TMPL_calFillSunday . "'";
             } else {
                 $dayfill = "";
             }
         }
         $OUTPUT .= "\n\t\t<td {$dayfill} width='23' align='center'>\n\t\t\t<a id='calSmallMonthOMLink' href='javascript: dateSelUpdate(\"{$idpfx}\", \"{$c_day}\", \"{$tmp_month}\", \"{$tmp_year}\");'>{$c_day}</a>\n\t\t</td>";
     }
     /* finish the tables and return */
     $OUTPUT .= "\n\t\t\t</tr>\n\t\t</table>\n\t\t</td>\n\t</tr>\n\t</table>\n\n\t</td></tr>\n\t</table>\n\t</div>\n\t</div>";
     return $OUTPUT;
 }
/**
 * Calculate PAYE on salary
 *
 * @param array &$emp employee db row
 * @param int $prd month/week for which salary is calculated
 * @param float $paye_salary taxable salary
 * @param int $tyear periods in year (weekly emp: 52, monthly: 12, etc...)
 * @param int $age employee age
 * @return float
 */
function calculate_paye_old(&$emp, $prd, $paye_salary, $tyear, $age)
{
    $empnum = $emp["empnum"];
    //define("ACTUAL_EMP_YEAR",getYearOfEmpMon($prd));
    payedbg("fromsal: {$paye_salary}<br />");
    /* query expression for previous payments/paye */
    if ($emp["payprd"] == "w" || $emp["payprd"] == "f" || $emp["payprd"] == "d") {
        list($month, $week) = explode(":", $prd);
        if ($emp["payprd"] == "d") {
            $day = $week;
        } else {
            $day = 1;
        }
        $mw_b = "((month::int>='3' AND month::int<'{$month}')\n\t\t\t\tOR ('{$month}' < '3' AND (month::int<'{$month}' OR month::int>='3')))\n\t\t\t\tOR (month::int='{$month}' AND week<'{$week}')";
    } else {
        $month = $prd;
        $day = 1;
        $mw_b = "(month::int>='3' AND month::int<'{$month}')\n\t\t\t\tOR ('{$month}' < '3' AND (month::int<'{$month}' OR month::int>='3'))";
    }
    /* determine previously paid amounts */
    $sql = "SELECT 1 AS m, * FROM cubit.salamt_pay\n\t\t\tWHERE empnum='{$empnum}' AND cyear='" . EMP_YEAR . "' AND ({$mw_b})\n\t\t\tUNION\n\t\t\tSELECT -1 AS m, * FROM cubit.salamt_rev\n\t\t\tWHERE empnum='{$empnum}' AND cyear='" . EMP_YEAR . "' AND ({$mw_b})";
    $qry = new dbSql($sql);
    $qry->run();
    $prev_emp = $emp["cyear"] == EMP_YEAR && ($emp["prevemp_tax"] > 0 && $emp["prevemp_remun"] > 0);
    payedbg("prevemp: " . ($prev_emp ? "true" : "false") . "<br />");
    if ($prev_emp) {
        $totpaye = $emp["prevemp_tax"];
        $totgross = $paye_salary + $emp["prevemp_remun"];
    } else {
        $totpaye = 0;
        $totgross = $paye_salary;
    }
    $totnetgross = 0;
    while ($row = $qry->fetch_array()) {
        $totpaye += $row["paye"] * $row["m"];
        $totgross += $row["payegross"] * $row["m"];
        $totnetgross += $row["netgross"] * $row["m"];
    }
    /* calculate current year fraction */
    $fday = 1;
    $year_fmon = getYearOfEmpMon(3);
    $year_month = getYearOfEmpMon($month);
    $fmstart = mktime(0, 0, 0, 3, $fday, $year_fmon);
    $tmstart = mktime(0, 0, 0, $month, $day, $year_month);
    /* if weekly/fortnightly, find the first friday (effective first week)
    		and last day of selected weeks  */
    if ($emp["payprd"] == "w" || $emp["payprd"] == "f") {
        payedbg("week: {$week}<br />");
        /* effective first week */
        while (date("w", $fmstart) != 5) {
            $fmstart = mktime(0, 0, 0, 3, ++$fday, $year_fmon);
        }
        /* end of week, find first week first */
        while (date("w", $tmstart) != 5) {
            $tmstart = mktime(0, 0, 0, $month, ++$day, $year_month);
        }
        /* move the day by "week" number of weeks */
        $day += ($week - 1) * ($emp["payprd"] == "w" ? 1 : 2) * 7;
        $tmstart = mktime(0, 0, 0, $month, $day, $year_month);
        // hack(fortnightly): increase to end of 1st week
        if ($emp["payprd"] == "f") {
            $fmstart += 7 * 24 * 60 * 60;
            //$tmstart += 7 * 24 * 60 * 60;
        }
    }
    /* count the periods in the past */
    $curprd = prdage($fmstart, $tmstart, $emp["payprd"]);
    payedbg("curprd calc: " . mkdatet($fmstart) . " - " . mkdatet($tmstart) . BR);
    payedbg("curprd: {$curprd}<br />");
    /* determine start period from the $curprd */
    $finYearStart = getYearOfEmpMon(3);
    $styear = extractYear($emp["hiredate"]);
    $stmon = extractMonth($emp["hiredate"]);
    if ($styear < $finYearStart || $styear == $finYearStart && $stmon < 3) {
        $stprd = 1;
    } else {
        //$stprd = prdage(mktimefd($emp["hiredate"]), $tmstart, $emp["payprd"]);
        payedbg("stprd calc: " . date("Y-m-d", mktimefd(getYearOfEmpMon(3) . "-03-01")));
        payedbg(" - " . date("Y-m-d", mktimefd($emp["hiredate"])) . "<br />");
        $stprd = prdage(mktimefd(getYearOfEmpMon(3) . "-03-01"), mktimefd($emp["hiredate"]), $emp["payprd"]);
    }
    if ($prev_emp) {
        $working_prd = $curprd;
        $totprd = $tyear;
        //$totprd = $tyear - ($stprd - 0);
    } else {
        // num of prds working
        $working_prd = $curprd - ($stprd - 1);
        // total periods should be working this year
        $totprd = $tyear - ($stprd - 1);
    }
    payedbg("startprd: {$stprd}<br />");
    payedbg("totprd: {$totprd}<br />");
    payedbg("totgross: {$totgross}<br />");
    payedbg("totnetgross: {$totnetgross}<br />");
    payedbg("workprd: {$working_prd}<br />");
    //$working_prd = 2;
    //$totprd = 7;
    $paye_salary = $totgross / $working_prd;
    payedbg("payesal1: {$paye_salary}<br />");
    /* scale paye to amount of periods should be working */
    $paye_salary *= $totprd / $tyear;
    //$paye_salary *= $tyear / $curprd;
    payedbg("payesal2: {$paye_salary}<br />");
    $paye = bracket_calcpaye_old($age, $paye_salary, $tyear);
    if (($amt = sprint($paye * ($working_prd / $totprd) - $totpaye)) < 0) {
        $amt = 0;
    }
    return $amt;
}
/**
 * returns which period schema to use for a date
 *
 * @param string $date
 * @return int
 */
function getPRDDB($date = false)
{
    if ($date === false) {
        $date = date("Y-m-d");
    }
    return extractMonth($date);
}