function view()
{
    extract($_GET);
    require_lib("validate");
    $v = new validate();
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    $v->isOk($id, "num", 1, 20, "Invalid payslip number.");
    if ($v->isError()) {
        $confirmCust = $v->genErrors() . "<br><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    if (($emp = qryEmployee($empnum, "*")) === false) {
        $emp = qryLEmployee($empnum, "*");
    }
    if (isset($rev)) {
        $tbl = "salr";
    } else {
        $tbl = "salpaid";
    }
    $sql = "SELECT * FROM cubit.{$tbl} WHERE empnum='{$empnum}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to read employee salary details from Cubit.");
    if (pg_numrows($rslt) < 1) {
        return "<li>Employee payment not found.</li>";
    }
    $pay = pg_fetch_array($rslt);
    # Calculate gross salary from nettpay
    $gross = $pay['salary'] - $pay['totallow'] - $pay['comm'] + $pay['totded'] + $pay['uif'] + $pay['paye'] + $pay['loanins'];
    vsprint($gross);
    # Layout
    $slip = "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<td align='right'><font size='3' color='white'><b>Employee: </b></font></td>\n\t\t<td align='left'><b>{$emp['empnum']}</b></td>\n\t\t<td align='right'><font size='3' color='white'><b>Name: </b></font></td>\n\t\t<td align='left'><b>{$emp['fnames']}</b></td>\n\t\t<td align='right'><font size='3' color='white'><b>Surname: </b></font></td>\n\t\t<td align='left'><b>{$emp['sname']}</b></td>\n\t</tr>\n\t" . TBL_BR . "\n\t</table>\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th>Description</th>\n\t\t<th>Amount</th>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Gross Basic salary</td>\n\t\t<td align='center'>" . CUR . " {$gross}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Commission</td>\n\t\t<td align='center'>" . CUR . " {$pay['comm']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Low or interest-free loan</td>\n\t\t<td align='center'>" . CUR . " {$pay['loanins']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Interest rate charged by company</td>\n\t\t<td align='center'>{$emp['loanint']} %</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Deductions</td>\n\t\t<td align='center'>" . CUR . " {$pay['totded']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>UIF</td>\n\t\t<td align='center'>" . CUR . " {$pay['uif']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>PAYE</td>\n\t\t<td align='center'>" . CUR . " {$pay['paye']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Allowances</td>\n\t\t<td align='center'>" . CUR . " {$pay['totallow']}</td>\n\t</tr>\n\t" . TBL_BR . "\n\t<tr class='" . bg_class() . "'>\n\t\t<td><h3>Nett Income</h3></td>\n\t\t<td align='center'><b>" . CUR . " {$pay['salary']}</b></td>\n\t</tr>\n\t</table>" . mkQuickLinks(ql("../admin-employee-add.php", "Add Employee"));
    return $slip;
}
function entersal(&$frm)
{
    /* @var $frm cForm */
    if ($frm->validate("entersal")) {
        return select_emp($frm);
    }
    $frm->setkey("writesal");
    extract($_POST);
    $empi = qryEmployee($empnum);
    $qry = new dbSelect("salpaid", "cubit", grp(m("cols", "month, week"), m("where", "empnum='{$empnum}' AND cyear='" . EMP_YEAR . "'"), m("order", "month, week"), m("group", "month, week")));
    //print $qry->sql;
    $qry->run();
    /* in case we did a correction, we run clean_fields to remove the 
    		previous employee's fields */
    $frm->clean_fields("headers");
    $frm->clean_fields("hrs", true);
    $frm->clean_fields("sal", true);
    $frm->setcell(1, 2);
    $frm->add_layout("\n\t\t<tr>\n\t\t\t<th>Month</th>\n\t\t\t" . ($empi["payprd"] == "m" ? "" : "<th>Week/Day</th>") . "\n\t\t\t<th>Basic Salary Rate<br />for Month</th>\n\t\t\t" . ($empi["saltyp"] != "h" ? "" : "<th>Hours Worked</th>") . "\n\t\t</tr>", false, "headers");
    while ($row = $qry->fetch_array()) {
        $sqry = new dbSelect("salpaid", "cubit", grp(m("where", "empnum='{$empnum}' AND cyear='" . EMP_YEAR . "'\n\t\t\t\t\t\tAND month='{$row['month']}' AND week='{$row['week']}'"), m("order", "true_ids DESC"), m("limit", "1")));
        $sqry->run();
        if ($sqry->num_rows() > 0) {
            $si = $sqry->fetch_array();
            /* hours field option */
            if ($empi["saltyp"] == "h") {
                $hrsopt = "<td>%fldonly</td>";
            } else {
                $hrsopt = "";
            }
            /* show week number */
            if ($empi["payprd"] == "m") {
                $weekdisp = "";
            } else {
                $weekdisp = "<td>{$row['week']}</td>";
            }
            $lay = "\n\t\t\t<tr %bg>\n\t\t\t\t<td>{$row['month']}</td>\n\t\t\t\t{$weekdisp}\n\t\t\t\t<td>%fldonly</td>\n\t\t\t\t{$hrsopt}\n\t\t\t</tr>";
            $frm->add_layout($lay);
            $frm->add_text("", "sal[{$si['id']}]", $si["salrate"], "float", "1:40", array("size" => "7"));
            if ($empi["saltyp"] == "h") {
                $frm->add_text("", "hrs[{$si['id']}]", $si["hours"], "float", "1:40", array("size" => "5"));
            }
        }
    }
    return $frm->getfrm_input();
}
function slip($_POST, $pure = false)
{
    # get vars
    extract($_POST);
    $empnum += 0;
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($from_day)) {
        $v->isOk($from_day, "num", 1, 2, "Invalid from Date day.");
        $v->isOk($from_month, "num", 1, 2, "Invalid from Date month.");
        $v->isOk($from_year, "num", 1, 4, "Invalid from Date Year.");
        $v->isOk($to_day, "num", 1, 2, "Invalid to Date day.");
        $v->isOk($to_month, "num", 1, 2, "Invalid to Date month.");
        $v->isOk($to_year, "num", 1, 4, "Invalid to Date Year.");
        # mix dates
        $fromdate = $from_year . "-" . $from_month . "-" . $from_day;
        $todate = $to_year . "-" . $to_month . "-" . $to_day;
        if (!checkdate($from_month, $from_day, $from_year)) {
            $v->isOk($fromdate, "num", 1, 1, "Invalid from date.");
        }
        if (!checkdate($to_month, $to_day, $to_year)) {
            $v->isOk($todate, "num", 1, 1, "Invalid to date.");
        }
    } else {
        if (isset($mon)) {
            $v->isOk($mon, "num", 1, 2, "Invalid month selected.");
        }
    }
    $v->isOk($empnum, "num", 1, 14, "Invalid employee selected.");
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirmCust .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    #check what we have permission to
    $get_perm = "SELECT payroll_groups FROM users WHERE username = '******'USER_NAME']}' LIMIT 1";
    $run_perm = db_exec($get_perm) or errDie("Unable to get payroll groups permission information.");
    if (pg_numrows($run_perm) > 0) {
        $parr = pg_fetch_array($run_perm);
        if (strlen($parr['payroll_groups']) > 0) {
            $pay_grps = explode(",", $parr['payroll_groups']);
        } else {
            $pay_grps = array();
        }
    } else {
        $pay_grps = array();
    }
    if (isset($emp_group) and is_array($emp_group)) {
        $emp_groups = array();
        $emps = array();
        foreach ($emp_group as $each) {
            if (!in_array($each, $pay_grps)) {
                continue;
            }
            $emp_groups[] = $each;
            $get_emp = "SELECT empnum FROM employees WHERE emp_group = '{$each}'";
            $run_emp = db_exec($get_emp) or errDie("Unable to get employees information.");
            if (pg_numrows($run_emp) > 0) {
                while ($earr = pg_fetch_array($run_emp)) {
                    $emps[] = $earr['empnum'];
                }
            }
        }
    } else {
        #check for which groups we have perm
        $get_check = "SELECT payroll_groups FROM users WHERE username = '******'USER_NAME']}' LIMIT 1";
        $run_check = db_exec($get_check) or errDie("Unable to get employees group permissions.");
        if (pg_numrows($run_check) > 0) {
            $earr = pg_fetch_array($run_check);
            if (strlen($earr['payroll_groups']) > 0) {
                $eperms = explode(",", $earr['payroll_groups']);
                $egsearch = " AND (emp_group = '" . implode("' OR emp_group = '", $eperms) . "')";
            } else {
                $egsearch = "AND FALSE";
            }
        }
        $emp_groups[] = array(0 => '0');
        $get_emp = "SELECT empnum FROM employees WHERE true {$egsearch}";
        $run_emp = db_exec($get_emp) or errDie("Unable to get employees information.");
        while ($earr = pg_fetch_array($run_emp)) {
            $emps[] = $earr['empnum'];
        }
    }
    if (!isset($emps)) {
        $emps = array(0);
    }
    if (in_array('0', $emp_groups)) {
        $show_all = TRUE;
    } else {
        $show_all = FALSE;
    }
    $totgross = 0;
    $totcomm = 0;
    $totins = 0;
    $totuif = 0;
    $totpaye = 0;
    $totded = 0;
    $totsal = 0;
    if (!isset($salyear) or strlen($salyear) < 1) {
        $salyear = EMP_YEAR;
    }
    /* get employee details */
    db_connect();
    if (isset($from_day)) {
        $retfunc = "slctDate";
        if ($empnum != "0") {
            #if not all then use selected employee
            $empw = "empnum='{$empnum}' AND ";
        } else {
            #else use all payslips ... but only with emps in selected group
            if (!$show_all) {
                $empw = "";
                foreach ($emps as $each) {
                    $empw .= "empnum='{$each}' OR ";
                }
                $empw .= "empnum='{$each}'";
            }
        }
        if (substr($empw, -4) == "AND ") {
            $empw = substr($empw, 0, -4);
        }
        if (!isset($empw)) {
            $empw = "true";
        }
        $sql = "SELECT 'salp' AS paytype, * FROM salpaid\n\t\t\t\tWHERE ({$empw}) AND saldate >= '{$fromdate}' AND saldate <= '{$todate}' AND div = '" . USER_DIV . "' AND cyear='{$salyear}'\n\t\t\t\tUNION\n\t\t\t\tSELECT 'salr' AS paytype, * FROM salr\n\t\t\t\tWHERE ({$empw}) AND saldate >= '{$fromdate}' AND saldate <= '{$todate}' AND div = '" . USER_DIV . "' AND cyear='{$salyear}'\n\t\t\t\tORDER BY true_ids ASC";
    } else {
        if (isset($empnum)) {
            $retfunc = "slctEmployee";
            $sql = "SELECT 'salp' AS paytype, * FROM salpaid\n\t\t\t\tWHERE month='{$mon}' AND empnum='{$empnum}' AND div = '" . USER_DIV . "' AND cyear='{$salyear}'\n\t\t\t\tUNION\n\t\t\t\tSELECT 'salr' AS paytype, * FROM salr\n\t\t\t\tWHERE month='{$mon}' AND empnum='{$empnum}' AND div = '" . USER_DIV . "' AND cyear='{$salyear}'\n\t\t\t\tORDER BY true_ids ASC";
        } else {
            invalid_use();
        }
    }
    $pRslt = db_exec($sql) or errDie("Unable to select employee payments from database.");
    if (pg_numrows($pRslt) < 1) {
        return "<li class='err'> - Employee salaries matching the search criteria not found.</li>" . $retfunc();
    }
    $slip = "";
    if (pg_numrows($pRslt) > 0) {
        $empdata = array();
        $empcounter = array();
        while ($pay = pg_fetch_array($pRslt)) {
            $en = $pay["empnum"];
            $mwid = "{$pay['month']}:{$pay['week']}";
            if (!isset($empdata[$en])) {
                $empdata[$en] = array();
            }
            if (!isset($empdata[$en][$mwid])) {
                $empdata[$en][$mwid] = array("gross" => 0, "comm" => 0, "loanins" => 0, "uif" => 0, "paye" => 0, "salary" => 0, "saldate" => "", "payslip" => 0);
            }
            $ed =& $empdata[$en][$mwid];
            $gross = $pay['salary'] - $pay['totallow'] - $pay['comm'] + $pay['totded'] + $pay['uif'] + $pay['paye'] + $pay['loanins'];
            $ed["saldate"] = $pay["saldate"];
            if ($pay["paytype"] == "salp") {
                $ed["gross"] += $gross;
                $ed["comm"] += $pay["comm"];
                $ed["loanins"] += $pay["loanins"];
                $ed["uif"] += $pay["uif"];
                $ed["paye"] += $pay["paye"];
                // 				$ed["totded"] += $pay["totded"];
                $ed["salary"] += $pay["salary"];
                $ed["payslip"] = $pay["id"];
                $totgross += $gross;
                $totcomm += $pay['comm'];
                $totins += $pay['loanins'];
                $totuif += $pay['uif'];
                $totpaye += $pay['paye'];
                $totded += $pay['totded'];
                $totsal += $pay['salary'];
            } else {
                $ed["gross"] -= $gross;
                $ed["comm"] -= $pay["comm"];
                $ed["loanins"] -= $pay["loanins"];
                $ed["uif"] -= $pay["uif"];
                $ed["paye"] -= $pay["paye"];
                // 				$ed["totded"] -= $pay["totded"];
                $ed["salary"] -= $pay["salary"];
                $ed["payslip"] = "{$pay['id']}&rev=true";
                $totgross -= $gross;
                $totcomm -= $pay['comm'];
                $totins -= $pay['loanins'];
                $totuif -= $pay['uif'];
                $totpaye -= $pay['paye'];
                $totded -= $pay['totded'];
                $totsal -= $pay['salary'];
            }
            $get_deds = "SELECT distinct(type) FROM emp_ded WHERE payslip = '{$pay['id']}'";
            $run_deds = db_exec($get_deds) or errDie("Unable to get salary deduction information.");
            if (pg_numrows($run_deds) > 0) {
                // 				$deductions = "";
                // 				$ed["totded"] = array()
                $colspan = 0;
                while ($darr = pg_fetch_array($run_deds)) {
                    $darr['type'] += 0;
                    if ($darr['type'] > 0) {
                        print "adding a deduction<br>";
                        $get_amt = "SELECT amount, description FROM emp_ded WHERE payslip = '{$pay['id']}' AND type = '{$darr['type']}' LIMIT 1";
                        $run_amt = db_exec($get_amt) or errDie("Unable to get employee deduction amount.");
                        $deduction_heading .= "<th>" . pg_fetch_result($run_amt, 0, 1) . "</th>";
                        $ed["totded"][] = "<td nowrap>" . CUR . " " . sprint(pg_fetch_result($run_amt, 0, 0)) . "</td>";
                        // 						$deductions .= "<td nowrap>".CUR." ".sprint($darr['amount'])."</td>";
                        $colspan++;
                    }
                }
            } else {
                // 				$deductions = "";
                $colspan = 1;
            }
        }
        print "----------<br>";
        print "<pre>";
        var_dump($ed);
        print "</pre>";
        print "<br>>>>>>>>>>>>>>>>>>>>><br>";
        // print "<pre>";
        // var_dump ($
        foreach ($empdata as $empnum => $months) {
            foreach ($months as $monthweek => $sal) {
                list($month, $week) = explode(":", $monthweek);
                if (($emp = qryEmployee($empnum, "fnames, sname, basic_sal, payprd")) === false) {
                    $emp = qryLEmployee($empnum, "fnames, sname, basic_sal, payprd");
                }
                // not a date range but a single employee, store the name
                if (!isset($from_day)) {
                    $empname = "{$emp['fnames']} {$emp['sname']}";
                }
                /* create month week description */
                $mw_desc = getMonthName($month);
                // weekly
                if ($emp["payprd"] == "w") {
                    $mw_desc .= ", Week {$week}";
                    // fortnightly
                } else {
                    if ($emp["payprd"] == "f") {
                        if ($week == 1) {
                            $week = "1-2";
                        } else {
                            if ($week == 2) {
                                $week = "3-4";
                            } else {
                                $week = "5";
                            }
                        }
                        $mw_desc .= ", Week {$week}";
                    }
                }
                print "<pre>";
                var_dump($sal["totded"]);
                print "</pre>";
                $bgColor = bgcolorg();
                $slip .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>{$emp['fnames']} {$emp['sname']}</td>\n\t\t\t\t\t\t<td nowrap>" . CUR . " " . sprint($sal["gross"]) . "</td>\n\t\t\t\t\t\t<td nowrap>" . CUR . " " . sprint($sal["comm"]) . "</td>\n\t\t\t\t\t\t<td nowrap>" . CUR . " " . sprint($sal["loanins"]) . "</td>\n\t\t\t\t\t\t<td nowrap>" . CUR . " " . sprint($sal["uif"]) . "</td>\n\t\t\t\t\t\t<td nowrap>" . CUR . " " . sprint($sal["paye"]) . "</td>\n\t\t\t\t\t\t" . implode("", $sal["totded"]) . "\n\t\t\t\t\t\t<td nowrap>" . CUR . " " . sprint($sal["salary"]) . "</td>\n\t\t\t\t\t\t<td nowrap>{$mw_desc}</td>\n\t\t\t\t\t\t<td nowrap>{$sal['saldate']}</td>";
                if (!$pure) {
                    $slip .= "\n\t\t\t\t\t\t<td><a href='payslip-view.php?empnum={$empnum}&id={$sal['payslip']}'>View</a></td>\n\t\t\t\t\t\t<td><a target='_blank' href='payslip-print.php?id={$sal['payslip']}'>Print</a></td>";
                }
                $slip .= "</tr>";
            }
        }
        # Format the totals
        $totgross = sprint($totgross);
        $totcomm = sprint($totcomm);
        $totins = sprint($totins);
        $totuif = sprint($totuif);
        $totpaye = sprint($totpaye);
        $totded = sprint($totded);
        $totsal = sprint($totsal);
        $slip .= "\n\t\t\t<tr class='bg-even'>\n\t\t\t\t<td><b>Total</b></td>\n\t\t\t\t<td nowrap><b>" . CUR . " {$totgross}</b></td>\n\t\t\t\t<td nowrap><b>" . CUR . " {$totcomm}</b></td>\n\t\t\t\t<td nowrap><b>" . CUR . " {$totins}</b></td>\n\t\t\t\t<td nowrap><b>" . CUR . " {$totuif}</b></td>\n\t\t\t\t<td nowrap><b>" . CUR . " {$totpaye}</b></td>\n\t\t\t\t<td nowrap><b>" . CUR . " {$totded}</b></td>\n\t\t\t\t<td nowrap><b>" . CUR . " {$totsal}</b></td>\n\t\t\t\t<td colspan='4'></td>\n\t\t\t</tr>";
    } else {
        return "<li> - There are no salary payments for the selected month</li>";
    }
    if (isset($from_day)) {
        $title = "<h3>Salaries Paid {$fromdate} TO {$todate}</h3>";
    } else {
        $title = "<h3>Salaries for {$empname}</h3>";
    }
    $slip = "\n\t\t<center>\n\t\t{$title}\n\t\t<table " . TMPL_tblDflts . " width='70%'>\n\t\t\t<tr>\n\t\t\t\t<th>Employee</th>\n\t\t\t\t<th>Gross Salary</th>\n\t\t\t\t<th>Commission</th>\n\t\t\t\t<th>Low or interest free loan</th>\n\t\t\t\t<th>UIF</th>\n\t\t\t\t<th>PAYE</th>\n\t\t\t\t<th colspan='{$colspan}'>Deductions</th>\n\t\t\t\t<th>Nett Income</th>\n\t\t\t\t<th>Month/Week</th>\n\t\t\t\t<th>Payment Date</th>\n\t\t\t\t" . (!$pure ? "<th colspan='2'>Options</th>" : "") . "\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th colspan='6'></th>\n\t\t\t\t{$deduction_heading}\n\t\t\t\t<th colspan='5'></th>\n\t\t\t</tr>\n\t\t\t{$slip}\n\t\t\t" . TBL_BR;
    if (!$pure) {
        $slip .= "\n\t\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t" . array2form($_REQUEST) . "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><input name=key type=submit value='Export to Spreadsheet'></td>\n\t\t\t\t</tr>\n\t\t\t</form>" . mkQuickLinks(ql("../admin-employee-add.php", "Add Employee")) . "\n\t\t\t</td></tR>";
    }
    $slip .= "\n\t\t</table>\n\t\t</center>";
    return $slip;
}
예제 #4
0
function enter_data2($_POST)
{
    extract($_POST);
    global $_SESSION;
    $out = "\n\t\t<h3>Trial Balance Import</h3>\n\t\t%%USEDNUMS_MSG%%\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='confirm' />\n\t\t\t<input type='hidden' name='login' value='1' />\n\t\t\t<input type='hidden' name='div' value='{$_SESSION['USER_DIV']}' />\n\t\t\t<input type='hidden' name='login_user' value='{$_SESSION['USER_NAME']}' />\n\t\t\t<input type='hidden' name='login_pass' value='{$_SESSION['USER_PASS']}' />\n\t\t\t<input type='hidden' name='code' value='{$_SESSION['code']}' />\n\t\t\t<input type='hidden' name='comp' value='{$_SESSION['comp']}' />\n\t\t\t<input type='hidden' name='noroute' value='1' />\n\t\t\t<input type='hidden' name='prd' value='{$prd}' />\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Importing into " . getMonthName($prd) . " " . getYearOfFinMon($prd) . "</th>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<th>Acc No</th>\n\t\t\t\t<th>Account Name</th>\n\t\t\t\t<th>Debit</th>\n\t\t\t\t<th>Credit</th>\n\t\t\t\t<th>Confrim Account to link to/Select category of new account</th>\n\t\t\t</tr>";
    db_conn('exten');
    $Sl = "SELECT stkacc FROM warehouses";
    $Ri = db_exec($Sl);
    $wd = pg_fetch_array($Ri);
    $ic = $wd['stkacc'];
    $Sl = "SELECT debtacc,credacc FROM departments";
    $Ri = db_exec($Sl);
    $dd = pg_fetch_array($Ri);
    $cc = $dd['debtacc'];
    $sc = $dd['credacc'];
    db_conn('cubit');
    $Sl = "SELECT * FROM import_data ORDER BY des1";
    $Ri = db_exec($Sl);
    $i = 0;
    $tot_debit = 0;
    $tot_credit = 0;
    db_conn('core');
    $Sl = "SELECT accnum FROM salacc WHERE name='salaries control'";
    $Rt = db_exec($Sl);
    $sd = pg_fetch_array($Rt);
    $salc = $sd['accnum'];
    $blocked = array();
    $cc_tot = 0;
    $sc_tot = 0;
    $sal_tot = 0;
    $i_tot = 0;
    $usednums_msg = $dupnums_msg = "";
    while ($fd = pg_fetch_array($Ri)) {
        $fid = $fd['id'];
        $bgcolor = bgcolor($i);
        $accnum_parts = explode("/", $fd["des1"]);
        $accnum = "{$fd['des1']}";
        if (substr($accounts[$fid], 0, 1) == "n") {
            $check_num = new dbSelect("accounts", "core", grp(m("where", wgrp(m("topacc", $accnum_parts[0]), m("accnum", $accnum_parts[1])))));
            $check_num->run();
        } else {
            $check_num = false;
        }
        $check_dup = new dbSelect("import_data", "cubit", grp(m("where", "des1='{$fd['des1']}' AND id!='{$fd['id']}'")));
        $check_dup->run();
        if ($check_num && $check_num->num_rows() > 0 || $check_dup->num_rows() > 0) {
            $mark = "";
            if ($check_dup->num_rows() > 0) {
                $mark .= IMP;
                $dupnums_msg = "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2' class='err'>Accounts marked with " . IMP . " have account numbers\n\t\t\t\t\t\tused by other accounts in the import. Please change them so all\n\t\t\t\t\t\taccounts have unique numbers.\n\t\t\t\t\t</tr>\n\t\t\t\t</tr>";
            }
            if ($check_num && $check_num->num_rows() > 0) {
                $mark .= REQ;
                $usednums_msg = "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2' class='err'>Accounts marked with " . REQ . " have account numbers\n\t\t\t\t\t\talready in use by Cubit. Either delete these accounts from Cubit or change the\n\t\t\t\t\t\taccount numbers in the fields provided.\n\t\t\t\t\t</td>\n\t\t\t\t</tr>";
            }
            $recommended_accnums = "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' class='err'><u><b>Recommended Account Numbers:</b></u></td>\n\t\t\t</tr>\n\t\t\t<tr class='err'>\n\t\t\t\t<td nowrap><b>Income Account</b>:</td>\n\t\t\t\t<td width='100%'>" . str_pad(MIN_INC, 4, '0', STR_PAD_LEFT) . "/000 <i>to</i> " . MAX_INC . "/999</td>\n\t\t\t</tr>\n\t\t\t<tr class='err'>\n\t\t\t\t<td nowrap><b>Expense Account</b>:</td>\n\t\t\t\t<td width='100%'>" . MIN_EXP . "/000 <i>to</i> " . MAX_EXP . "/999</td>\n\t\t\t</tr>\n\t\t\t<tr class='err'>\n\t\t\t\t<td nowrap><b>Balance Sheet Account</b>:</td>\n\t\t\t\t<td width='100%'>" . MIN_BAL . "/000 <i>to</i> " . MAX_BAL . "/999</td>\n\t\t\t</tr>";
            $accnum = "{$mark}\n\t\t\t\t<input type='text' size='4' name='topacc[{$fid}]' value='{$accnum_parts['0']}' /> /\n\t\t\t\t<input type='text' size='3' name='accnum[{$fid}]' value='{$accnum_parts['1']}' />";
        }
        if (substr($accounts[$fid], 0, 1) == "n") {
            switch (substr($accounts[$fid], 1, 1)) {
                case "1":
                    $catsa = array("-- INCOME", "other_income" => "Other Income", "sales" => "Sales");
                    break;
                case "2":
                    $catsa = array("-- EXPENSES", "expenses" => "Expenses", "cost_of_sales" => "Cost of Sales");
                    break;
                case "3":
                    $catsa = array("-- ASSETS", "fixed_asset" => "Fixed Assets", "investments" => "Investments", "other_fixed_asset" => "Other Fixed Assets", "current_asset" => "Current Assets", "-- EQUITY AND LIABILITIES", "share_capital" => "Share Capital", "retained_income" => "Retained Income", "shareholders_loan" => "Shareholders Loan", "non_current_liability" => "Non-current Liabilities", "long_term_borrowing" => "Long Term Borrowings", "other_long_term_liability" => "Other Long Term Liabilities", "current_liability" => "Current Liabilities");
            }
            $cats = "<select name='cat[{$fid}]'>";
            $optgrouped = false;
            foreach ($catsa as $dbval => $humanval) {
                if (isset($cat) && $cat[$fid] == "{$dbval}:{$humanval}") {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                if (substr($humanval, 0, 3) == "-- ") {
                    if ($optgrouped) {
                        $cats .= "</optgroup>";
                    }
                    $cats .= "<optgroup label='" . substr($humanval, 3) . "'>";
                    continue;
                }
                $cats .= "<option value='{$dbval}:{$humanval}' {$sel}>{$humanval}</option>";
            }
            if ($optgrouped) {
                $cats .= "</optgroup>";
            }
            $cats .= "</select>";
            $add = "{$cats}</td>";
        } else {
            $accounts[$fid] += 0;
            if (in_array($accounts[$fid], $blocked)) {
                $Sl = "SELECT accid,accname FROM accounts WHERE accid='{$accounts[$fid]}'";
                $Rx = db_exec($Sl);
                $ad = pg_fetch_array($Rx);
                return enter_data($_POST) . "<li class='err'>You cannot link an account to more than one account({$ad['accname']}).</li>";
            }
            $blocked[] = $accounts[$fid];
            $Sl = "SELECT accid,accname FROM accounts WHERE accid='{$accounts[$fid]}'";
            $Rx = db_exec($Sl);
            $ad = pg_fetch_array($Rx);
            $add = "{$ad['accname']}</td>";
            if ($ad['accid'] == $cc) {
                $cc_tot = sprint($fd['des3'] - $fd['des4']);
            }
            if ($ad['accid'] == $sc) {
                $sc_tot = sprint($fd['des4'] - $fd['des3']);
            }
            if ($ad['accid'] == $ic) {
                $i_tot = sprint($fd['des3'] - $fd['des4']);
            }
            if ($ad['accid'] == $salc) {
                $sal_tot = sprint($fd['des4'] - $fd['des3']);
            }
        }
        $out .= "\n\t\t\t<input type='hidden' name='accounts[{$fid}]' value='{$accounts[$fid]}' />\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$accnum}</td>\n\t\t\t\t<td>{$fd['des2']}</td>\n\t\t\t\t<td>{$fd['des3']}</td>\n\t\t\t\t<td>{$fd['des4']}</td>\n\t\t\t\t<td>{$add}</td>\n\t\t\t</tr>";
        $tot_debit += $fd['des3'];
        $tot_credit += $fd['des4'];
    }
    $tot_debit = sprint($tot_debit);
    $tot_credit = sprint($tot_credit);
    $out .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='2'>Total</td>\n\t\t\t<td align='right'>{$tot_debit}</td>\n\t\t\t<td align='right'>{$tot_credit}</td>\n\t\t</tr>";
    if ($cc_tot > 0) {
        db_conn('cubit');
        $Sl = "SELECT cusnum,accno,surname FROM customers ORDER BY surname";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>If you want to import your customer control account you need to add customers first</li>";
        }
        $out .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='4'><li class='err'>Please enter the customer balances to link up with 'Customer Control Account'</li></td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td colspan='10'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Acc No</th>\n\t\t\t\t\t\t\t<th>Customer</th>\n\t\t\t\t\t\t\t<th>Balance</th>\n\t\t\t\t\t\t</tr>";
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $cid = $cd['cusnum'];
            if (!isset($cbalance[$cid])) {
                $cbalance[$cid] = "";
            }
            $out .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$cd['accno']}</td>\n\t\t\t\t<td>{$cd['surname']}</td>\n\t\t\t\t<td><input type='text' size='12' name='cbalance[{$cid}]' value='{$cbalance[$cid]}'></td>\n\t\t\t</tr>";
        }
        $out .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'><b>Total</b></td>\n\t\t\t\t\t<td align='right'><b>" . CUR . " {$cc_tot}</b></td>\n\t\t\t\t</tr>\n\t\t\t</td>\n\t\t</tr>";
        $out .= "<tr><td><br></td></tr>";
    }
    if ($sc_tot > 0) {
        db_conn('cubit');
        $Sl = "SELECT supid,supno,supname FROM suppliers ORDER BY supname";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>If you want to import your supplier control account you need to add suppliers first</li>";
        }
        $out .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='4'><li class='err'>Please enter the supplier balances to link up with 'Supplier Control Account'</li></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 colspan='10'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Supplier No</th>\n\t\t\t\t\t\t\t<th>Supplier</th>\n\t\t\t\t\t\t\t<th>Balance</th>\n\t\t\t\t\t\t</tr>";
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $sid = $cd['supid'];
            if (!isset($sbalance[$sid])) {
                $sbalance[$sid] = "";
            }
            $out .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cd['supno']}</td>\n\t\t\t\t\t<td>{$cd['supname']}</td>\n\t\t\t\t\t<td><input type='text' size='12' name='sbalance[{$sid}]' value='{$sbalance[$sid]}'></td>\n\t\t\t\t</tr>";
        }
        $out .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='2'><b>Total</b></td>\n\t\t\t<td align='right'><b>" . CUR . " {$sc_tot}</b></td>\n\t\t</tr>";
        $out .= "\n\t\t</td></tr>";
        $out .= TBL_BR;
    }
    if ($sal_tot > 0) {
        $emps = qryEmployee();
        $out .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='4'><li class='err'>Please enter the employee balances to link up with 'Employees Control Account'</li></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 colspan='10'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Employee Number</th>\n\t\t\t\t\t\t\t<th>Employee</th>\n\t\t\t\t\t\t\t<th>Balance</th>\n\t\t\t\t\t\t</tr>";
        $tot = 0;
        while ($cd = $emps->fetch_array()) {
            $eid = $cd['empnum'];
            if (!isset($ebalance[$eid])) {
                $ebalance[$eid] = "";
            }
            $out .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cd['enum']}</td>\n\t\t\t\t\t<td>{$cd['sname']}, {$cd['fnames']}</td>\n\t\t\t\t\t<td><input type='text' size='12' name='ebalance[{$eid}]' value='{$ebalance[$eid]}'></td>\n\t\t\t\t</tr>";
            $i++;
        }
        $out .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='2'><b>Total</b></td>\n\t\t\t\t\t\t<td align='right'><b>" . CUR . " {$sal_tot}</b></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</td>\n\t\t\t</tr>";
        $out .= "<tr><td><br></td></tr>";
    }
    if ($i_tot > 0) {
        db_conn('cubit');
        $Sl = "SELECT stkid,stkcod,stkdes FROM stock ORDER BY stkcod";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>If you want to import your inventory control account you need to add stock first</li>";
        }
        $out .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='4'><li class='err'>Please enter the inventory balances to link up with 'Inventory Control Account'</li></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 colspan='10'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Stock Code</th>\n\t\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t\t<th>Balance(" . CUR . ")</th>\n\t\t\t\t\t\t\t<th>Units(Qty)</th>\n\t\t\t\t\t\t</tr>";
        $tot = 0;
        $stocktot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $iid = $cd['stkid'];
            if (!isset($ibalance[$iid])) {
                $ibalance[$iid] = "";
            }
            if (!isset($units[$iid])) {
                $units[$iid] = "";
            }
            #check if this stock item has balance,units
            $stksql = "SELECT units,balance FROM stock_tbimport WHERE stkid = '{$cd['stkid']}' LIMIT 1";
            $runstk = db_exec($stksql) or errDie("Unable to get stock information.");
            if (pg_numrows($runstk) > 0) {
                if (!isset($ibalance[$iid]) or strlen($ibalance[$iid]) < 1) {
                    $stkarr = pg_fetch_array($runstk);
                    $ibalance[$iid] = $stkarr['balance'];
                    $units[$iid] = $stkarr['units'];
                }
            }
            $out .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cd['stkcod']}</td>\n\t\t\t\t\t<td>{$cd['stkdes']}</td>\n\t\t\t\t\t<td><input type=text size=12 name=ibalance[{$iid}] value='{$ibalance[$iid]}'></td>\n\t\t\t\t\t<td><input type=text size=5 name=units[{$iid}] value='{$units[$iid]}'></td>\n\t\t\t\t</tr>";
            $stocktot = $stocktot + $ibalance[$iid];
            $i++;
        }
        $bgcolor = bgcolor($i);
        $stocktot = sprint($stocktot);
        $out .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='2'><b>Import Stock Total</b></td>\n\t\t\t\t\t\t<td align='right'><b>" . CUR . " {$stocktot}</b></td>\n\t\t\t\t\t\t<td></td>\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 colspan='2'><b>Total</b></td>\n\t\t\t\t\t\t<td align='right'><b>" . CUR . " {$i_tot}</b></td>\n\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</td>\n\t\t\t</tr>";
        $out .= TBL_BR;
    }
    $out .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t\t<td colspan='1' align='right'><input type='submit' value='Confirm &raquo;'></td>\n\t\t\t</tr>\n\t\t\t<input type='hidden' name='cc_tot' value='{$cc_tot}'>\n\t\t\t<input type='hidden' name='sal_tot' value='{$sal_tot}'>\n\t\t\t<input type='hidden' name='sc_tot' value='{$sc_tot}'>\n\t\t\t<input type='hidden' name='i_tot' value='{$i_tot}'>\n\t\t</form>\n\t\t</table>";
    if (!isset($recommended_accnums)) {
        $recommended_accnums = "";
    }
    $dispmsg = "\n\t\t<table " . TMPL_tblDflts . " width='600'>\n\t\t\t{$usednums_msg}\n\t\t\t{$dupnums_msg}\n\t\t\t" . TBL_BR . "\n\t\t\t{$recommended_accnums}\n\t\t\t" . TBL_BR . "\n\t\t</table>";
    $out = preg_replace("/%%USEDNUMS_MSG%%/", $dispmsg, $out);
    return $out;
}