function bank($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cashid, "num", 1, 20, "Invalid Reference number.");
    $v->isOk("{$date_day}{$date_month}{$date_year}", "num", 6, 8, "Invalid date selected.");
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->addError("", "Invalid date selected. No such date possible.");
    }
    # 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;
    }
    $seldate = "{$date_year}-{$date_month}-{$date_day}";
    $salconacc = gethook("accnum", "salacc", "name", "salaries control");
    # Get cash book record
    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 database11.", SELF);
    if (pg_numrows($accntRslt) < 1) {
        $OUTPUT = "<li clss='err'>The entry with reference number, <b>{$cashid}</b> was not found in Cubit.</li>";
        return $OUTPUT;
    }
    $accnt = pg_fetch_array($accntRslt);
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $bank = pg_fetch_array($rslt);
    # Date
    $sdate = date("Y-m-d");
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # If tis customer payment
    if (($accnt['cusnum'] > 0 || $accnt["multicusnum"] != "") && strlen($accnt['rinvids']) > 0) {
        db_connect();
        # Get invoice Ids and Amounts
        $invids = explode("|", $accnt['rinvids']);
        $amounts = explode("|", $accnt['amounts']);
        $invprds = explode("|", $accnt['invprds']);
        $rages = explode("|", $accnt['rages']);
        if ($accnt["multicusnum"] != "") {
            $cusnums = explode(",", $accnt["multicusnum"]);
            $cusamts = explode(",", $accnt["multicusamt"]);
        } else {
            $cusnums = array($accnt["cusnum"]);
            $cusamts = array($accnt["amount"]);
        }
        $oa = 0;
        # Return the amount that was surppose to be paid to invoices
        foreach ($invids as $key => $invid) {
            if ($invids[$key] <= 0) {
                continue;
            }
            db_connect();
            if (ext_ex("invoices", "invid", $invids[$key]) && $invprds[$key] != 0) {
                db_connect();
                $sql = "\n\t\t\t\t\tUPDATE invoices \n\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                if (open()) {
                    $sql = "SELECT invnum FROM invoices WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $idata = pg_fetch_array($payRslt);
                    $sql = "\n\t\t\t\t\t\tUPDATE open_stmnt \n\t\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\t\tWHERE invid = '{$idata['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $oa = $oa - $amounts[$key];
                }
            } else {
                if (ext_ex("nons_invoices", "invid", $invids[$key]) && $invprds[$key] == 0) {
                    db_connect();
                    $sql = "\n\t\t\t\t\tUPDATE nons_invoices \n\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    /*$Sll="SELECT sdate FROM nons_invoices WHERE invid = '$invids[$key]' AND div = '".USER_DIV."'";
                    		$Rii=db_exec($Sll) or errDie("Unable to get invoice data.");
                    		$dii=pg_fetch_array($Rii);*/
                    $cnsql = "SELECT cusid FROM cubit.nons_invoices WHERE invid='{$invids[$key]}'";
                    $cnrslt = db_exec($cnsql) or errDie("Error reading customer info from nonstock invoice.");
                    $invcusid = pg_fetch_result($cnrslt, 0, 0);
                    custDTA($amounts[$key], $invcusid, $rages[$key], $seldate);
                } else {
                    if ($invprds[$key] != 0 && ext_ex("pinvoices", "invid", $invids[$key], $invprds[$key])) {
                        $sql = "\n\t\t\t\t\tUPDATE \"{$invprds[$key]}\".pinvoices \n\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                        db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        $sql = "SELECT cusnum, balance FROM \"{$invprds[$key]}\".pinvoices WHERE invid='{$invids[$key]}'";
                        $rslt = db_exec($sql) or errDie("Error reading customer info from nonstock invoice.");
                        $invcusid = pg_fetch_result($rslt, 0, 0);
                        custDTA($amounts[$key], $invcusid, $rages[$key], $seldate);
                    } else {
                        if ($invprds[$key] > 0) {
                            if (open()) {
                                db_conn($invprds[$key]);
                                $sql = "SELECT invnum FROM  invoices WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                                $idata = pg_fetch_array($payRslt);
                                db_conn('cubit');
                                $sql = "\n\t\t\t\t\t\tUPDATE open_stmnt \n\t\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\t\tWHERE invid = '{$idata['invnum']}' AND div = '" . USER_DIV . "'";
                                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                                $oa = $oa - $amounts[$key];
                            }
                            db_conn($invprds[$key]);
                            # check if invoice exitsts on prd
                            if (ext_ex("invoices", "invid", $invids[$key])) {
                                # if found, Move the invoice back
                                if (moveback($invids[$key], $invprds[$key], $amounts[$key])) {
                                }
                            }
                        }
                    }
                }
            }
        }
        foreach ($cusnums as $cuskey => $cusnum) {
            $accnt["cusnum"] = $cusnum;
            $cusamt = $cusamts[$cuskey];
            db_connect();
            # Update the customer (make balance more)
            $sql = "UPDATE customers SET balance = (balance + '{$cusamt}'::numeric(13,2)) \n\t\t\t\t\tWHERE cusnum = '{$accnt['cusnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit1.", SELF);
            # Record the transaction on the statement
            $sql = "\n\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\tcusnum, invid, amount, date, type, \n\t\t\t\t\tdiv, allocation_date\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$accnt['cusnum']}', '0', '{$cusamt}', '{$seldate}', 'Cheque/Payment for Invoices Returned.', \n\t\t\t\t\t'" . USER_DIV . "', '{$accnt['date']}'\n\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            if (sprint($accnt['amount'] + $oa) > 0) {
                # Record the transaction on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, balance\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$accnt['cusnum']}', '0', '" . sprint($accnt['amount'] + $oa) . "', '{$seldate}', \n\t\t\t\t\t\t'Cheque/Payment for Invoices Returned.', '" . USER_DIV . "', '{$cusamt}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            }
        }
        # Delete cashbook ID
        $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        copyEntry($cashid);
        if ($accnt['lcashid'] > 0) {
            // Connect to database
            db_Connect();
            $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.2", SELF);
            $laccnt = pg_fetch_array($laccntRslt);
            $sql = "\n\t\t\t\tUPDATE bankacct \n\t\t\t\tSET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) \n\t\t\t\tWHERE bankid = '{$laccnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit2.", SELF);
            # Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        # Make ledge record
        //		custledger($accnt['cusnum'], $bank['accnum'], $accnt['date'], "cancel", "Payment Returned.", $accnt['amount'], "d");
        foreach ($cusnums as $cuskey => $cusnum) {
            $cusamt = $cusamts[$cuskey];
            custledger($cusnum, $bank['accnum'], $seldate, "cancel", "Payment Returned.", $cusamt, "d");
        }
        $descript = $accnt['descript'] . " Returned, Unpaid";
        $refnum = getrefnum();
        $date = date("Y-m-d");
        # debit customer account, credit bank account (customer takes money back)
        //		writetrans($accnt['accinv'], $bank['accnum'], $accnt['date'], $refnum, $accnt['amount'], $descript);
        writetrans($accnt['accinv'], $bank['accnum'], $seldate, $refnum, $accnt['amount'], $descript);
        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
        if ($accnt['vat'] != 0) {
            # DT(VAT), CT(Bank)
            writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
        }
    } else {
        if (($accnt['cusnum'] > 0 || $accnt["multicusnum"] != "") && $accnt['trantype'] != "withdrawal") {
            $refnum = getrefnum();
            $date = date("Y-m-d");
            //		recordDT($accnt['amount'], $accnt['cusnum']);
            recordCT($accnt['amount'], $accnt['cusnum']);
            if ($accnt["multicusnum"] != "") {
                $cusnums = explode(",", $accnt["multicusnum"]);
                $cusamts = explode(",", $accnt["multicusamt"]);
            } else {
                $cusnums = array($accnt["cusnum"]);
                $cusamts = array($accnt["amount"]);
            }
            db_connect();
            foreach ($cusnums as $cuskey => $cusnum) {
                $accnt["cusnum"] = $cusnum;
                $cusamt = $cusamts[$cuskey];
                # receipt from customer returned
                $sql = "\n\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t(cusnum, invid, amount, date, type, st, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$accnt['cusnum']}', '0', '{$cusamt}', '{$seldate}', 'Cheque/Payment returned', 'n', '" . USER_DIV . "', '{$accnt['date']}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                $sql = "INSERT INTO open_stmnt(cusnum, invid, amount, date, type, st, div,balance) VALUES('{$accnt['cusnum']}', '0', '{$cusamt}', '{$seldate}', '{$accnt['descript']}, Cheque/Payment returned', 'n', '" . USER_DIV . "','{$cusamt}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                # update the customer (make balance more)
                $sql = "UPDATE customers SET balance = (balance + '{$cusamt}') WHERE cusnum = '{$accnt['cusnum']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
            }
            copyEntry($cashid);
            foreach ($cusnums as $cuskey => $cusnum) {
                $cusamt = $cusamts[$cuskey];
                # Make ledge record
                //		custledger($accnt['cusnum'], $bank['accnum'], $accnt['date'], $refnum, "Cheque/Payment returned.", $accnt['amount'], "c");
                custledger($cusnum, $bank['accnum'], $seldate, $refnum, "Cheque/Payment returned.", $cusamt, "d");
            }
            db_conn('cubit');
            $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            //		writetrans ($accnt['accinv'],$bank['accnum'], $accnt['date'], $refnum, $accnt['amount'], "Cheque/Payment returned.$accnt[descript]");
            writetrans($accnt['accinv'], $bank['accnum'], $seldate, $refnum, $accnt['amount'], "Cheque/Payment returned.{$accnt['descript']}");
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            if ($accnt['vat'] != 0) {
                # DT(VAT), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
            }
        } elseif ($accnt['cusnum'] > 0) {
            $refnum = getrefnum();
            $date = date("Y-m-d");
            recordCT($accnt['amount'], $accnt['cusnum']);
            db_connect();
            # receipt from customer returned
            $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, amount, date, type, st, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$accnt['cusnum']}', '0', '-{$accnt['amount']}', '{$seldate}', 'Cheque/Payment returned', 'n', '" . USER_DIV . "', '{$accnt['date']}')";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            $sql = "INSERT INTO open_stmnt(cusnum, invid, amount, date, type, st, div,balance) VALUES('{$accnt['cusnum']}', '0', '-{$accnt['amount']}', '{$seldate}', '{$accnt['descript']}, Cheque/Payment returned', 'n', '" . USER_DIV . "','-{$accnt['amount']}')";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            # update the customer (make balance more)
            $sql = "UPDATE customers SET balance = (balance - '{$accnt['amount']}') WHERE cusnum = '{$accnt['cusnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
            copyEntry($cashid);
            # Make ledge record
            custledger($accnt['cusnum'], $bank['accnum'], $accnt['date'], $refnum, "Cheque/Payment returned.", $accnt['amount'], "c");
            db_conn('cubit');
            $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            //		writetrans ($bank['accnum'],$accnt['accinv'], $date, $refnum, $accnt['amount'], "Cheque/Payment returned.$accnt[descript]");
            writetrans($bank['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $accnt['amount'], "Cheque/Payment returned.{$accnt['descript']}");
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            if ($accnt['vat'] != 0) {
                # DT(VAT), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
            }
        } elseif ($accnt['supid'] > 0) {
            db_connect();
            $ids = explode("|", $accnt['ids']);
            $purids = explode("|", $accnt['purids']);
            $pamounts = explode("|", $accnt['pamounts']);
            $pdates = explode("|", $accnt['pdates']);
            if (count($ids) > 0) {
                foreach ($ids as $key => $vale) {
                    if ($ids[$key] > 0) {
                        rerecord($ids[$key], $accnt['supid'], $purids[$key], $pamounts[$key], $pdates[$key]);
                    }
                }
            }
            # if the amount was overpaid
            if (array_sum($pamounts) < $accnt['amount']) {
                # get and record amount that was overpaid to balance the equation
                $rem = $accnt['amount'] - array_sum($pamounts);
                rerecord('0', $accnt['supid'], '0', $rem, $accnt['date']);
            }
            # Update the supplier (make balance more)
            $sql = "UPDATE suppliers SET balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE supid = '{$accnt['supid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit3.", SELF);
            # Record the payment on the statement
            $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, ref, descript, amount, div) VALUES('{$accnt['supid']}', '{$seldate}', '{$bank['accnum']}', '{$accnt['cheqnum']}', 'Cheque/Payment to Supplier Returned.', '{$accnt['amount']}', '" . USER_DIV . "')";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            # Delete cashbook ID
            $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            copyEntry($cashid);
            if ($accnt['lcashid'] > 0) {
                // Connect to database
                db_Connect();
                $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database3.", SELF);
                $laccnt = pg_fetch_array($laccntRslt);
                $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.4", SELF);
                # Delete cashbook ID
                $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            }
            suppledger($accnt['supid'], $bank['accnum'], $accnt['date'], $accnt['cheqnum'], "Payment to Supplier Returned", $accnt['amount'], "c");
            db_connect();
            $descript = $accnt['descript'] . " Returned, Unpaid";
            $refnum = getrefnum();
            $date = date("Y-m-d");
            # debit bank, credit supplier account
            writetrans($bank['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $accnt['amount'], $descript);
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            if ($accnt['vat'] != 0) {
                # DT(VAT), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
            }
        } elseif ($accnt['suprec'] > 0) {
            db_connect();
            $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$accnt['suprec']}','-{$accnt['amount']}','{$accnt['date']}', 'Receipt Returned','{$accnt['cheqnum']}','0', '" . USER_DIV . "')";
            $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
            # Update the supplier (make balance less)
            $sql = "UPDATE suppliers SET balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE supid = '{$accnt['suprec']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.5", SELF);
            suppDT($accnt['amount'], $accnt['suprec']);
            suppledger($accnt['suprec'], $bank['accnum'], $accnt['date'], $accnt['cheqnum'], "Receipt from Supplier Returned", $accnt['amount'], "d");
            db_connect();
            # Delete cashbook ID
            $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            copyEntry($cashid);
            if ($accnt['lcashid'] > 0) {
                # Delete cashbook ID
                $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            }
            $descript = $accnt['descript'] . " Returned, Unpaid";
            $refnum = getrefnum();
            $date = date("Y-m-d");
            # debit bank, credit supplier account
            writetrans($accnt['accinv'], $bank['accnum'], $accnt['date'], $refnum, $accnt['amount'], $descript);
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            if ($accnt['vat'] != 0) {
                # DT(VAT), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
            }
        } else {
            if ($accnt["empnum"] != "0" && strlen($accnt["empnum"]) > 0 && $accnt['trantype'] == "withdrawal") {
                $refnum = getrefnum();
                $date = date("Y-m-d");
                $sql = "UPDATE cubit.employees SET balance = balance + '{$accnt['amount']}' \n\t\t\t\tWHERE empnum='{$accnt['empnum']}' AND div = '" . USER_DIV . "'";
                db_exec($sql) or errDie("Unable to get employee details.");
                $sql = "SELECT fnames,sname FROM cubit.employees WHERE empnum='{$accnt['empnum']}'";
                $rslt = db_exec($sql);
                $empinfo = pg_fetch_array($rslt);
                $empname = "{$empinfo['fnames']} {$empinfo['sname']}";
                copyEntry($cashid);
                empledger($accnt["empnum"], $bank['accnum'], $accnt["date"], $refnum, "Cheque/Payment Returned", $accnt['amount'], "c");
                db_conn('cubit');
                $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
                writetrans($bank['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $accnt['amount'], "Cheque/Payment returned for {$empname}");
            } elseif (strlen($accnt['accids']) > 0) {
                /* -- Start Hooks -- */
                $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                /* -- End Hooks -- */
                multican($accnt, $bank, $vatacc, $accnt['vatcode']);
            } else {
                $amount = $accnt['amount'];
                $vat = $accnt['vat'];
                $chrgvat = $accnt['chrgvat'];
                $amount -= $vat;
                /* -- Start Hooks -- */
                $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                /* -- End Hooks -- */
                db_connect();
                # Delete cashbook ID
                $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
                copyEntry($cashid);
                if ($accnt['trantype'] == "deposit") {
                    $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$accnt['famount']}'::numeric(13,2)), balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
                    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.5", SELF);
                } else {
                    $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
                    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.6", SELF);
                }
                /* ---- the Others ---- */
                if ($accnt['lcashid'] > 0) {
                    //Connect to database
                    db_Connect();
                    $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                    $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.4", SELF);
                    $laccnt = pg_fetch_array($laccntRslt);
                    if ($laccnt['trantype'] == "deposit") {
                        $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$laccnt['famount']}'::numeric(13,2)), balance = (balance - '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.7", SELF);
                    } else {
                        $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.8", SELF);
                    }
                    # Delete cashbook ID
                    $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                    $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
                    /* ---- End the Others ---- */
                }
                $descript = $accnt['descript'] . " Returned, Unpaid";
                $refnum = getrefnum();
                $date = date("Y-m-d");
                if ($accnt['trantype'] == "deposit") {
                    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "a");
                    # DT(account involved), CT(bank)
                    //			writetrans($accnt['accinv'], $bank['accnum'], $accnt['date'], $refnum, $amount, $descript);
                    writetrans($accnt['accinv'], $bank['accnum'], $seldate, $refnum, $amount, $descript);
                    if ($vat != 0) {
                        # DT(Vat), CT(Bank)
                        db_conn('cubit');
                        $Sl = "SELECT * FROM vatcodes WHERE id='{$accnt['vatcode']}'";
                        $Ri = db_exec($Sl);
                        $vd = pg_fetch_array($Ri);
                        //				vatr($vd['id'],$date,"OUTPUT",$vd['code'],$refnum,$descript,-($amount+$vat),-$vat);
                        vatr($vd['id'], $seldate, "OUTPUT", $vd['code'], $refnum, $descript, -($amount + $vat), -$vat);
                        //				writetrans($vatacc, $bank['accnum'], $accnt['date'], $refnum, $vat, $descript);
                        writetrans($vatacc, $bank['accnum'], $seldate, $refnum, $vat, $descript);
                    }
                    $cc_trantype = cc_TranTypeAcc($accnt['accinv'], $bank['accnum']);
                } else {
                    # DT(bank), CT(account invoilved)
                    //			writetrans($bank['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $amount, $descript);
                    writetrans($bank['accnum'], $accnt['accinv'], $seldate, $refnum, $amount, $descript);
                    if ($vat != 0) {
                        # DT(Vat), CT(Bank)
                        db_conn('cubit');
                        $Sl = "SELECT * FROM vatcodes WHERE id='{$accnt['vatcode']}'";
                        $Ri = db_exec($Sl);
                        $vd = pg_fetch_array($Ri);
                        //				vatr($vd['id'],$date,"INPUT",$vd['code'],$refnum,$descript,($amount+$vat),$vat);
                        vatr($vd['id'], $seldate, "INPUT", $vd['code'], $refnum, $descript, $amount + $vat, $vat);
                        //				writetrans($bank['accnum'], $vatacc, $accnt['date'], $refnum, $vat, $descript);
                        writetrans($bank['accnum'], $vatacc, $seldate, $refnum, $vat, $descript);
                    }
                    $cc_trantype = cc_TranTypeAcc($bank['accnum'], $accnt['accinv']);
                }
                /* stock purchase/sale */
                if (!empty($accnt["stkinfo"])) {
                    list($si_stkid, $si_unitnum, $si_cost, $si_vat) = explode("|", $accnt["stkinfo"]);
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                    $stk = pg_fetch_array($stkRslt);
                    if ($accnt['trantype'] == "deposit") {
                        db_connect();
                        $sql = "UPDATE stock SET csamt = (csamt + '{$si_cost}'), \n\t\t\t\t\t\t\tunits = (units + '{$si_unitnum}') \n\t\t\t\t\t\tWHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                        $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $seldate, $si_unitnum, $si_cost, "Returned receipt for: {$accnt['descript']}");
                        db_connect();
                        $cspric = sprint($si_cost / $si_unitnum);
                        $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\t\t\tVALUES('{$seldate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'inc', '{$si_unitnum}', '{$si_cost}', '{$cspric}', 'Returned receipt for: {$accnt['descript']}', '" . USER_DIV . "')";
                        $recRslt = db_exec($sql);
                        db_connect();
                        $sql = "SELECT * FROM stock WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                        $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                        $stk = pg_fetch_array($stkRslt);
                        if ($stk['units'] != 0) {
                            $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        } else {
                            $csprice = sprint($si_cost / $si_unitnum);
                            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        }
                    } else {
                        db_connect();
                        $sql = "UPDATE stock SET csamt = (csamt - {$si_cost}), \n\t\t\t\t\t\t\tunits = (units - '{$si_unitnum}') \n\t\t\t\t\t\tWHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                        $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $seldate, $si_unitnum, $si_cost, "Returned payment for: {$accnt['descript']}");
                        db_connect();
                        $cspric = sprint($si_cost / $si_unitnum);
                        $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\t\t\tVALUES('{$seldate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'dec', '-{$si_unitnum}', '{$si_cost}', '{$cspric}', 'Returned payment for: {$accnt['descript']}', '" . USER_DIV . "')";
                        $recRslt = db_exec($sql);
                        db_connect();
                        $sql = "SELECT * FROM stock WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                        $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                        $stk = pg_fetch_array($stkRslt);
                        if ($stk['units'] != 0) {
                            $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        } else {
                            $csprice = sprint($si_cost / $si_unitnum);
                            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        }
                    }
                }
            }
        }
    }
    if (isset($cc_trantype) && $cc_trantype != false) {
        $cc = "<script> CostCenter('{$cc_trantype}', 'Returned, Unpaid Bank Transaction', '{$seldate}', '{$descript}', '" . ($accnt['amount'] - $accnt['vat']) . "', '../'); </script>";
    } else {
        $cc = "";
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Status report
    $bank = "\n\t\t\t{$cc}\n\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Cash Book</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>Cash Book Entry was successfully canceled .</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    # Main table (layout with menu)
    $OUTPUT = "\n\t\t\t<center>\n\t\t\t<table width='90%'>\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td width='60%'>{$bank}</td>\n\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='cashbook-view.php'>View Cash Book</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='../reporting/not-banked.php'>View Outstanding Cash Book Entries</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='bank-pay-add.php'>Add Bank Payment</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='bank-recpt-add.php'>Add Bank Receipt</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    return $OUTPUT;
}
function package($_POST)
{
    $_POST = var_makesafe($_POST);
    extract($_POST);
    $week += 0;
    if (isset($back)) {
        return process($_POST);
    }
    $annual += 0;
    $bonus += 0;
    $paye_salary += 0;
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    $v->isOk($accid, "num", 1, 20, "Invalid bank number.");
    $v->isOk($MON, "num", 1, 2, "Invalid month.");
    $v->isOk($basic_sal, "float", 1, 20, "Invalid basic salary.");
    $v->isOk($overamt, "float", 1, 20, "Invalid overtime amount.");
    $v->isOk($income, "float", 1, 20, "Invalid income.");
    $v->isOk($commission, "float", 0, 20, "Invalid commision.");
    $v->isOk($loaninstall, "float", 0, 20, "Invalid loan installment.");
    $v->isOk($paidamount, "float", 1, 20, "Invalid paid amount.");
    if (isset($allowances)) {
        foreach ($allowances as $key => $value) {
            $v->isOk($allowances[$key], "float", 0, 20, "Invalid allowance amount " . ($key + 1) . ".");
        }
    }
    if (isset($deductid)) {
        foreach ($deductid as $key => $value) {
            $v->isOk($deductid[$key], "num", 1, 20, "Invalid deductions ID.");
        }
    }
    if (isset($deductions)) {
        foreach ($deductions as $key => $value) {
            $v->isOk($deductions[$key], "float", 0, 20, "Invalid deduction amount" . ($key + 1) . ".");
        }
    }
    if (isset($allowid)) {
        foreach ($allowid as $key => $value) {
            $v->isOk($allowid[$key], "num", 1, 20, "Invalid allowance ID.");
        }
    }
    if (isset($allowtax)) {
        foreach ($allowtax as $key => $value) {
            $v->isOk($allowtax[$key], "string", 2, 20, "Invalid allowance tax " . ($key + 1) . ".");
        }
    }
    $ydate = $year . "-" . $mon . "-" . $day;
    $ddate = $day . "-" . $mon . "-" . $year;
    if (!checkdate($mon, $day, $year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    $mon = $MON;
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    db_conn('cubit');
    $nettpay = $income;
    $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.";
    }
    $ecost = 0;
    $myEmp = pg_fetch_array($empRslt);
    // fringe benefits
    $i = 0;
    $fringes = "";
    $fringes_desc = "";
    if (isset($fringebens)) {
        foreach ($fringebens as $key => $value) {
            if ($fringebens[$key] > 0) {
                $fringes_desc .= "\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$fringename[$key]}</td>\r\n\t\t\t\t\t<td>" . CUR . " {$fringebens[$key]}</td>\r\n\t\t\t\t</tr>";
            }
        }
    }
    if (!empty($fringes_desc)) {
        $fringes_desc = "<tr><th colspan=2>Fringe Benefits</th></tr>{$fringes_desc}";
    }
    $all_before = "";
    $all_after = "";
    $all_beforeamount = 0;
    $all_afteramount = 0;
    if (isset($allowtax)) {
        foreach ($allowtax as $key => $perc) {
            if ($perc == "Yes" and $allowances[$key] > 0) {
                $all_before .= "<tr><td>{$allowname[$key]}</td><td align=right>" . CUR . " {$allowances[$key]}</td></tr>";
                $all_beforeamount = $all_beforeamount + $allowances[$key];
            } elseif ($allowances[$key] > 0) {
                $all_after .= "<tr><td>{$allowname[$key]}</td><td align=right>" . CUR . " {$allowances[$key]}</td></tr>";
                $all_afteramount = $all_afteramount + $allowances[$key];
            }
        }
    }
    $de_before = "\r\n\t\t<tr>\r\n\t\t\t<td colspan='2'>\r\n\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Details</th>\r\n\t\t\t\t\t\t<th>Employee Contribution</th>\r\n\t\t\t\t\t\t<!--<th>Employer Contribution</th>//-->\r\n\t\t\t\t\t</tr>";
    $de_after = "\r\n\t\t<tr>\r\n\t\t\t<td colspan='2'>\r\n\t\t\t\t<table " . TMPL_tblDflts . ">\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<th>Details</th>\r\n\t\t\t\t\t\t<th>Employee Contribution</th>\r\n\t\t\t\t\t\t<!--<th>Employer Contribution</th>//-->\r\n\t\t\t\t\t</tr>";
    $de_beforeamount = 0;
    $de_afteramount = 0;
    $de_beforeamount_emp = 0;
    $de_afteramount_emp = 0;
    if (isset($deducttax)) {
        foreach ($deducttax as $key => $perc) {
            if ($perc == "Yes" and $deductions[$key] > 0) {
                $de_before .= "\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td>{$deductname[$key]}</td>\r\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$deductions[$key]}</td>\r\n<!--\t\t\t\t\t<td align='right'>" . CUR . " {$employer_deductions[$key]}</td> //-->\r\n\t\t\t\t\t</tr>";
                $de_beforeamount = $de_beforeamount + $deductions[$key] + $employer_deductions[$key];
                $de_beforeamount_emp += $employer_deductions[$key];
            } elseif ($deductions[$key] > 0) {
                $de_after .= "\r\n\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t<td>{$deductname[$key]}</td>\r\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$deductions[$key]}</td>\r\n<!--\t\t\t\t\t<td align='right'>" . CUR . " {$employer_deductions[$key]}</td> //-->\r\n\t\t\t\t\t</tr>";
                $de_afteramount = $de_afteramount + $deductions[$key] + $employer_deductions[$key];
                $de_afteramount_emp += $employer_deductions[$key];
            }
        }
    }
    $de_before .= "</table></td></tr>";
    $de_after .= "</table></td></tr>";
    if ($all_beforeamount > 0) {
        $all_before = "<tr><td colspan='2'>Allowances</td></tr>" . $all_before;
    }
    if ($all_afteramount > 0) {
        $all_after = "<tr><td colspan='2'>Allowances</td></tr>" . $all_after;
    }
    if ($de_beforeamount > 0) {
        $de_before = "<tr><td colspan='2'>Deductions</td></tr>" . $de_before;
    }
    if ($de_afteramount > 0) {
        $de_after = "<tr><td colspan='2'>Deductions</td></tr>" . $de_after;
    }
    $gros_sal = sprint($grossal);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.";
    }
    $bank = pg_fetch_array($rslt);
    $bankacc = $bank["accnum"];
    $basic_sal = sprint($basic_sal);
    $commission = sprint($commission);
    $overamt = sprint($overamt);
    $paye = sprint($paye);
    $nettpay = sprint($nettpay);
    $date = date("d-m-Y");
    $sdl = sprint($comp_sdl);
    $amount = sprint($gros_sal + $comp_pension + $comp_provident + $comp_medical + $comp_other + $comp_uif + $comp_ret + $sdl);
    $loaninstall = sprint($loaninstall);
    //Original CC
    //$cc = "<script> CostCenter('ct', 'Salaries', '$date', 'Salary Payment for employee,  $myEmp[fnames] $myEmp[sname]', '$amount', '../'); </script>";
    //New CC
    $cc = "CostCenter('ct', 'Salaries', '{$date}', 'Salary Payment for employee,  {$myEmp['fnames']} {$myEmp['sname']}', '{$amount}', '../'); ";
    $ecost = $amount;
    if ($commission > 0) {
        $comDis = "<tr><td>Commission</td><td align='right'>" . CUR . " {$commission}</td></tr>";
    } else {
        $comDis = "";
    }
    if ($overamt > 0) {
        $oveDis = "<tr><td>Overtime</td><td align='right'>" . CUR . " {$overamt}</td></tr>";
    } else {
        $oveDis = "";
    }
    if ($loaninstall > 0) {
        $loaDis = "<tr><td>Loan Instalment</td><td align='right'>" . CUR . " {$loaninstall}</td></tr>";
    } else {
        $loaDis = "";
    }
    if ($basic_sal != $gros_sal) {
        $groDis = "<tr><td>Gross Salary</td><td align='right'>" . CUR . " {$gros_sal}</td></tr>";
    } else {
        $groDis = "";
    }
    if ($all_travel > 0) {
        $talDis = "<tr><td>Travel Allowance</td><td align='right'>" . CUR . " {$all_travel}</td></tr>";
    } else {
        $talDis = "";
    }
    db_connect();
    $Sl = "SELECT * FROM salset";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        $con = true;
    } else {
        $con = false;
    }
    $intrec = gethook("accnum", "salacc", "name", "interestreceived");
    $uifbal = gethook("accnum", "salacc", "name", "uifbal");
    $sdlbal = gethook("accnum", "salacc", "name", "sdlbal");
    $pa = gethook("accnum", "salacc", "name", "pension");
    $ma = gethook("accnum", "salacc", "name", "medical");
    $cash_account = gethook("accnum", "salacc", "name", "cash");
    $retire = gethook("accnum", "salacc", "name", "retire");
    $provident = gethook("accnum", "salacc", "name", "provident");
    $salconacc = gethook("accnum", "salacc", "name", "salaries control");
    $commacc = gethook("accnum", "salacc", "name", "Commission");
    $payeacc = gethook("accnum", "salacc", "name", "PAYE");
    $uifacc = gethook("accnum", "salacc", "name", "UIF");
    $providente = $myEmp["expacc_provident"];
    $retiree = $myEmp["expacc_ret"];
    $pax = $myEmp["expacc_pension"];
    $uifexp = $myEmp["expacc_uif"];
    $max = $myEmp["expacc_medical"];
    $dedgenerale = $myEmp["expacc_other"];
    $sdlexp = $myEmp["expacc_sdl"];
    $salacc = $myEmp["expacc_salwages"];
    $loanexp = $myEmp["expacc_loan"];
    if ($con) {
        $uifexp = $salacc;
        $sdlexp = $salacc;
        $pax = $salacc;
        $max = $salacc;
        $retiree = $salacc;
    }
    // Get Bank account [the traditional way re: hook of hook]
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accid}' AND div = '" . USER_DIV . "'";
    $Rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($Rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $bank = pg_fetch_array($Rslt);
    # date(todays date)
    $date = $ddate;
    $refnum = getrefnum($date);
    # Debit uif acc and credit uif control acc
    if ($comp_uif > 0) {
        writetrans($uifexp, $uifbal, $date, $refnum, $comp_uif, "Company UIF Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_uif > 0) {
        db_conn("cubit");
        $Sl = "UPDATE employees SET balance=balance-({$emp_uif}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $uifacc, $ydate, $refnum, "UIF", $emp_uif, "d");
        writetrans($salconacc, $uifbal, $date, $refnum, $emp_uif, "Employee UIF Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    # Debit uif sdl and credit sdl control acc
    writetrans($sdlexp, $sdlbal, $date, $refnum, $sdl, "SDL,  {$myEmp['fnames']} {$myEmp['sname']}.");
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    db_conn('cubit');
    $Sl = "UPDATE employees SET balance=balance+({$grossal_nodedall}) WHERE empnum = '{$empnum}'";
    $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
    empledger($empnum, $salacc, $ydate, $refnum, "Gross Salary", $grossal_nodedall, "c");
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    # Debit salaries acc and credit salaries control acc
    writetrans($salacc, $salconacc, $date, $refnum, $grossal_nodedall, "Gross Salary proccessing for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    if ($commission > 0) {
        if ($con) {
            $commacc = $salacc;
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance+({$commission}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $commacc, $ydate, $refnum, "Commission", $commission, "c");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit commission acc and credit salaries control acc
        writetrans($commacc, $salconacc, $date, $refnum, $commission, "Commission for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($paye > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paye}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $payeacc, $ydate, $refnum, "PAYE", $paye, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit salaries control acc and credit PAYE control acc
        writetrans($salconacc, $payeacc, $date, $refnum, $paye, "PAYE for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    db_conn('cubit');
    // fringe benefits
    if (isset($fringeid)) {
        foreach ($fringeid as $i => $id) {
            //			empledger($empnum, $fringeaccs[$i], $ydate, $refnum,"Fringe Benefit, $fringename[$i]" , $fringebens[$i], "d");
            //			writetrans($salconacc, $fringeaccs[$i], $date, $refnum, $fringebens[$i], "Fringe Benefit for employee, $myEmp[fnames] $myEmp[sname].");
        }
    }
    if ($fringe_medical > 0) {
        //		empledger($empnum, $fringe_medexp, $ydate, $refnum,"Medical Fringe Benefit" , $fringe_medical, "d");
        //		writetrans($salconacc, $fringe_medexp, $date, $refnum, $fringe_medical, "Fringe Benefit for employee, $myEmp[fnames] $myEmp[sname].");
    }
    if ($fringe_car1 > 0) {
        //		empledger($empnum, $fringe_carexp, $ydate, $refnum,"Motor Vehicle 1 Fringe Benefit" , $fringe_car1, "d");
        //		writetrans($salconacc, $fringe_carexp, $date, $refnum, $fringe_car1, "Car Fringe Benefit for employee, $myEmp[fnames] $myEmp[sname].");
    }
    if ($fringe_car2 > 0) {
        //		empledger($empnum, $fringe_carexp, $ydate, $refnum,"Motor Vehicle 2 Fringe Benefit" , $fringe_car2, "d");
        //		writetrans($salconacc, $fringe_carexp, $date, $refnum, $fringe_car2, "Car Fringe Benefit for employee, $myEmp[fnames] $myEmp[sname].");
    }
    if ($fringe_loan > 0) {
        //		empledger($empnum, $fringe_loanexp, $ydate, $refnum,"Loan Interest Fringe Benefit" , $fringe_loan, "d");
        //		writetrans($salconacc, $fringe_loanexp, $date, $refnum, $fringe_loan, "Loan Interest Benefit for employee, $myEmp[fnames] $myEmp[sname].");
    }
    # Pay allowances accounts
    if (isset($allowid)) {
        foreach ($allowid as $i => $id) {
            # Debit allowances acc and credit salaries control acc
            if ($con) {
                $allowaccs[$i] = $salacc;
            }
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance+({$allowances[$i]}) WHERE empnum = '{$empnum}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($empnum, $allowaccs[$i], $ydate, $refnum, "Allowance", $allowances[$i], "c");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($allowaccs[$i], $salconacc, $date, $refnum, $allowances[$i], "Allowances for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
        }
    }
    # Pay Deductions accounts
    if (isset($deductid)) {
        foreach ($deductid as $i => $id) {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance-({$deductions[$i]}) WHERE empnum = '{$empnum}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($empnum, $dedaccs[$i], $ydate, $refnum, "Deduction", $deductions[$i], "d");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            # Debit salaries control acc and credit  acc
            // salcon acc - ded balance acc
            writetrans($salconacc, $dedaccs[$i], $date, $refnum, $deductions[$i], "Deductions for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
            db_conn("cubit");
            $sql = "SELECT * FROM salded WHERE id='{$id}'";
            $rslt = db_exec($sql) or errDie("Error reading deduction information.");
            $dedinfo = pg_fetch_array($rslt);
            /*
            			if ( $employer_deductions[$i] > 0 && $dedinfo["creditor"] != "In House" ) {
            				// ded exp acc - ded balance acc
            				writetrans($dedaccs[$i], $bal_dedaccs[$i], $date, $refnum, $employer_deductions[$i], "Company Contribution to Deductions for employee, $myEmp[fnames] $myEmp[sname].");
            			}*/
        }
    }
    if ($comp_pension > 0) {
        writetrans($pax, $pa, $date, $refnum, $comp_pension, "Company Pension Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_pension > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_pension}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $pa, $ydate, $refnum, "Pension Contribution", $emp_pension, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $pa, $date, $refnum, $emp_pension, "Pension Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($comp_medical > 0) {
        writetrans($max, $ma, $date, $refnum, $comp_medical, "Company Medical Aid Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_medical > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_medical}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $ma, $ydate, $refnum, "Medical Aid Contribution", $emp_medical, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $ma, $date, $refnum, $emp_medical, "Employee Medical Aid Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($comp_provident > 0) {
        writetrans($providente, $provident, $date, $refnum, $comp_provident, "Company Provident Fund Contribution, {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_provident > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_provident}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $provident, $ydate, $refnum, "Provident Fund Contribution", $emp_provident, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $provident, $date, $refnum, $emp_provident, "Provident Fund Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if (false && $comp_other > 0) {
        writetrans($dedgenerale, $dedgeneral, $date, $refnum, $comp_other, "Company Contribution to Other Deductions, {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if (false && $emp_other > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_other}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $dedgeneral, $ydate, $refnum, "Other Deductions Contribution", $emp_other, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $dedgeneral, $date, $refnum, $emp_other, "Other Deductions Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_ret > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_ret}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $retire, $ydate, $refnum, "Retirement Annuity Contribution", $emp_ret, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $retire, $date, $refnum, $emp_ret, "Employee Retirement Annuity Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($comp_ret > 0) {
        writetrans($retiree, $retire, $date, $refnum, $comp_ret, "Company Retirement Annuity Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    db_conn('cubit');
    $mons = "{$mon};";
    $due = sprint($nettpay - $paidamount);
    //, balance=balance+'$due
    $sql = "UPDATE employees SET lastpay = '{$mons}',\r\n\t\t\t\tloanamt = (loanamt - cast(float '{$loaninstall}' as numeric)),\r\n\t\t\t\tloanfringe = (loanfringe - cast(float '{$fringe_loan}' as numeric))\r\n\t\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to get employee details.");
    // check if loan is 0, then unmark loan as active, and store in archive
    $sql = "SELECT loanid FROM employees WHERE loanamt=0 AND empnum='{$empnum}' AND gotloan='t'::bool";
    $rslt = db_exec($sql) or errDie("Error reading employee details for loan.");
    if (pg_num_rows($rslt) > 0) {
        $loanid = pg_fetch_result($rslt, 0, 0);
        $sql = "UPDATE employees SET gotloan='f'::bool, loaninstall='0'\r\n\t\t\t\tWHERE empnum='{$empnum}'";
        $rslt = db_exec($sql) or errDie("Unable to update employee loan status.");
        $sql = "UPDATE emp_loanarchive SET donedata=CURRENT_DATE WHERE id='{$loanid}'";
        $rslt = db_exec($sql) or errDie("Unable to archive loan.");
        $sql = "SELECT loanint_unpaid FROM employees WHERE empnum='{$empnum}'";
        $rslt = db_exec($sql) or errDie("Error reading loan interest for installment.");
        $loanint = sprint(pg_fetch_result($rslt, 0, 0));
    } else {
        if ($loaninstall > 0) {
            $sql = "SELECT loanamt_tot, loanint_amt FROM employees WHERE empnum='{$empnum}'";
            $rslt = db_exec($sql) or errDie("Error reading loan interest for installment.");
            $loan_tot = pg_fetch_result($rslt, 0, 0);
            $loan_totint = pg_fetch_result($rslt, 0, 1);
            $loanint = sprint($loaninstall / $loan_tot * $loan_totint);
        } else {
            $loanint = 0;
        }
    }
    $sql = "UPDATE employees SET loanint_unpaid = (loanint_unpaid - cast(float '{$loanint}' as numeric))\r\n\t\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update employee interest.");
    if ($loaninstall > 0 && !empty($loanexp)) {
        $loaninstall += 0;
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$loaninstall}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $loanexp, $ydate, $refnum, "Loan Instalment", $loaninstall, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit salaries control acc and credit loan control acc
        writetrans($salconacc, $loanexp, $date, $refnum, $loaninstall - $loanint, "Loan Installment for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
        writetrans($salconacc, $intrec, $date, $refnum, $loanint, "Loan Interest for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    $loaninstall = $loaninstall + 0;
    $totded = $de_beforeamount + $de_afteramount + $emp_pension + $emp_medical + $emp_provident + $emp_ret + $emp_other;
    $totded_employer = $de_beforeamount_emp + $de_afteramount_emp + $comp_pension + $comp_medical + $comp_provident + $comp_ret + $comp_other;
    $totall = $all_beforeamount + $all_afteramount;
    $parkage = "\r\n\t\t<br><br>\r\n\t\t<center>\r\n\t\t{$cc}\r\n\t\t<table border='2' cellpadding='4' cellspacing='0' width='750' bordercolor='#000000'>\r\n\t        <tr>\r\n\t        \t<td align='center'><b>Description</b></td>\r\n\t        \t<td width='100' align='center'><b>Amount</b></td>\r\n\t        </tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>Basic salary</td>\r\n\t\t\t\t<td align='right'>" . CUR . " {$basic_sal}</td>\r\n\t\t\t</tr>\r\n\t\t\t{$comDis}\r\n\t\t\t{$fringes_desc}\r\n\t\t\t{$all_before}\r\n\t\t\t{$de_before}\r\n\t\t\t{$groDis}\r\n\t\t\t{$talDis}\r\n\t\t\t<tr><td>UIF</td><td align='right'>" . CUR . " {$emp_uif}</td></tr>\r\n\t\t\t<tr><td>PAYE</td><td align='right'>" . CUR . " {$paye}</td></tr>\r\n\t\t\t{$loaDis}\r\n\t\t\t{$all_after}\r\n\t\t\t{$de_after}\r\n\t\t\t<tr><td><b>Nett Pay</b></td><td align='right'><b>" . CUR . " {$nettpay}</b></td></tr>\r\n\t\t\t</form>\r\n\t\t</table>\r\n\t\t</center>";
    $parkagesave = "\r\n\t\t<br><br>\r\n\t\t<center>\r\n\t\t<table border='2' width='750' border=2 cellpadding='4' cellspacing='0' bordercolor='#000000'>\r\n\t\t\t<tr>\r\n\t\t\t\t<td align='center'><b>Description</b></td>\r\n\t\t\t\t<td width='100' align='center'><b>Amount</b></td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td>Basic salary</td>\r\n\t\t\t\t<td align='right'>" . CUR . " {$basic_sal}</td>\r\n\t\t\t</tr>\r\n\t\t\t{$comDis}\r\n\t\t\t{$fringes_desc}\r\n\t\t\t{$all_before}\r\n\t\t\t{$de_before}\r\n\t\t\t{$groDis}\r\n\t\t\t{$talDis}\r\n\t\t\t<tr><td>UIF</td><td align='right'>" . CUR . " {$emp_uif}</td></tr>\r\n\t\t\t<tr><td>PAYE</td><td align='right'>" . CUR . " {$paye}</td></tr>\r\n\t\t\t{$loaDis}\r\n\t\t\t{$all_after}\r\n\t\t\t{$de_after}\r\n\t\t\t<tr><td><b>Nett Pay</b></td><td align='right'><b>" . CUR . " {$nettpay}</b></td></tr>\r\n\t\t</form>\r\n\t\t</table>\r\n\t\t</center>";
    $OUTPUT = $parkage;
    $save = base64_encode($parkagesave);
    $Date = $ydate;
    $np = $nettpay;
    if (isset($rbsa)) {
        $np = sprint($np - array_sum($rbsa));
    }
    db_conn("cubit");
    $Sl = "\r\n       \t\tINSERT INTO salpaid (\r\n       \t\t\tempnum, month, bankid, salary, comm, uifperc, uif, payeperc, paye, totded, \r\n       \t\t\ttotded_employer, totallow, loanins, div, display, saldate, week\r\n       \t\t) VALUES (\r\n       \t\t\t'{$empnum}', '{$mon}', '{$accid}', '{$np}', '{$commission}', '0', '{$emp_uif}', '0', '{$paye}', '{$totded}', \r\n       \t\t\t'{$totded_employer}', '{$totall}', '{$loaninstall}', '" . USER_DIV . "','{$save}','{$Date}','{$week}'\r\n       \t\t)";
    $Ry = db_exec($Sl) or errDie("Unable to insert record.");
    $id = pglib_lastid("salpaid", "id");
    $year = $year;
    $payslip_id = $id;
    db_conn('cubit');
    $Sl = "SELECT * FROM rbs ORDER BY name";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    $i = 0;
    if (pg_num_rows($Ri) > 0) {
        while ($td = pg_fetch_array($Ri)) {
            if (!isset($rbsa[$td['id']]) || $rbsa[$td['id']] < 1) {
                continue;
            }
            db_conn('cubit');
            $rbsa[$td['id']] = sprint($rbsa[$td['id']]);
            //$rt.="<tr class='".bg_class()."'>
            //<td><input type=hidden name='rbs[$td[id]]' value='$td[id]'>$td[name]</td>
            //<td>".CUR." <input type=hidden name='rbsa[$td[id]]' value='".$rbsa[$td['id']]."'>".$rbsa[$td['id']]."</td></tr>";
            $rb = $rbsa[$td['id']];
            $i++;
            $Sl = "\r\n\t\t\t\tINSERT INTO emp_inc (\r\n\t\t\t\t\temp, year, period, date, payslip, type, code, description, qty, rate, amount, ex\r\n\t\t\t\t) VALUES (\r\n\t\t\t\t\t'{$empnum}','{$year}','{$mon}', '{$Date}', '{$payslip_id}', '{$td['id']}', '', '{$td['name']}', '1', '0', '{$rb}', 'RBS'\r\n\t\t\t\t)";
            $Ri = db_exec($Sl) or errDie("unable to insert data.");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance+({$rb}) WHERE empnum = '{$empnum}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($empnum, $td['account'], $ydate, $refnum, "Reimbursement", $rb, "c");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($td['account'], $salconacc, $date, $refnum, $rb, "Reimbursement for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
        }
    }
    if ($myEmp['paytype'] == "Cash") {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paidamount}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $cash_account, $ydate, $refnum, "Payment(Cash)", $paidamount, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit salaries control acc and credit Bank acc
        writetrans($salconacc, $cash_account, $date, $refnum, $paidamount, "Salary Payment(Cash) for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    } elseif ($myEmp['paytype'] == "Ledger Account") {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paidamount}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $account, $ydate, $refnum, "Payment(Ledger Account)", $paidamount, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit salaries control acc and credit Bank acc
        writetrans($salconacc, $account, $date, $refnum, $paidamount, "Salary Payment(Ledger Account) for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    } else {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paidamount}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $bankacc, $ydate, $refnum, "Payment(Bank)", $paidamount, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit salaries control acc and credit Bank acc
        writetrans($salconacc, $bankacc, $date, $refnum, $paidamount, "Salary Payment for employee(Bank),  {$myEmp['fnames']} {$myEmp['sname']}.");
        # issue bank record
        banktrans($accid, "withdrawal", $date, "{$myEmp['fnames']} {$myEmp['sname']}", "Salary Payment for employee,  {$myEmp['fnames']} {$myEmp['sname']}", 0, $paidamount, $salconacc, $myEmp['empnum']);
    }
    db_conn('cubit');
    /*
    	writetrans($uifexp,$uifbal , $date, $refnum, $uif, "Company UIF Contribution,  $myEmp[fnames] $myEmp[sname].");
    */
    # Debit uif sdl and credit sdl control acc
    //	writetrans($sdlexp,$sdlbal , $date, $refnum, $sdl, "SDL,  $myEmp[fnames] $myEmp[sname].");
    db_conn("cubit");
    if ($comp_uif > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','UIFC','','UIF','1','0','{$comp_uif}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data1.");
    }
    if ($emp_uif > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','UIFE','','UIF','1','0','{$emp_uif}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data3.");
    }
    if ($sdl > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','SDL','','SDL','1','0','{$sdl}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data2.");
    }
    if ($paye > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','PAYE','','PAYE','1','0','{$paye}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data3.");
    }
    if ($basic_sal > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INC','','Basic Salary','','1','0','{$basic_sal}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data4.");
    }
    if ($fringe_tot > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INC','','Fringe Benefits Total','','1','0','{$fringe_tot}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data4.");
    }
    if ($myEmp["loanpayslip"] > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','LOAN','','Employee Loan','','1','0','{$myEmp['loanpayslip']}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert loan data for employee income on payslip.");
        $sql = "UPDATE employees SET loanpayslip='0' WHERE empnum='{$empnum}'";
        $rslt = db_exec($sql) or errDie("Error updating loan information for payslip.");
    }
    if ($bonus > 0 && $myEmp["payprd"] != "f" && $myEmp["payprd"] != "w") {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INCB','','Bonus','','1','0','{$bonus}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data5.");
    } else {
        if ($bonus > 0) {
            $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INCB','','Special Bonus/Additional Salary','','1','0','{$bonus}','')";
            $Ri = db_exec($Sl) or errDie("unable to insert data5.");
        }
    }
    if ($annual > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INCAB','','Annual Bonus','','1','0','{$annual}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data5.");
    }
    if ($commission > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INCC','','Commission','','1','0','{$commission}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data6.");
    }
    if ($all_travel > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INCT','','Travel Allowance','','1','0','{$all_travel}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data7.");
    }
    if ($loaninstall > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDL','','Loan Repayment','1','0','{$loaninstall}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data8.");
    }
    if ($comp_pension > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','COMP','','Pension','1','0','{$comp_pension}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_pension > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDP','','Pension','1','0','{$emp_pension}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($comp_ret > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','COMR','','Retirement Annuity Fund','1','0','{$comp_ret}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_ret > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDR','','Retirement Annuity Fund','1','0','{$emp_ret}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($myEmp["fringe_car1_contrib"] > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDR','','Motorcar 1 Contribution for Use','1','0','{$myEmp['fringe_car1_contrib']}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($myEmp["fringe_car2_contrib"] > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDR','','Motorcar 2 Contribution for Use','1','0','{$myEmp['fringe_car2_contrib']}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($comp_medical > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','COMM','','Medical Aid','1','0','{$comp_medical}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data.11");
    }
    if ($emp_medical > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDM','','Medical Aid','1','0','{$emp_medical}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data.12");
    }
    if ($comp_provident > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','COMV','','Provident','1','0','{$comp_provident}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_provident > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDV','','Provident','1','0','{$emp_provident}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($comp_other > 0) {
        $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','COMO','','Other Deductions','1','0','{$comp_other}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_other > 0) {
        $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','DEDO','','Other Deductions','1','0','{$emp_other}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($overamt > 0) {
        $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,qty,rate,amount,ex) VALUES\r\n\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$id}','INCO','','Over Time','1','0','{$overamt}','')";
        $Ri = db_exec($Sl) or errDie("unable to insert data.13");
    }
    $payslip_id = $id;
    if (isset($allowid)) {
        $Sl = "SELECT id,allowance FROM allowances";
        $Ri = db_exec($Sl) or errDie("Unable to get allowances.");
        while ($data = pg_fetch_array($Ri)) {
            $allname[$data['id']] = $data['allowance'];
        }
        foreach ($allowid as $i => $id) {
            $aname = $allname[$allowid[$i]];
            if (($allowances[$i] = sprint($allowances[$i])) <= 0) {
                continue;
            }
            $Sl = "INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,qty,rate,amount,ex)\r\n\t\t\t\tVALUES ('{$empnum}','{$year}','{$mon}','{$Date}','{$payslip_id}','{$allowid[$i]}','','{$aname}','1','0','{$allowances[$i]}','')";
            $Ri = db_exec($Sl) or errDie("unable to insert data.");
        }
    }
    # Pay Deductions accounts
    if (isset($deductid)) {
        $Sl = "SELECT id,deduction FROM salded";
        $Ri = db_exec($Sl) or errDie("Unabel to get get dat.");
        while ($data = pg_fetch_array($Ri)) {
            $dnames[$data['id']] = $data['deduction'];
        }
        foreach ($deductid as $i => $id) {
            $dname = $dnames[$deductid[$i]];
            # Debit salaries control acc and credit  acc
            if (($deductions[$i] = sprint($deductions[$i])) > 0) {
                $Sl = "INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t\t\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$payslip_id}','{$deductid[$i]}','','{$dname}','1','0','{$deductions[$i]}')";
                $Ri = db_exec($Sl) or errDie("unable to insert data.");
            }
            if (($employer_deductions[$i] = sprint($employer_deductions[$i])) > 0) {
                $Sl = "INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES\r\n\t\t\t\t\t('{$empnum}','{$year}','{$mon}','{$Date}','{$payslip_id}','{$deductid[$i]}','','{$dname}','1','0','{$employer_deductions[$i]}')";
                //$Ri=db_exec($Sl) or errDie("unable to insert data1.");
            }
        }
    }
    $id = $payslip_id;
    $ecost += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM empc WHERE emp='{$empnum}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        while ($data = pg_fetch_array($Ri)) {
            db_conn('cubit');
            $sql = "SELECT * FROM costcenters WHERE ccid = '{$data['cid']}'";
            $ccRslt = db_exec($sql) or errDie("Unable to retrieve Cost centers from database.");
            $cc = pg_fetch_array($ccRslt);
            $amount = sprint($ecost * $data['amount'] / 100);
            db_conn(PRD_DB);
            $sql = "INSERT INTO cctran(ccid, trantype, typename, edate, description, amount, username, div)\r\n\t\t\tVALUES('{$cc['ccid']}', 'ct', 'Salary', '{$Date}', 'Salary for employee,  {$myEmp['fnames']} {$myEmp['sname']}', '{$amount}', '" . USER_NAME . "', '" . USER_DIV . "')";
            $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
        }
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $OUTPUT = "<script>printer('payslip-print.php?id={$id}');move('../main.php');</script>";
    require "../template.php";
}
function write($HTTP_VARS)
{
    extract($HTTP_VARS);
    if (isset($back)) {
        return enter($HTTP_VARS);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($id, "num", 1, 20, "Invalid employee number.");
    $v->isOk($bankid, "num", 1, 20, "Invalid bank number.");
    $v->isOk($paidamount, "float", 1, 10, "Invalid amount.");
    if (isset($account)) {
        $v->isOk($account, "num", 1, 100, "Invalid account.");
    }
    $date = $day . "-" . $mon . "-" . $year;
    $ydate = $year . "-" . $mon . "-" . $day;
    $day += 0;
    $mon += 0;
    $year += 0;
    if (!checkdate($mon, $day, $year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"];
        }
        $confirmCust .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirmCust;
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    //$date=date("d-m-Y");
    $salconacc = gethook("accnum", "salacc", "name", "salaries control");
    $cash_account = gethook("accnum", "salacc", "name", "cash");
    $refnum = getrefnum($date);
    $paidamount = sprint($paidamount);
    db_conn('cubit');
    $Sl = "SELECT * FROM employees WHERE empnum='{$id}'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) < 1) {
        return "Invalid employee.";
    }
    $edata = pg_fetch_array($Ri);
    $edata['paytype'] = "Ledger Account";
    if ($entry != "DT") {
        $paidamount = -$paidamount;
    }
    db_conn('cubit');
    $Sl = "UPDATE employees SET balance=balance-'{$paidamount}' WHERE empnum = '{$id}' AND div = '" . USER_DIV . "'";
    $Ri = db_exec($Sl) or errDie("Unable to get employee details.");
    if ($entry != "DT") {
        $paidamount = -$paidamount;
    }
    if ($edata['paytype'] == "Cash") {
        writetrans($salconacc, $cash_account, $date, $refnum, $paidamount, "Salary Payment(Cash) for employee,  {$edata['fnames']} {$edata['sname']}.");
        empledger($id, $cash_account, $ydate, $refnum, "Payment(Cash)", $paidamount, "d");
    } elseif ($edata['paytype'] == "Ledger Account") {
        //print $entry;exit;
        if ($entry == "DT") {
            writetrans($salconacc, $account, $date, $refnum, $paidamount, "{$description}  {$edata['fnames']} {$edata['sname']}.");
            empledger($id, $account, $ydate, $refnum, $description, $paidamount, "d");
        } else {
            writetrans($account, $salconacc, $date, $refnum, $paidamount, "{$description},  {$edata['fnames']} {$edata['sname']}.");
            empledger($id, $account, $ydate, $refnum, $description, $paidamount, "c");
        }
    } else {
        core_connect();
        $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
        # check if link exists
        if (pg_numrows($Rslt) < 1) {
            return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.";
        }
        $bank = pg_fetch_array($Rslt);
        $bankacc = $bank["accnum"];
        writetrans($salconacc, $bankacc, $date, $refnum, $paidamount, "Salary Payment for employee,  {$edata['fnames']} {$edata['sname']}.");
        empledger($id, $bankacc, $ydate, $refnum, "Payment(Bank)", $paidamount, "d");
        # issue bank record
        banktrans($bankid, "withdrawal", $date, "{$edata['fnames']} {$edata['sname']}", "Salary Payment for employee,  {$edata['fnames']} {$edata['sname']}", 0, $paidamount, $salconacc, $edata['empnum']);
    }
    $out = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Transaction Done</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Transaction with employee has been recorded</td>\n\t\t\t</tr>\n\t\t</table>";
    return $out;
}
function write_data($_POST)
{
    extract($_POST);
    if (isset($back)) {
        return enter_data2($_POST);
    }
    db_conn('core');
    $Sl = "SELECT accnum FROM salesacc WHERE name='VATIN'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        $vd = pg_fetch_array($Ri);
        $vatin = $vd['accnum'];
    } else {
        $vatin = 0;
    }
    $Sl = "SELECT accnum FROM salesacc WHERE name='VATOUT'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        $vd = pg_fetch_array($Ri);
        $vatout = $vd['accnum'];
    } else {
        $vatout = 0;
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes WHERE zero='Yes'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set up your vatcodes first.";
        }
    }
    $vcd = pg_fetch_array($Ri);
    db_conn('exten');
    $Sl = "SELECT debtacc FROM departments";
    $Ri = db_exec($Sl);
    $dd = pg_fetch_array($Ri);
    $cc = $dd['debtacc'];
    db_conn('core');
    $Sl = "SELECT * FROM accounts WHERE accname='Opening Balances / Suspense Account'";
    $Ri = db_exec($Sl) or errDie("Unable to get account.");
    if (pg_num_rows($Ri) < 1) {
        return "<li class='err'>There is no account called 'Opening Balances / Suspense Account'. <br>\n\t\tI Need that account.<br>\n\t\tPlease create it. <br><br>\n\t\tThank you.</li>";
    }
    $ad = pg_fetch_array($Ri);
    $bala = $ad['accid'];
    db_conn(PRD_DB);
    # get last ref number
    pglib_transaction("BEGIN");
    $refnum = getrefnum();
    /* check for main accounts whose sub accounts add up to same total,
    			then clear main account
    	   check for main accounts whose sub accounts dont add up, then unblock
    	   		main accounts
    	 */
    $sql = "SELECT * FROM cubit.import_data";
    $rslt = db_exec($sql) or errDie("Error validating data.");
    $acsub = $acmain = array();
    while ($fd = pg_fetch_array($rslt)) {
        $n = explode("/", $fd["des1"]);
        if (!isset($n[1]) || $n[1] == "000") {
            $n[1] = "000";
        }
        $a = array("num" => $fd["des1"], "name" => $fd["des2"], "dt" => $fd["des3"], "ct" => $fd["des4"]);
        if ($n[1] == "000") {
            $acmain["{$n['0']}"] = $a;
        } else {
            if (!isset($acsub[$n[0]])) {
                $acsub[$n[0]] = array();
            }
            $acsub[$n[0]][] = $a;
        }
    }
    /* match subs with mains */
    $unblock_main = false;
    foreach ($acmain as $k => $v) {
        $totdt = 0;
        $totct = 0;
        if (isset($acsub[$k])) {
            foreach ($acsub[$k] as $sk => $sv) {
                $totdt += $sv["dt"];
                $totct += $sv["ct"];
            }
            if ($totdt - $totct != $v["dt"] - $v["ct"]) {
                $unblock_main = true;
            } else {
                $sql = "UPDATE cubit.import_data SET des3='0', des4='0'\n\t\t\t\t\t\tWHERE des1='{$v['num']}' AND des2='{$v['name']}'";
                $rslt = db_exec($sql) or errDie("Error balancing main account with sub accounts: {$v['num']} - {$v['name']} with {$sv['num']} - {$sv['name']}.");
            }
        }
    }
    if ($unblock_main) {
        $sql = "UPDATE cubit.set SET value = 'nuse', descript = 'Dont block main accounts'\n\t\t\t\tWHERE label = 'BLOCK' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Error unblocking main accounts.");
    }
    /* continue importing (validated/fixed) data */
    db_conn('cubit');
    $Sl = "SELECT * FROM import_data";
    $Ri = db_exec($Sl);
    $i = 0;
    $tot_debit = 0;
    $tot_credit = 0;
    $date = mkdate(getYearOfFinMon($prd), $prd, 1);
    db_conn('core');
    while ($fd = pg_fetch_array($Ri)) {
        $fid = $fd['id'];
        $accs = explode('/', $fd['des1']);
        $topacc = $accs[0];
        $topacc = str_pad($topacc, 4, "0");
        if (isset($accs[1])) {
            $accnum = $accs[1];
        } else {
            $accnum = "000";
        }
        db_conn('core');
        if ($accounts[$fid] == 0) {
            $catss = explode(":", $cat[$fid]);
            if ($catss[0] == "other_income" || $catss[0] == "sales") {
                $catT = "I10";
                $type = "I";
            } elseif ($catss[0] == "expenses" || $catss[0] == "cost_of_sales") {
                $catT = "E10";
                $type = "E";
            } else {
                $catT = "B10";
                $type = "B";
            }
            $Sl = "\n\t\t\t\tINSERT INTO accounts (\n\t\t\t\t\ttopacc, accnum, catid, accname, vat, \n\t\t\t\t\tdiv, toptype, acctype\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$topacc}', '{$accnum}', '{$catT}', '{$fd['des2']}', 'f', \n\t\t\t\t\t'" . USER_DIV . "', '{$catss['0']}', '{$type}'\n\t\t\t\t)";
            $Rl = db_exec($Sl);
            $accname = $fd['des2'];
            $accid = pglib_lastid("accounts", "accid");
            // 			$query = "INSERT INTO trial_bal(accid, topacc, accnum, accname, div) VALUES('$accid', '$topacc', '$accnum', '$fd[des2]', '".USER_DIV."')";
            // 			$trialRslt = db_exec($query);
            global $MONPRD;
            insert_trialbal($accid, $topacc, $accnum, $accname, $type, 'f', USER_DIV);
            for ($i = 1; $i <= 12; $i++) {
                $periodname = getMonthName($i);
                $sql = "INSERT INTO " . YR_DB . ".{$periodname} (accid, topacc, accnum, accname,\n\t\t\t\t\t\t\tdebit, credit, div)\n\t\t\t\t\t\tSELECT accid, topacc, accnum, accname, debit, credit, div\n\t\t\t\t\t\tFROM core.trial_bal WHERE month='{$i}' AND accid='{$accid}'";
                db_exec($sql) or die($sql);
                $sql = "INSERT INTO \"{$i}\".openbal (accid, accname, debit, credit, div)\n\t\t\t\t\t\tSELECT accid, accname, debit, credit, div\n\t\t\t\t\t\tFROM core.trial_bal WHERE month='{$i}' AND accid='{$accid}'";
                db_exec($sql) or die($sql);
                $sql = "INSERT INTO \"{$i}\".ledger (acc, contra, edate, eref, descript,\n\t\t\t\t\t\t\tcredit, debit, div, caccname, ctopacc, caccnum, cbalance, dbalance)\n\t\t\t\t\t\tSELECT accid, accid, CURRENT_DATE, '0', 'Balance', '0', '0', div,\n\t\t\t\t\t\t\taccname, topacc, accnum, credit, debit\n\t\t\t\t\t\tFROM core.trial_bal WHERE month='{$i}' AND accid='{$accid}'";
                db_exec($sql) or die($sql);
            }
            $accounts[$fid] = $accid;
        } else {
            $Sl = "UPDATE accounts SET topacc='{$topacc}',accnum='{$accnum}',accname='{$fd['des2']}' WHERE accid='{$accounts[$fid]}'";
            $Rl = db_exec($Sl);
            $Sl = "UPDATE trial_bal SET topacc='{$topacc}',accnum='{$accnum}',accname='{$fd['des2']}' WHERE accid='{$accounts[$fid]}'";
            $Rl = db_exec($Sl);
        }
        $Sl = "SELECT accid,accname FROM accounts WHERE accid='{$accounts[$fid]}'";
        $Rx = db_exec($Sl);
        $ad = pg_fetch_array($Rx);
        $i++;
        $debit = $fd['des3'];
        $credit = $fd['des4'];
        if ($debit > 0) {
            writetrans($ad['accid'], $bala, $date, $refnum, sprint($debit), "Opening balance imported");
        }
        if ($credit > 0) {
            writetrans($bala, $ad['accid'], $date, $refnum, sprint($credit), "Opening balance imported");
        }
        $tot_debit += $fd['des3'];
        $tot_credit += $fd['des4'];
        if ($ad['accid'] == $vatin) {
            vatr($vcd['id'], $date, "INPUT", $vcd['code'], $refnum, "Opening balance VAT imported", sprint($credit - $debit), sprint($credit - $debit));
        }
        if ($ad['accid'] == $vatout) {
            vatr($vcd['id'], $date, "OUTPUT", $vcd['code'], $refnum, "Opening balance VAT imported", sprint($credit - $debit), sprint($credit - $debit));
        }
    }
    $tot_debit = sprint($tot_debit);
    $tot_credit = sprint($tot_credit);
    if ($cc_tot > 0) {
        $tot = array_sum($cbalance);
        if (sprint($cc_tot) != sprint($tot)) {
            return enter_data2($_POST) . "<li class='err'>The total amount for balances for customers you entered is: " . CUR . " {$tot}, the\n\t\t\ttotal for the control account is: " . sprint($cc_tot) . ". These need to be the same.</li>";
        }
        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>";
        }
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $cid = $cd['cusnum'];
            $cbalance[$cid] = sprint($cbalance[$cid]);
            if ($cbalance[$cid] > 0) {
                db_conn('cubit');
                # Update the customer (make balance more)
                $sql = "UPDATE customers SET balance = (balance + '{$cbalance[$cid]}') WHERE cusnum = '{$cid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, type, \n\t\t\t\t\t\tst, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cid}', '0', '{$cbalance[$cid]}', '{$date}', 'Opening Balance Imported', \n\t\t\t\t\t\t'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, balance, date, \n\t\t\t\t\t\ttype, st, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cid}', '0', '{$cbalance[$cid]}', '{$cbalance[$cid]}', '{$date}', \n\t\t\t\t\t\t'Opening Balance Imported', 'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                crecordDT($cbalance[$cid], $cid, $date);
                custledger($cid, $bala, $date, 0, "Opening Balance Imported", $cbalance[$cid], "d");
            } elseif ($cbalance[$cid] < 0) {
                db_conn('cubit');
                # Update the customer (make balance more)
                $sql = "UPDATE customers SET balance = (balance + '{$cbalance[$cid]}') WHERE cusnum = '{$cid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, type, \n\t\t\t\t\t\tst, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cid}', '0', '{$cbalance[$cid]}', '{$date}', 'Opening Balance Imported', \n\t\t\t\t\t\t'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, balance, date, \n\t\t\t\t\t\ttype, st, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cid}', '0', '{$cbalance[$cid]}', '{$cbalance[$cid]}', '{$date}', \n\t\t\t\t\t\t'Opening Balance Imported', 'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                crecordCT(-$cbalance[$cid], $cid, $date);
                custledger($cid, $bala, $date, 0, "Opening Balance Imported", -$cbalance[$cid], "c");
            }
            $i++;
            $tot += $cbalance[$cid];
        }
    }
    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>";
        }
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $sid = $cd['supid'];
            $sbalance[$sid] += 0;
            if ($sbalance[$sid] > 0) {
                db_conn('cubit');
                $sql = "UPDATE suppliers SET balance = (balance + '{$sbalance[$sid]}') WHERE supid = '{$sid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update supplier in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\t\tsupid, edate, ref, cacc, descript, \n\t\t\t\t\t\tamount, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sid}', '{$date}', '0', '{$bala}', 'Opening balance imported', \n\t\t\t\t\t\t'{$sbalance[$sid]}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                recordCT(-$sbalance[$sid], $sid, $date);
                suppledger($sid, $bala, $date, $refnum, "Opening balance imported", $sbalance[$sid], "c");
            } elseif ($sbalance[$sid] < 0) {
                db_conn('cubit');
                $sql = "UPDATE suppliers SET balance = (balance + '{$sbalance[$sid]}') WHERE supid = '{$sid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update supplier in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\t\tsupid, edate, ref, cacc, descript, amount, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sid}', '{$date}', '0', '{$bala}', 'Opening balance imported', \n\t\t\t\t\t\t'{$sbalance[$sid]}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                recordDT(-$sbalance[$sid], $sid, $date);
                suppledger($sid, $bala, $date, $refnum, "Opening balance imported", $sbalance[$sid], "d");
            }
            $i++;
            $tot += $sbalance[$sid];
        }
        if (sprint($sc_tot) != sprint($tot)) {
            return enter_data2($_POST) . "<li class='err'>The total amount for balances for suppliers you entered is: " . CUR . " {$tot}, the\n\t\t\ttotal for the control account is: " . sprint($sc_tot) . ". These need to be the same.</li>";
        }
    }
    if ($sal_tot > 0) {
        db_conn('cubit');
        $Sl = "SELECT empnum,enum,sname,fnames FROM employees ORDER BY sname,fnames";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>If you want to import your employee control account you need to add employees first</li>";
        }
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $eid = $cd['empnum'];
            if (!isset($ebalance[$eid])) {
                $ebalance[$eid] = "";
            }
            $ebalance[$eid] = sprint($ebalance[$eid]);
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance+'{$ebalance[$eid]}' WHERE empnum = '{$eid}' AND div = '" . USER_DIV . "'";
            $Rt = db_exec($Sl) or errDie("Unable to get employee details.");
            if ($ebalance[$eid] > 0) {
                empledger($eid, $bala, $date, $refnum, "Opening balance imported", $ebalance[$eid], "c");
            } else {
                empledger($eid, $bala, $date, $refnum, "Opening balance imported", abs($ebalance[$eid]), "d");
            }
            $i++;
            $tot += $ebalance[$eid];
        }
        if (sprint($sal_tot) != sprint($tot)) {
            return enter_data2($_POST) . "<li class='err'>The total amount for balances for employees you entered is: " . CUR . " {$tot}, the\n\t\t\ttotal for the control account is: " . sprint($sal_tot) . ". These need to be the same.</li>";
        }
    }
    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>";
        }
        $tot = 0;
        while ($cd = pg_fetch_array($Ri)) {
            $iid = $cd['stkid'];
            if (!isset($ibalance[$iid])) {
                $ibalance[$iid] = "";
            }
            if ($ibalance[$iid] > 0) {
                $unitnum = $units[$iid];
                db_connect();
                $sql = "UPDATE stock SET csamt = (csamt + '{$ibalance[$iid]}'), units = (units + '{$unitnum}') WHERE stkid = '{$iid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                stockrec($cd['stkid'], $cd['stkcod'], $cd['stkdes'], 'dt', $date, $unitnum, $ibalance[$iid], "Inventory balance imported");
                db_connect();
                $cspric = sprint($ibalance[$iid] / $unitnum);
                //$cspric = sprint(0);
                $sql = "\n\t\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, \n\t\t\t\t\t\tcsprice, csamt, details, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$date}', '{$cd['stkid']}', '{$cd['stkcod']}', '{$cd['stkdes']}', 'inc', '{$unitnum}', \n\t\t\t\t\t\t'{$ibalance[$iid]}', '{$cspric}', 'Inventory balance imported', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $recRslt = db_exec($sql);
                db_connect();
                $sql = "SELECT * FROM stock WHERE stkid = '{$iid}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                if (pg_numrows($stkRslt) < 1) {
                    return "<li> Invalid Stock ID.</li>";
                } else {
                    $stk = pg_fetch_array($stkRslt);
                }
                if ($stk['units'] != 0) {
                    $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$iid}' AND div = '" . USER_DIV . "'";
                    $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                } else {
                    $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$iid}' AND div = '" . USER_DIV . "'";
                    $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                }
            }
            $tot += $ibalance[$iid];
            $i++;
        }
        if (sprint($i_tot) != sprint($tot)) {
            return enter_data2($_POST) . "<li class='err'>The total amount for balances for inventory you entered is: " . CUR . " {$tot}, the\n\t\t\ttotal for the control account is: " . sprint($sal_tot) . ". These need to be the same.</li>";
        }
    }
    $out = "\n\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t<tr>\n\t\t\t\t<th>Data Imported</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>Trial balance, has been successfully imported.</td>\n\t\t\t</tr>\n\t\t</table>";
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    block();
    return $out;
}
function package($_POST)
{
    $_POST = var_makesafe($_POST);
    extract($_POST);
    $week += 0;
    if (isset($back)) {
        return process($_POST);
    }
    $annual += 0;
    $bonus += 0;
    $paye_salary += 0;
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($empnum, "num", 1, 20, "Invalid employee number.");
    $v->isOk($accid, "num", 1, 20, "Invalid bank number.");
    $v->isOk($MON, "num", 1, 2, "Invalid month.");
    $v->isOk($basic_sal, "float", 1, 40, "Invalid basic salary.");
    $v->isOk($overamt, "float", 1, 40, "Invalid overtime amount.");
    $v->isOk($income, "float", 1, 40, "Invalid income.");
    $v->isOk($commission, "float", 0, 40, "Invalid commision.");
    $v->isOk($abonus, "float", 0, 40, "Invalid Bonus.");
    $v->isOk($loaninstall, "float", 0, 40, "Invalid loan installment.");
    $v->isOk($paidamount, "float", 1, 40, "Invalid paid amount.");
    if (isset($allowances)) {
        foreach ($allowances as $key => $value) {
            $v->isOk($allowances[$key], "float", 0, 20, "Invalid allowance amount " . ($key + 1) . ".");
        }
    }
    if (isset($deductid)) {
        foreach ($deductid as $key => $value) {
            $v->isOk($deductid[$key], "num", 1, 20, "Invalid deductions ID.");
        }
    }
    if (isset($deductions)) {
        foreach ($deductions as $key => $value) {
            $v->isOk($deductions[$key], "float", 0, 20, "Invalid deduction amount" . ($key + 1) . ".");
        }
    }
    if (isset($allowid)) {
        foreach ($allowid as $key => $value) {
            $v->isOk($allowid[$key], "num", 1, 20, "Invalid allowance ID.");
        }
    }
    if (isset($allowtax)) {
        foreach ($allowtax as $key => $value) {
            $v->isOk($allowtax[$key], "string", 2, 20, "Invalid allowance tax " . ($key + 1) . ".");
        }
    }
    $date = mkdate($year, $mon, $day);
    $pdate = mkdate($year, $MON, $pday);
    if (!checkdate($mon, $day, $year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    $mon = $MON;
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    $basic_sal_save = $basic_sal;
    if (isset($multi)) {
        $basic_sal = sprint($basic_sal * $multi);
        $tyear = $tyear / $multi;
    } else {
        $basic_sal = $basic_sal;
    }
    db_conn('cubit');
    $nettpay = $income;
    $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.";
    }
    $ecost = 0;
    $myEmp = pg_fetch_array($empRslt);
    // fringe benefits
    $i = 0;
    $fringes = "";
    $fringes_desc = "";
    if (isset($fringebens)) {
        foreach ($fringebens as $key => $value) {
            if ($fringebens[$key] > 0) {
                $fringes_desc .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$fringename[$key]}</td>\n\t\t\t\t\t<td>" . CUR . " {$fringebens[$key]}</td>\n\t\t\t\t</tr>";
            }
        }
    }
    if (!empty($fringes_desc)) {
        $fringes_desc = "<tr><th colspan='2'>Fringe Benefits</th></tr>{$fringes_desc}";
    }
    $all_before = "";
    $all_after = "";
    $all_beforeamount = 0;
    $all_afteramount = 0;
    if (isset($allowtax)) {
        foreach ($allowtax as $key => $perc) {
            if ($perc == "Yes" and $allowances[$key] > 0) {
                $all_before .= "<tr><td>{$allowname[$key]}</td><td align='right'>" . CUR . " {$allowances[$key]}</td></tr>";
                $all_beforeamount = $all_beforeamount + $allowances[$key];
            } elseif ($allowances[$key] > 0) {
                $all_after .= "<tr><td>{$allowname[$key]}</td><td align='right'>" . CUR . " {$allowances[$key]}</td></tr>";
                $all_afteramount = $all_afteramount + $allowances[$key];
            }
        }
    }
    $de_before = "\n\t\t<tr>\n\t\t\t<td colspan='2'>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Details</th>\n\t\t\t\t\t\t<th>Employee aContribution</th>\n\t\t\t\t\t\t<!--<th>Employer Contribution</th>//-->\n\t\t\t\t\t</tr>";
    $de_after = "\n\t\t<tr>\n\t\t\t<td colspan='2'>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Details</th>\n\t\t\t\t\t\t<th>Employee Contribution</th>\n\t\t\t\t\t\t<!--<th>Employer Contribution</th>//-->\n\t\t\t\t\t</tr>";
    $de_beforeamount = 0;
    $de_afteramount = 0;
    $de_beforeamount_emp = 0;
    $de_afteramount_emp = 0;
    if (isset($deducttax)) {
        foreach ($deducttax as $key => $perc) {
            if ($perc == "Yes" and $deductions[$key] > 0) {
                $de_before .= "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>{$deductname[$key]}</td>\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$deductions[$key]}</td>\n<!--\t\t\t\t\t\t<td align='right'>" . CUR . " {$employer_deductions[$key]}</td> //-->\n\t\t\t\t\t</tr>";
                $de_beforeamount = $de_beforeamount + $deductions[$key] + $employer_deductions[$key];
                $de_beforeamount_emp += $employer_deductions[$key];
            } elseif ($deductions[$key] > 0) {
                $de_after .= "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>{$deductname[$key]}</td>\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$deductions[$key]}</td>\n<!--\t\t\t\t\t\t<td align='right'>" . CUR . " {$employer_deductions[$key]}</td> //-->\n\t\t\t\t\t</tr>";
                $de_afteramount = $de_afteramount + $deductions[$key] + $employer_deductions[$key];
                $de_afteramount_emp += $employer_deductions[$key];
            }
        }
    }
    $de_before .= "</table></td></tr>";
    $de_after .= "</table></td></tr>";
    if ($all_beforeamount > 0) {
        $all_before = "<tr><td colspan='2'>Allowances</td></tr>" . $all_before;
    }
    if ($all_afteramount > 0) {
        $all_after = "<tr><td colspan='2'>Allowances</td></tr>" . $all_after;
    }
    if ($de_beforeamount > 0) {
        $de_before = "<tr><td colspan='2'>Deductions</td></tr>" . $de_before;
    }
    if ($de_afteramount > 0) {
        $de_after = "<tr><td colspan='2'>Deductions</td></tr>" . $de_after;
    }
    $gros_sal = sprint($grossal);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $bank = pg_fetch_array($rslt);
    $bankacc = $bank["accnum"];
    $basic_sal = sprint($basic_sal);
    $commission = sprint($commission);
    $abonus = sprint($abonus);
    $overamt = sprint($overamt);
    $paye = sprint($paye);
    $nettpay = sprint($nettpay);
    $sdl = sprint($comp_sdl);
    $amount = sprint($gros_sal + $comp_pension + $comp_provident + $comp_medical + $comp_other + $comp_uif + $comp_ret + $sdl);
    $loaninstall = sprint($loaninstall);
    //Original CC
    //$cc = "<script> CostCenter('ct', 'Salaries', '$date', 'Salary Payment for employee,  $myEmp[fnames] $myEmp[sname]', '$amount', '../'); </script>";
    //New CC
    $cc = "CostCenter('ct', 'Salaries', '{$date}', 'Salary Payment for employee,  {$myEmp['fnames']} {$myEmp['sname']}', '{$amount}', '../'); ";
    $ecost = $amount;
    if ($commission > 0) {
        $comDis = "<tr><td>Commission</td><td align='right'>" . CUR . " {$commission}</td></tr>";
    } else {
        $comDis = "";
    }
    if ($abonus > 0) {
        $aboDis = "<tr><td>Annual Bonus</td><td align='right'>" . CUR . " {$abonus}</td></tr>";
    } else {
        $aboDis = "";
    }
    if ($overamt > 0) {
        $oveDis = "<tr><td>Overtime</td><td align='right'>" . CUR . " {$overamt}</td></tr>";
    } else {
        $oveDis = "";
    }
    if ($loaninstall > 0) {
        $loaDis = "<tr><td>Loan Instalment</td><td align='right'>" . CUR . " {$loaninstall}</td></tr>";
    } else {
        $loaDis = "";
    }
    if ($basic_sal != $gros_sal) {
        $groDis = "<tr><td>Gross Salary</td><td align='right'>" . CUR . " {$gros_sal}</td></tr>";
    } else {
        $groDis = "";
    }
    if ($all_travel > 0) {
        $talDis = "<tr><td>Travel Allowance</td><td align='right'>" . CUR . " {$all_travel}</td></tr>";
    } else {
        $talDis = "";
    }
    db_connect();
    $Sl = "SELECT * FROM salset";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        $con = true;
    } else {
        $con = false;
    }
    $intrec = gethook("accnum", "salacc", "name", "interestreceived");
    $uifbal = gethook("accnum", "salacc", "name", "uifbal");
    $sdlbal = gethook("accnum", "salacc", "name", "sdlbal");
    $pa = gethook("accnum", "salacc", "name", "pension");
    $ma = gethook("accnum", "salacc", "name", "medical");
    $cash_account = gethook("accnum", "salacc", "name", "cash");
    $retire = gethook("accnum", "salacc", "name", "retire");
    $provident = gethook("accnum", "salacc", "name", "provident");
    $salconacc = gethook("accnum", "salacc", "name", "salaries control");
    $commacc = gethook("accnum", "salacc", "name", "Commission");
    $abonusacc = gethook("accnum", "salacc", "name", "Bonus");
    $payeacc = gethook("accnum", "salacc", "name", "PAYE");
    $uifacc = gethook("accnum", "salacc", "name", "UIF");
    $providente = $myEmp["expacc_provident"];
    $retiree = $myEmp["expacc_ret"];
    $pax = $myEmp["expacc_pension"];
    $uifexp = $myEmp["expacc_uif"];
    $max = $myEmp["expacc_medical"];
    $dedgenerale = $myEmp["expacc_other"];
    $sdlexp = $myEmp["expacc_sdl"];
    $salacc = $myEmp["expacc_salwages"];
    $loanexp = $myEmp["expacc_loan"];
    $reimbursexp = $myEmp["expacc_reimburs"];
    if ($con) {
        $uifexp = $salacc;
        $sdlexp = $salacc;
        $pax = $salacc;
        $max = $salacc;
        $retiree = $salacc;
    }
    // Get Bank account [the traditional way re: hook of hook]
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accid}' AND div = '" . USER_DIV . "'";
    $Rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($Rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.";
    }
    $bank = pg_fetch_array($Rslt);
    $refnum = getrefnum($date);
    # Debit uif acc and credit uif control acc
    if ($comp_uif > 0) {
        writetrans($uifexp, $uifbal, $date, $refnum, $comp_uif, "Company UIF Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_uif > 0) {
        db_conn("cubit");
        $Sl = "UPDATE employees SET balance=balance-({$emp_uif}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $uifacc, $date, $refnum, "UIF", $emp_uif, "d");
        writetrans($salconacc, $uifbal, $date, $refnum, $emp_uif, "Employee UIF Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    # Debit uif sdl and credit sdl control acc
    writetrans($sdlexp, $sdlbal, $date, $refnum, $sdl, "SDL,  {$myEmp['fnames']} {$myEmp['sname']}.");
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    db_conn('cubit');
    $Sl = "UPDATE employees SET balance=balance+({$grossal_nodedall}) WHERE empnum = '{$empnum}'";
    $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
    empledger($empnum, $salacc, $date, $refnum, "Gross Salary", $grossal_nodedall, "c");
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    # Debit salaries acc and credit salaries control acc
    writetrans($salacc, $salconacc, $date, $refnum, $grossal_nodedall, "Gross Salary proccessing for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    if ($commission > 0) {
        if ($con) {
            $commacc = $salacc;
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance+({$commission}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $commacc, $date, $refnum, "Commission", $commission, "c");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit commission acc and credit salaries control acc
        writetrans($commacc, $salconacc, $date, $refnum, $commission, "Commission for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($abonus > 0) {
        if ($con) {
            $abonusacc = $salacc;
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance+({$abonus}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $abonusacc, $date, $refnum, "Bonus", $abonus, "c");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit bonus acc and credit salaries control acc
        writetrans($abonusacc, $salconacc, $date, $refnum, $abonus, "Bonus for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($paye > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paye}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $payeacc, $date, $refnum, "PAYE", $paye, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        # Debit salaries control acc and credit PAYE control acc
        writetrans($salconacc, $payeacc, $date, $refnum, $paye, "PAYE for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    db_conn('cubit');
    # Pay allowances accounts
    if (isset($allowid)) {
        foreach ($allowid as $i => $id) {
            # Debit allowances acc and credit salaries control acc
            if ($con) {
                $allowaccs[$i] = $salacc;
            }
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance+({$allowances[$i]}) WHERE empnum = '{$empnum}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($empnum, $allowaccs[$i], $date, $refnum, "Allowance", $allowances[$i], "c");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($allowaccs[$i], $salconacc, $date, $refnum, $allowances[$i], "Allowances for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
        }
    }
    # Pay Deductions accounts
    if (isset($deductid)) {
        foreach ($deductid as $i => $id) {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance-({$deductions[$i]}) WHERE empnum = '{$empnum}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($empnum, $dedaccs[$i], $date, $refnum, "Deduction", $deductions[$i], "d");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            # Debit salaries control acc and credit  acc
            // salcon acc - ded balance acc
            writetrans($salconacc, $dedaccs[$i], $date, $refnum, $deductions[$i], "Deductions for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
            db_conn("cubit");
            $sql = "SELECT * FROM salded WHERE id='{$id}'";
            $rslt = db_exec($sql) or errDie("Error reading deduction information.");
            $dedinfo = pg_fetch_array($rslt);
        }
    }
    if ($comp_pension > 0) {
        writetrans($pax, $pa, $date, $refnum, $comp_pension, "Company Pension Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_pension > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_pension}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $pa, $date, $refnum, "Pension Contribution", $emp_pension, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $pa, $date, $refnum, $emp_pension, "Pension Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($comp_medical > 0) {
        writetrans($max, $ma, $date, $refnum, $comp_medical, "Company Medical Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_medical > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_medical}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $ma, $date, $refnum, "Medical Contribution", $emp_medical, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $ma, $date, $refnum, $emp_medical, "Employee Medical Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($comp_provident > 0) {
        writetrans($providente, $provident, $date, $refnum, $comp_provident, "Company Provident Fund Contribution, {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_provident > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_provident}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $provident, $date, $refnum, "Provident Fund Contribution", $emp_provident, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $provident, $date, $refnum, $emp_provident, "Provident Fund Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if (false && $comp_other > 0) {
        writetrans($dedgenerale, $dedgeneral, $date, $refnum, $comp_other, "Company Contribution to Other Deductions, {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if (false && $emp_other > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_other}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $dedgeneral, $date, $refnum, "Other Deductions Contribution", $emp_other, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $dedgeneral, $date, $refnum, $emp_other, "Other Deductions Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($emp_ret > 0) {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$emp_ret}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $retire, $date, $refnum, "Retirement Annuity Contribution", $emp_ret, "d");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salconacc, $retire, $date, $refnum, $emp_ret, "Employee Retirement Annuity Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    if ($comp_ret > 0) {
        writetrans($retiree, $retire, $date, $refnum, $comp_ret, "Company Retirement Annuity Contribution,  {$myEmp['fnames']} {$myEmp['sname']}.");
    }
    db_conn('cubit');
    $mons = "{$mon};";
    $due = sprint($nettpay - $paidamount);
    //, balance=balance+'$due
    $sql = "\n\t\tUPDATE employees \n\t\tSET lastpay = '{$mons}', loanamt = (loanamt - cast(float '{$loaninstall}' as numeric)), \n\t\t\tloanfringe = (loanfringe - cast(float '{$fringe_loan}' as numeric)) \n\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to get employee details.");
    // check if loan is 0, then unmark loan as active, and store in archive
    $sql = "SELECT loanid FROM employees WHERE loanamt=0 AND empnum='{$empnum}' AND gotloan='t'::bool";
    $rslt = db_exec($sql) or errDie("Error reading employee details for loan.");
    if (pg_num_rows($rslt) > 0) {
        $loanid = pg_fetch_result($rslt, 0, 0);
        $sql = "UPDATE employees SET gotloan='f'::bool, loaninstall='0' WHERE empnum='{$empnum}'";
        $rslt = db_exec($sql) or errDie("Unable to update employee loan status.");
        $sql = "UPDATE emp_loanarchive SET donedata=CURRENT_DATE WHERE id='{$loanid}'";
        $rslt = db_exec($sql) or errDie("Unable to archive loan.");
        $sql = "SELECT loanint_unpaid FROM employees WHERE empnum='{$empnum}'";
        $rslt = db_exec($sql) or errDie("Error reading loan interest for installment.");
        $loanint = sprint(pg_fetch_result($rslt, 0, 0));
    } else {
        if ($loaninstall > 0) {
            $sql = "SELECT loanamt_tot, loanint_amt FROM employees WHERE empnum='{$empnum}'";
            $rslt = db_exec($sql) or errDie("Error reading loan interest for installment.");
            $loan_tot = pg_fetch_result($rslt, 0, 0);
            $loan_totint = pg_fetch_result($rslt, 0, 1);
            $loanint = sprint($loaninstall / $loan_tot * $loan_totint);
        } else {
            $loanint = 0;
        }
    }
    $sql = "\n\t\tUPDATE employees \n\t\tSET loanint_unpaid = (loanint_unpaid - cast(float '{$loanint}' as numeric)) \n\t\tWHERE empnum = '{$empnum}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update employee interest.");
    if ($loaninstall > 0 && !empty($loanexp)) {
        $loaninstall += 0;
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$loaninstall}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $loanexp, $date, $refnum, "Loan Instalment", $loaninstall, "d");
        # Debit salaries control acc and credit loan control acc
        writetrans($salconacc, $loanexp, $date, $refnum, $loaninstall - $loanint, "Loan Installment for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
        writetrans($salconacc, $intrec, $date, $refnum, $loanint, "Loan Interest for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
        /* record this month's loan amounts (for reversal purposes) */
        // determine the salary period
        switch ($myEmp["payprd"]) {
            case "d":
                $lprd = date_part($pdate, DP_DAY);
                break;
            case "m":
            case "f":
            case "w":
            default:
                $lprd = $week;
                break;
        }
        // record it!
        db_conn("cubit");
        $sql = "\n\t\t\tINSERT INTO emp_loaninstallments (\n\t\t\t\tempnum, fdate, fperiod, fmonth, fyear, installment, interest, fringe\n\t\t\t) VALUES (\n\t\t\t\t'{$empnum}', '{$date}', '{$lprd}', '{$mon}', '" . EMP_YEAR . "', '{$loaninstall}', '{$loanint}', '{$fringe_loan}'\n\t\t\t)";
        $rslt = db_exec($sql) or errDie("Error record loan fringe benefit.");
    }
    $loaninstall = $loaninstall + 0;
    $totded = sprint($de_beforeamount + $de_afteramount + $emp_pension + $emp_medical + $emp_provident + $emp_ret + $emp_other);
    $totded_employer = sprint($de_beforeamount_emp + $de_afteramount_emp + $comp_pension + $comp_medical + $comp_provident + $comp_ret + $comp_other);
    $totall = sprint($all_beforeamount + $all_afteramount + $all_travel);
    $parkage = "\n\t\t<br><br>\n\t\t<center>\n\t\t{$cc}\n\t\t<table border=2 cellpadding='4' cellspacing='0' width='750' bordercolor='#000000'>\n\t\t\t<tr>\n\t\t\t\t<td align='center'><b>Description</b></td>\n\t\t\t\t<td width='100' align='center'><b>Amount</b></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>Basic salary</td>\n\t\t\t\t<td align='right'>" . CUR . " {$basic_sal}</td>\n\t\t\t</tr>\n\t\t\t{$comDis}\n\t\t\t{$aboDis}\n\t\t\t{$fringes_desc}\n\t\t\t{$all_before}\n\t\t\t{$de_before}\n\t\t\t{$groDis}\n\t\t\t{$talDis}\n\t\t\t<tr>\n\t\t\t\t<td>UIF</td>\n\t\t\t\t<td align='right'>" . CUR . " {$emp_uif}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>PAYE</td>\n\t\t\t\t<td align='right'>" . CUR . " {$paye}</td>\n\t\t\t</tr>\n\t\t\t{$loaDis}\n\t\t\t{$all_after}\n\t\t\t{$de_after}\n\t\t\t<tr>\n\t\t\t\t<td><b>Nett Pay</b></td>\n\t\t\t\t<td align='right'><b>" . CUR . " {$nettpay}</b></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>\n\t\t</center>";
    $parkagesave = "\n\t\t<br><br>\n\t\t<center>\n\t\t<table border='2' width='750' border=2 cellpadding='4' cellspacing='0' bordercolor='#000000'>\n\t\t\t<tr>\n\t\t\t\t<td align='center'><b>Description</b></td>\n\t\t\t\t<td width='100' align='center'><b>Amount</b></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>Basic salary</td>\n\t\t\t\t<td align='right'>" . CUR . " {$basic_sal}</td>\n\t\t\t</tr>\n\t\t\t{$comDis}\n\t\t\t{$aboDis}\n\t\t\t{$fringes_desc}\n\t\t\t{$all_before}\n\t\t\t{$de_before}\n\t\t\t{$groDis}\n\t\t\t{$talDis}\n\t\t\t<tr>\n\t\t\t\t<td>UIF</td>\n\t\t\t\t<td align='right'>" . CUR . " {$emp_uif}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>PAYE</td>\n\t\t\t\t<td align='right'>" . CUR . " {$paye}</td>\n\t\t\t</tr>\n\t\t\t{$loaDis}\n\t\t\t{$all_after}\n\t\t\t{$de_after}\n\t\t\t<tr>\n\t\t\t\t<td><b>Nett Pay</b></td>\n\t\t\t\t<td align='right'><b>" . CUR . " {$nettpay}</b></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>\n\t\t</center>";
    $OUTPUT = $parkage;
    $save = base64_encode($parkagesave);
    $Date = $date;
    $np = $nettpay;
    if (isset($rbsa)) {
        $np = sprint($np - array_sum($rbsa));
    }
    /* hack to store the pay date for dailies */
    if ($myEmp["payprd"] == "d") {
        $week = $pday;
    }
    if (empty($novert)) {
        $novert = "0";
    }
    if (empty($hovert)) {
        $hovert = "0";
    }
    db_conn("cubit");
    $sql = "\n   \t\tINSERT INTO cubit.salpaid (\n   \t\t\tempnum, month, bankid, salary, comm, uifperc, uif, payeperc, paye, totded, totded_employer, \n\t\t\ttotallow, loanins, tot_fringe, div, display, saldate, week, cyear, novert, \n   \t\t\thovert, taxed_sal, hours, salrate, bonus\n   \t\t) VALUES (\n   \t\t\t'{$empnum}', '{$mon}', '{$accid}', '{$np}', '{$commission}', '0', '{$emp_uif}', '0', '{$paye}', '{$totded}', '{$totded_employer}', \n\t\t\t'{$totall}', '{$loaninstall}', '{$fringe_tot}', '" . USER_DIV . "', '{$save}', '{$Date}', '{$week}', '" . EMP_YEAR . "', '{$novert}', \n   \t\t\t'{$hovert}', '{$paye_salary}', '{$multi}', '{$basic_sal_save}', '{$abonus}'\n   \t\t)";
    $Ry = db_exec($sql) or errDie("Unable to insert record.");
    $id = pglib_lastid("salpaid", "id");
    $year = $year;
    $payslip_id = $id;
    db_conn("cubit");
    $Sl = "SELECT * FROM cubit.rbs ORDER BY name";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    $i = 0;
    if (pg_num_rows($Ri) > 0) {
        while ($td = pg_fetch_array($Ri)) {
            if (!isset($rbsa[$td['id']]) || $rbsa[$td['id']] < 1) {
                continue;
            }
            $rb = sprint($rbsa[$td['id']]);
            db_conn("cubit");
            $sql = "\n\t\t\t\tINSERT INTO emp_inc (\n\t\t\t\t\temp, year, period, date, week, payslip, type, code, description, \n\t\t\t\t\tqty, rate, amount, ex\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$Date}', '{$week}', '{$payslip_id}', '{$td['id']}', '', '{$td['name']}', \n\t\t\t\t\t'1', '0', '{$rb}', 'RBS'\n\t\t\t\t)";
            db_exec($sql) or errDie("unable to insert data.");
            $sql = "UPDATE employees SET balance=balance+({$rb}) WHERE empnum = '{$empnum}'";
            db_exec($sql) or errDie("Unable to get employee details.");
            empledger($empnum, $td['account'], $date, $refnum, "Reimbursement", $rb, "c");
            writetrans($td['account'], $salconacc, $date, $refnum, $rb, "Reimbursement for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
        }
    }
    if (isset($subsname)) {
        foreach ($subsname as $sid => $sn) {
            if (empty($subsamt[$sid]) || $subsamt[$sid] <= 0) {
                continue;
            }
            $samt = sprint($subsamt[$sid]);
            $i++;
            db_conn('cubit');
            $cols = grp(m("emp", $empnum), m("year", EMP_YEAR), m("period", $mon), m("week", $week), m("date", $Date), m("payslip", $payslip_id), m("type", $sid), m("code", ""), m("description", $subsname[$sid]), m("qty", 1), m("rate", 0), m("amount", $samt), m("ex", "SUBS"));
            $subin = new dbUpdate("emp_inc", "cubit", $cols);
            $subin->run(DB_INSERT);
            $cols = grp(m("balance", raw("balance+({$samt})")));
            $subin->setTable("employees");
            $subin->setOpt($cols, wgrp(m("empnum", $empnum)));
            $subin->run(DB_UPDATE);
            empledger($empnum, $subsacc[$sid], $date, $refnum, "Subsistence Allowance: {$subsname[$sid]}", $samt, "c");
            writetrans($subsacc[$sid], $salconacc, $date, $refnum, $samt, "Subsistence Allownace ({$subsname[$sid]}) for employee, {$myEmp['fnames']} {$myEmp['sname']}.");
        }
    }
    if ($myEmp['paytype'] == "Cash") {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paidamount}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $cash_account, $date, $refnum, "Payment(Cash)", $paidamount, "d");
        writetrans($salconacc, $cash_account, $date, $refnum, $paidamount, "Salary Payment(Cash) for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    } elseif ($myEmp['paytype'] == "Ledger Account") {
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paidamount}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $account, $date, $refnum, "Payment(Ledger Account)", $paidamount, "d");
        writetrans($salconacc, $account, $date, $refnum, $paidamount, "Salary Payment(Ledger Account) for employee,  {$myEmp['fnames']} {$myEmp['sname']}.");
    } else {
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance-({$paidamount}) WHERE empnum = '{$empnum}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($empnum, $bankacc, $date, $refnum, "Payment(Bank)", $paidamount, "d");
        writetrans($salconacc, $bankacc, $date, $refnum, $paidamount, "Salary Payment for employee(Bank),  {$myEmp['fnames']} {$myEmp['sname']}.");
        # issue bank record
        banktrans($accid, "withdrawal", $date, "{$myEmp['fnames']} {$myEmp['sname']}", "Salary Payment for employee,  {$myEmp['fnames']} {$myEmp['sname']}", 0, $paidamount, $salconacc, $myEmp['empnum']);
    }
    db_conn('cubit');
    /*
    	writetrans($uifexp,$uifbal , $date, $refnum, $uif, "Company UIF Contribution,  $myEmp[fnames] $myEmp[sname].");
    */
    # Debit uif sdl and credit sdl control acc
    //	writetrans($sdlexp,$sdlbal , $date, $refnum, $sdl, "SDL,  $myEmp[fnames] $myEmp[sname].");
    db_conn("cubit");
    if ($comp_uif > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'UIFC', '', 'UIF', '1', '0','{$comp_uif}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data1.");
    }
    if ($emp_uif > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'UIFE', '', 'UIF', '1', '0', '{$emp_uif}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data3.");
    }
    if ($sdl > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'SDL', '', 'SDL', '1', '0', '{$sdl}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data2.");
    }
    if ($paye > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'PAYE', '', 'PAYE', '1', '0', '{$paye}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data3.");
    }
    if ($basic_sal > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INC', '', 'Basic Salary', '', '1', '0', '{$basic_sal}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data4.");
    }
    if ($myEmp["loanpayslip"] > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'LOAN', '', 'Employee Loan', '', '1', '0', '{$myEmp['loanpayslip']}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert loan data for employee income on payslip.");
        $sql = "UPDATE employees SET loanpayslip='0' WHERE empnum='{$empnum}'";
        $rslt = db_exec($sql) or errDie("Error updating loan information for payslip.");
    }
    if ($bonus > 0 && $myEmp["payprd"] != "f" && $myEmp["payprd"] != "w") {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCB', '', 'Bonus', '', '1', '0', '{$bonus}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data5.");
    } else {
        if ($bonus > 0) {
            $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCB', '', 'Special Bonus/Additional Salary', '', '1', '0', '{$bonus}', '')";
            $Ri = db_exec($Sl) or errDie("unable to insert data5.");
        }
    }
    if ($annual > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCAB', '', 'Annual Bonus', '', '1', '0', '{$annual}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data5.");
    }
    if ($commission > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCC', '', 'Commission', '', '1', '0', '{$commission}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data6.");
    }
    if ($abonus > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCAB', '', 'Bonus', '', '1', '0', '{$abonus}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data6.");
    }
    if ($all_travel > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, pension, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCT', '', 'Travel Allowance', '', '1', '0', '{$all_travel}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data7.");
    }
    if ($loaninstall > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDL', '', 'Loan Repayment', '1', '0', '{$loaninstall}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data8.");
    }
    if ($comp_pension > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'COMP', '', 'Pension', '1', '0', '{$comp_pension}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_pension > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDP', '', 'Pension', '1', '0', '{$emp_pension}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($comp_ret > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'COMR', '', 'Retirement Annuity Fund', '1', '0', '{$comp_ret}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_ret > 0) {
        $Sl = "\n        \tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n        \tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDR', '', 'Retirement Annuity Fund', '1', '0', '{$emp_ret}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($myEmp["fringe_car1_contrib"] > 0) {
        $Sl = "\n        \tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n        \tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDA', '', 'Motorcar 1 Contribution for Use', '1', '0', '{$myEmp['fringe_car1_contrib']}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($myEmp["fringe_car2_contrib"] > 0) {
        $Sl = "\n        \tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n        \tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDB', '', 'Motorcar 2 Contribution for Use', '1', '0', '{$myEmp['fringe_car2_contrib']}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($comp_medical > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'COMM', '', 'Medical Contribution', '1', '0', '{$comp_medical}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data.11");
    }
    if ($emp_medical > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDM', '', 'Medical Contribution', '1', '0', '{$emp_medical}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data.12");
    }
    if ($comp_provident > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'COMV', '', 'Provident', '1', '0', '{$comp_provident}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_provident > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDV', '', 'Provident', '1', '0', '{$emp_provident}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($comp_other > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'COMO', '', 'Other Deductions', '1', '0', '{$comp_other}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data9.");
    }
    if ($emp_other > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'DEDO', '', 'Other Deductions', '1', '0', '{$emp_other}')";
        $Ri = db_exec($Sl) or errDie("unable to insert data10.");
    }
    if ($overamt > 0) {
        $Sl = "\n\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount, ex) \n\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$id}', 'INCO', '', 'Over Time', '1', '0', '{$overamt}', '')";
        $Ri = db_exec($Sl) or errDie("unable to insert data.13");
    }
    $payslip_id = $id;
    // fringe benefits
    $frinupd = new dbUpdate("emp_frin", "cubit");
    if (isset($fringebens)) {
        foreach ($fringebens as $key => $value) {
            $cols = grp(m("emp", $empnum), m("year", EMP_YEAR), m("period", $mon), m("week", $week), m("fdate", $Date), m("payslip", $payslip_id), m("code", $key), m("description", $fringename[$key]), m("qty", 1), m("amount", sprint($fringebens[$key])));
            $frinupd->setCols($cols);
            $frinupd->run(DB_INSERT);
        }
    }
    if ($fringe_loan > 0) {
        $cols = grp(m("emp", $empnum), m("year", $year), m("period", $mon), m("fdate", $Date), m("payslip", $payslip_id), m("code", "FRINLOAN"), m("description", "Loan Fringe Benefit"), m("qty", 1), m("amount", $fringe_loan));
        $frinupd->setCols($cols);
        $frinupd->run(DB_INSERT);
    }
    if ($fringe_medical > 0) {
        $cols = grp(m("emp", $empnum), m("year", $year), m("period", $mon), m("fdate", $Date), m("payslip", $payslip_id), m("code", "FRINMED"), m("description", "Medical Fringe Benefit"), m("qty", 1), m("amount", $fringe_medical));
        $frinupd->setCols($cols);
        $frinupd->run(DB_INSERT);
    }
    if ($fringe_car1 > 0) {
        $cols = grp(m("emp", $empnum), m("year", $year), m("period", $mon), m("fdate", $Date), m("payslip", $payslip_id), m("code", "FRINCAR1"), m("description", "Fringe Benefit: Vehicle 1"), m("qty", 1), m("amount", $fringe_car1));
        $frinupd->setCols($cols);
        $frinupd->run(DB_INSERT);
    }
    if ($fringe_car2 > 0) {
        $cols = grp(m("emp", $empnum), m("year", $year), m("period", $mon), m("fdate", $Date), m("payslip", $payslip_id), m("code", "FRINCAR2"), m("description", "Fringe Benefit: Vehicle 2"), m("qty", 1), m("amount", $fringe_car2));
        $frinupd->setCols($cols);
        $frinupd->run(DB_INSERT);
    }
    if (isset($allowid)) {
        $Sl = "SELECT id,allowance FROM allowances";
        $Ri = db_exec($Sl) or errDie("Unable to get allowances.");
        while ($data = pg_fetch_array($Ri)) {
            $allname[$data['id']] = $data['allowance'];
        }
        foreach ($allowid as $i => $id) {
            $aname = $allname[$allowid[$i]];
            if (($allowances[$i] = sprint($allowances[$i])) <= 0) {
                continue;
            }
            $Sl = "\n\t\t\t\tINSERT INTO emp_inc (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount, ex)\n\t\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$payslip_id}', '{$allowid[$i]}', '', '{$aname}', '1', '0', '{$allowances[$i]}', '')";
            $Ri = db_exec($Sl) or errDie("unable to insert data.");
        }
    }
    # Pay Deductions accounts
    if (isset($deductid)) {
        $Sl = "SELECT id,deduction FROM salded";
        $Ri = db_exec($Sl) or errDie("Unabel to get get dat.");
        while ($data = pg_fetch_array($Ri)) {
            $dnames[$data['id']] = $data['deduction'];
        }
        foreach ($deductid as $i => $id) {
            $dname = $dnames[$deductid[$i]];
            # Debit salaries control acc and credit  acc
            if (($deductions[$i] = sprint($deductions[$i])) > 0) {
                $Sl = "\n\t\t\t\t\tINSERT INTO emp_ded (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$payslip_id}', '{$deductid[$i]}', '', '{$dname}', '1', '0', '{$deductions[$i]}')";
                $Ri = db_exec($Sl) or errDie("unable to insert data.");
            }
            if (($employer_deductions[$i] = sprint($employer_deductions[$i])) > 0) {
                $Sl = "\n\t\t\t\t\tINSERT INTO emp_com (emp, year, period, week, date, payslip, type, code, description, qty, rate, amount) \n\t\t\t\t\tVALUES ('{$empnum}', '" . EMP_YEAR . "', '{$mon}', '{$week}', '{$Date}', '{$payslip_id}', '{$deductid[$i]}', '', '{$dname}', '1', '0', '{$employer_deductions[$i]}')";
                //$Ri=db_exec($Sl) or errDie("unable to insert data1.");
            }
        }
    }
    $id = $payslip_id;
    $ecost += 0;
    db_conn('cubit');
    $Sl = "SELECT * FROM empc WHERE emp='{$empnum}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        while ($data = pg_fetch_array($Ri)) {
            db_conn('cubit');
            $sql = "SELECT * FROM costcenters WHERE ccid = '{$data['cid']}'";
            $ccRslt = db_exec($sql) or errDie("Unable to retrieve Cost centers from database.");
            $cc = pg_fetch_array($ccRslt);
            $amount = sprint($ecost * $data['amount'] / 100);
            db_conn(PRD_DB);
            $sql = "\n\t\t\t\tINSERT INTO cctran (\n\t\t\t\t\tccid, trantype, typename, edate, \n\t\t\t\t\tdescription, amount, username, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cc['ccid']}', 'ct', 'Salary', '{$Date}', \n\t\t\t\t\t'Salary for employee,  {$myEmp['fnames']} {$myEmp['sname']}', '{$amount}', '" . USER_NAME . "', '" . USER_DIV . "'\n\t\t\t\t)";
            $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
        }
    }
    /* update printslip setting */
    setCSetting("EMP_PRINTSLIP", $printslip);
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if ($printslip != "n") {
        $OUTPUT = "<script>printer('salwages/payslip-print.php?id={$id}');spmove('../main.php');</script>";
    } else {
        $OUTPUT = "\n\t\t\t<h3>Process Employee Salary</h3>\n\t\t\tSuccessfully processed salary.<br /><br />" . mkQuickLinks(ql("salaries-staff.php", "Process Employee Salary"), ql("../admin-employee-view.php", "View Employees/Process Salaries by Batch"), ql("../admin-employee-add.php", "Add New Employee"), ql("settings-acc-edit.php", "Salary Settings"));
    }
    //$OUTPUT .= "<script>move('../index-salaries.php');</script>";
    require "../template.php";
}
function write($_POST)
{
    $_POST = var_makesafe($_POST);
    extract($_POST);
    $week += 0;
    if (!isset($button)) {
        return enter($_POST);
    }
    if (!isset($date_day)) {
        exit;
    }
    require_lib("validate");
    $v = new validate();
    //$v->isOk ($empnum, "num", 1, 20, "Invalid employee number.");
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->isOk($date_day, "num", 10, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    $date = $date_year . "-" . $date_month . "-" . $date_day;
    $salconacc = gethook("accnum", "salacc", "name", "salaries control");
    $intrec = gethook("accnum", "salacc", "name", "interestreceived");
    $commacc = gethook("accnum", "salacc", "name", "Commission");
    $abonusacc = gethook("accnum", "salacc", "name", "Bonus");
    $payeacc = gethook("accnum", "salacc", "name", "PAYE");
    $uifacc = gethook("accnum", "salacc", "name", "UIF");
    $uifbal = gethook("accnum", "salacc", "name", "uifbal");
    $sdlbal = gethook("accnum", "salacc", "name", "sdlbal");
    $pa = gethook("accnum", "salacc", "name", "pension");
    $ma = gethook("accnum", "salacc", "name", "medical");
    $cash_account = gethook("accnum", "salacc", "name", "cash");
    $retire = gethook("accnum", "salacc", "name", "retire");
    $provident = gethook("accnum", "salacc", "name", "provident");
    $refnum = getrefnum($date);
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_conn('cubit');
    $i = 0;
    $Sl = "SELECT * FROM salset";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) > 0) {
        $con = true;
    } else {
        $con = false;
    }
    if ($con) {
        $uifexp = $salacc;
        $sdlexp = $salacc;
        $pax = $salacc;
        $max = $salacc;
        $retiree = $salacc;
    }
    $Sl = "SELECT * FROM employees WHERE div='" . USER_DIV . "' ORDER BY sname,fnames";
    $Rr = db_exec($Sl) or errDie("Unable to get data.");
    $out = "<script>";
    $batch_setting = getCSetting("PRINT_PSLIPS_BATCH");
    if (isset($batch_setting) and $batch_setting == "yes") {
        if ($printslip != "n") {
            $out .= "nhprinter('salwages/payslip-print.php?batch=";
        }
    }
    while ($data = pg_fetch_array($Rr)) {
        if (!isset($emps[$data['empnum']]) || isset($emps_already[$data["empnum"]])) {
            continue;
        }
        $providente = $data["expacc_provident"];
        $retiree = $data["expacc_ret"];
        $pax = $data["expacc_pension"];
        $uifexp = $data["expacc_uif"];
        $max = $data["expacc_medical"];
        $dedgenerale = $data["expacc_other"];
        $sdlexp = $data["expacc_sdl"];
        $salacc = $data["expacc_salwages"];
        $loanexp = $data["expacc_loan"];
        $id = $data['empnum'];
        $basic_sal_save[$id] = $basic_sal[$id];
        # Multiply basic_sal add overtime
        if (isset($multi[$id])) {
            $basic_sal[$id] = sprint($basic_sal[$id] * $multi[$id]);
        }
        $basic_sal[$id] = sprint($basic_sal[$id]);
        $bonus[$id] = sprint($bonus[$id]);
        $annual[$id] = sprint($annual[$id]);
        $abonus[$id] = sprint($abonus[$id]);
        $commission[$id] = sprint($commission[$id]);
        $all_travel[$id] = sprint($all_travel[$id]);
        $loaninstall[$id] = sprint($loaninstall[$id]);
        $comp_pension[$id] = sprint($comp_pension[$id]);
        $emp_pension[$id] = sprint($emp_pension[$id]);
        $comp_provident[$id] = sprint($comp_provident[$id]);
        $emp_provident[$id] = sprint($emp_provident[$id]);
        $comp_uif[$id] = sprint($comp_uif[$id]);
        $emp_uif[$id] = sprint($emp_uif[$id]);
        $comp_ret[$id] = sprint($comp_ret[$id]);
        $emp_ret[$id] = sprint($emp_ret[$id]);
        $comp_medical[$id] = sprint($comp_medical[$id]);
        $emp_medical[$id] = sprint($emp_medical[$id]);
        $comp_other[$id] = sprint($comp_other[$id]);
        $emp_other[$id] = sprint($emp_other[$id]);
        $novert[$id] += 0;
        $hovert[$id] += 0;
        $overamt[$id] = sprint($overamt[$id]);
        $sdl[$id] = sprint($comp_sdl[$id]);
        $ecost = $basic_sal[$id] + $overamt[$id] + $all_travel[$id] + $bonus[$id] + $annual[$id] + $sdl[$id] + $all_beforeamount[$id] + $all_afteramount[$id] + $comp_pension[$id] + $comp_uif[$id] + $comp_ret[$id] + $comp_medical[$id] + $comp_provident[$id] + $comp_other[$id] + $all_beforeamount[$id] + $all_afteramount[$id];
        $ecost = sprint($ecost);
        //		writetrans($uifexp,$uifbal , $date, $refnum, $comp_uif[$id], "Company UIF Contribution,  $data[fnames] $data[sname].");
        writetrans($sdlexp, $sdlbal, $date, $refnum, $sdl[$id], "SDL,  {$data['fnames']} {$data['sname']}.");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        db_conn('cubit');
        $Sl = "UPDATE employees SET balance=balance+({$grossal_nodedall[$id]}) WHERE empnum = '{$data['empnum']}'";
        $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        empledger($data['empnum'], $salacc, $date, $refnum, "Gross Salary", $grossal_nodedall[$id], "c");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        writetrans($salacc, $salconacc, $date, $refnum, $grossal_nodedall[$id], "Gross Salary proccessing for employee,  {$data['fnames']} {$data['sname']}.");
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        if ($emp_uif[$id] > 0) {
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance-({$emp_uif[$id]}) WHERE empnum = '{$data['empnum']}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($data['empnum'], $uifacc, $date, $refnum, "UIF", $emp_uif[$id], "d");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($salconacc, $uifbal, $date, $refnum, $emp_uif[$id], "UIF for employee,  {$data['fnames']} {$data['sname']}.");
        }
        if ($comp_uif[$id] > 0) {
            writetrans($uifexp, $uifbal, $date, $refnum, $emp_uif[$id], "UIF for employee,  {$data['fnames']} {$data['sname']}.");
        }
        if ($commission[$id] > 0) {
            if ($con) {
                $commacc = $salacc;
            }
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance+({$commission[$id]}) WHERE empnum = '{$data['empnum']}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($data['empnum'], $commacc, $date, $refnum, "Commission", $commission[$id], "c");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($commacc, $salconacc, $date, $refnum, $commission[$id], "Commission for employee,  {$data['fnames']} {$data['sname']}.");
        }
        if ($abonus[$id] > 0) {
            if ($con) {
                $abonusacc = $salacc;
            }
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance+({$abonus[$id]}) WHERE empnum = '{$data['empnum']}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($data['empnum'], $abonusacc, $date, $refnum, "Bonus", $abonus[$id], "c");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($abonusacc, $salconacc, $date, $refnum, $abonus[$id], "Bonus for employee,  {$data['fnames']} {$data['sname']}.");
        }
        if ($paye[$id] > 0) {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance-({$paye[$id]}) WHERE empnum = '{$data['empnum']}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($data['empnum'], $payeacc, $date, $refnum, "PAYE", $paye[$id], "d");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($salconacc, $payeacc, $date, $refnum, $paye[$id], "PAYE for employee,  {$data['fnames']} {$data['sname']}.");
        }
        if ($comp_pension[$id] > 0) {
            writetrans($pax, $pa, $date, $refnum, $comp_pension[$id], "Company Pension Contribution,  {$data['fnames']} {$data['sname']}.");
        }
        if ($comp_medical[$id] > 0) {
            writetrans($max, $ma, $date, $refnum, $comp_medical[$id], "Company Medical Contribution,  {$data['fnames']} {$data['sname']}.");
        }
        if ($emp_pension[$id] > 0) {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance-({$emp_pension[$id]}) WHERE empnum = '{$data['empnum']}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($data['empnum'], $pa, $date, $refnum, "Pension Contribution", $emp_pension[$id], "d");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($salconacc, $pa, $date, $refnum, $emp_pension[$id], "Employee Pension Contribution,  {$data['fnames']} {$data['sname']}.");
        }
        if ($emp_medical[$id] > 0) {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance-({$emp_medical[$id]}) WHERE empnum = '{$data['empnum']}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($data['empnum'], $ma, $date, $refnum, "Medical Contribution", $emp_medical[$id], "d");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($salconacc, $ma, $date, $refnum, $emp_medical[$id], "Employee Medical Contribution,  {$data['fnames']} {$data['sname']}.");
        }
        if ($comp_provident[$id] > 0) {
            writetrans($providente, $provident, $date, $refnum, $comp_provident[$id], "Company Provident Fund Contribution, {$data['fnames']} {$data['sname']}.");
        }
        if ($emp_provident[$id] > 0) {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance-({$emp_provident[$id]}) WHERE empnum = '{$data['empnum']}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($data['empnum'], $provident, $date, $refnum, "Provident Fund Contribution", $emp_provident[$id], "d");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($salconacc, $provident, $date, $refnum, $emp_provident[$id], "Provident Fund Contribution,  {$data['fnames']} {$data['sname']}.");
        }
        if (false && $comp_other[$id] > 0) {
            writetrans($dedgenerale, $dedgeneral, $date, $refnum, $comp_other[$id], "Company Contribution to Other Deductions, {$data['fnames']} {$data['sname']}.");
        }
        if (false && $emp_other[$id] > 0) {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance-({$emp_other[$id]}) WHERE empnum = '{$data['empnum']}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($data['empnum'], $dedgeneral, $date, $refnum, "Other Deductions Contribution", $emp_other[$id], "d");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($salconacc, $dedgeneral, $date, $refnum, $emp_other[$id], "Other Deductions Contribution,  {$data['fnames']} {$data['sname']}.");
        }
        if ($emp_ret[$id] > 0) {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance-({$emp_ret[$id]}) WHERE empnum = '{$data['empnum']}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($data['empnum'], $retire, $date, $refnum, "Retirement Annuity Contribution", $emp_ret[$id], "d");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($salconacc, $retire, $date, $refnum, $emp_ret[$id], "Employee Retirement Annuity Contribution,  {$data['fnames']} {$data['sname']}.");
        }
        if ($comp_ret[$id] > 0) {
            writetrans($retiree, $retire, $date, $refnum, $comp_ret[$id], "Company Retirement Annuity Contribution,  {$data['fnames']} {$data['sname']}.");
        }
        $paidamount[$id] += 0;
        db_conn('cubit');
        $mons = "{$month};";
        $due = sprint($nettpay[$id] - $paidamount[$id]);
        //, balance=balance+'$due'
        $sql = "\n\t\t\tUPDATE employees \n\t\t\tSET lastpay = '{$mons}', loanamt = (loanamt - cast(float '{$loaninstall[$id]}' as numeric)), \n\t\t\t\tloanfringe = (loanfringe - cast(float '{$fringe_loan[$id]}' as numeric)) \n\t\t\tWHERE empnum = '{$data['empnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to get employee details.");
        // check if loan is 0, then unmark loan as active, and store in archive
        $sql = "SELECT loanid FROM employees WHERE loanamt=0 AND empnum='{$data['empnum']}' AND gotloan='t'::bool";
        $rslt = db_exec($sql) or errDie("Error reading employee details for loan.");
        if (pg_num_rows($rslt) > 0) {
            $loanid = pg_fetch_result($rslt, 0, 0);
            $sql = "UPDATE employees SET gotloan='f'::bool, loaninstall='0' WHERE empnum='{$data['empnum']}'";
            $rslt = db_exec($sql) or errDie("Unable to update employee loan status.");
            $sql = "UPDATE emp_loanarchive SET donedata=CURRENT_DATE WHERE id='{$loanid}'";
            $rslt = db_exec($sql) or errDie("Unable to archive loan.");
            $sql = "SELECT loanint_unpaid FROM employees WHERE empnum='{$data['empnum']}'";
            $rslt = db_exec($sql) or errDie("Error reading loan interest for installment.");
            $loanint[$id] = sprint(pg_fetch_result($rslt, 0, 0));
        } else {
            if ($loaninstall[$id] > 0) {
                $sql = "SELECT loanamt_tot, loanint_amt FROM employees WHERE empnum='{$data['empnum']}'";
                $rslt = db_exec($sql) or errDie("Error reading loan interest for installment.");
                $loan_tot = pg_fetch_result($rslt, 0, 0);
                $loan_totint = pg_fetch_result($rslt, 0, 1);
                $loanint[$id] = sprint($loaninstall[$id] / $loan_tot * $loan_totint);
            } else {
                $loanint[$id] = 0;
            }
        }
        $sql = "\n\t\t\tUPDATE employees \n\t\t\tSET loanint_unpaid = (loanint_unpaid - cast(float '{$loanint[$id]}' as numeric)) \n\t\t\tWHERE empnum = '{$data['empnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update employee interest.");
        if ($loaninstall[$id] > 0 && !empty($loanexp)) {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            db_conn('cubit');
            $Sl = "UPDATE employees SET balance=balance-({$loaninstall[$id]}) WHERE empnum = '{$data['empnum']}'";
            $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
            empledger($data['empnum'], $loanexp, $date, $refnum, "Loan Instalment", $loaninstall[$id], "d");
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            writetrans($salconacc, $loanexp, $date, $refnum, $loaninstall[$id] - $loanint[$id], "Loan Installment for employee,  {$data['fnames']} {$data['sname']}.");
            writetrans($salconacc, $intrec, $date, $refnum, $loanint[$id], "Loan Interest for employee,  {$data['fnames']} {$data['sname']}.");
            /* record this month's loan amounts (for reversal purposes) */
            // determine the salary period
            switch ($data["payprd"]) {
                case "d":
                    $lprd = date_part($date, DP_DAY);
                    break;
                case "m":
                case "f":
                case "w":
                default:
                    $lprd = $week;
                    break;
            }
            // record it!
            db_conn("cubit");
            $sql = "\n\t\t\t\tINSERT INTO cubit.emp_loaninstallments (\n\t\t\t\t\tempnum, fdate, fperiod, fmonth, fyear, installment, interest, \n\t\t\t\t\tfringe\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$data['empnum']}', '{$date}', '{$lprd}', '{$month}', '" . EMP_YEAR . "', '{$loaninstall[$id]}', '{$loanint[$id]}', \n\t\t\t\t\t'{$fringe_loan[$id]}'\n\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Error record loan fringe benefit.");
        }
        if (!isset($accid[$id])) {
            $accid[$id] = 0;
        }
        $totded[$id] = sprint($de_beforeamount[$id] + $de_afteramount[$id] + $emp_pension[$id] + $emp_medical[$id] + $emp_provident[$id] + $emp_ret[$id] + $emp_other[$id]);
        $totded_employer[$id] = sprint($de_beforeamount_emp[$id] + $de_afteramount_emp[$id] + $comp_pension[$id] + $comp_medical[$id] + $comp_provident[$id] + $comp_ret[$id] + $comp_other[$id]);
        $totall[$id] = sprint($totall[$id]);
        $np = $nettpay[$id];
        if (isset($rbsa[$id])) {
            $np = sprint($np - array_sum($rbsa[$id]));
        }
        if ($data["payprd"] == "d") {
            $week = $pday;
        }
        if (empty($novert[$id])) {
            $novert[$id] = "0";
        }
        if (empty($hovert[$id])) {
            $hovert[$id] = "0";
        }
        db_conn("cubit");
        $Sl = "\n\t\t\tINSERT INTO cubit.salpaid (\n\t\t\t\tempnum, month, bankid, salary, comm, uifperc, uif, payeperc, \n\t\t\t\tpaye, totded, totded_employer, totallow, loanins, \n\t\t\t\ttot_fringe, div, display, saldate, week, cyear, novert, \n\t\t\t\thovert, taxed_sal, hours, salrate, bonus\n\t\t\t) VALUES (\n\t\t\t\t'{$data['empnum']}', '{$month}', '{$accid[$id]}', '{$np}', '{$commission[$id]}', '0', '{$emp_uif[$id]}', '0', \n\t\t\t\t'{$paye[$id]}', '{$totded[$id]}', '{$totded_employer[$id]}', '{$totall[$id]}', '{$loaninstall[$id]}', \n\t\t\t\t'{$fringe_tot[$id]}', '" . USER_DIV . "', '','{$date}','{$week}', '" . EMP_YEAR . "', '{$novert[$id]}', \n\t\t\t\t'{$hovert[$id]}', '{$paye_salary[$id]}', '{$multi[$id]}','{$basic_sal_save[$id]}', '{$abonus[$id]}'\n\t\t\t)";
        $Ry = db_exec($Sl) or errDie("Unable to insert record.");
        $pid = pglib_lastid("salpaid", "id");
        // fringe benefits
        if (isset($fringeid[$id])) {
            foreach ($fringeid[$id] as $i => $fid) {
                //				empledger($data["empnum"], $fringeaccs[$id][$i], $date, $refnum,"Fringe Benefit, ".$fringename[$id][$i], $fringebens[$id][$i], "d");
                //				writetrans($salconacc, $fringeaccs[$id][$i], $date, $refnum, $fringebens[$id][$i], "Fringe Benefit for employee, $data[fnames] $data[sname].");
            }
        }
        /*		db_conn('cubit');
        		// allowances
        		$i = 0;
        		$sql = "SELECT * FROM allowances WHERE div = '".USER_DIV."' ORDER BY allowance";
        		$allowRslt = db_exec ($sql) or errDie ("Unable to select allowances from database.");
        		if (pg_numrows ($allowRslt) > 0) {
        
        			while ($myAllow = pg_fetch_array ($allowRslt)) {
        
        				db_conn('cubit');
        
        				# check if employee has allowance
        				$sql = "SELECT * FROM empallow WHERE allowid='$myAllow[id]' AND empnum='$data[empnum]' AND div = '".USER_DIV."'";
        				$empAllowRslt = db_exec ($sql) or errDie ("Unable to select allowance info from database.");
        				if (pg_numrows ($empAllowRslt) > 0) {
        					$dataAllow = pg_fetch_array ($empAllowRslt);
        
        					if ( ($allowances[$id][$i]=sprint($allowances[$id][$i])) <= 0 ) continue;
        
        					$Sl="INSERT INTO emp_inc(emp,year,period,date,payslip,type,code,description,qty,rate,amount,ex)
        						VALUES ('$data[empnum]','$year','$month','$date','$pid','$myAllow[id]','','$myAllow[allowance]','1','0','".$allowances[$id][$i]."','')";
        					$Ri=db_exec($Sl) or errDie("unable to insert data.1");
        
        					if($con) {
        						$myAllow['accid']=$salacc;
        					}
        
        					///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        					db_conn('cubit');
        
        					$Sl = "UPDATE employees SET balance=balance+(".$allowances[$id][$i].") WHERE empnum = '$data[empnum]'";
        					$Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        
        					empledger($data['empnum'], $allowaccs[$id][$i], $date, $refnum,"Allowance" , $allowances[$id][$i] , "c");
        
        					///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        					writetrans($allowaccs[$id][$i], $salconacc, $date, $refnum, $allowances[$id][$i], "Allowances for employee, $data[fnames] $data[sname].");
        				}
        				$i++;
        			}
        		}*/
        $frinupd = new dbUpdate("emp_frin", "cubit");
        if (isset($fringebens[$id])) {
            foreach ($fringebens[$id] as $key => $value) {
                $cols = grp(m("emp", $data["empnum"]), m("year", EMP_YEAR), m("period", $month), m("week", $week), m("fdate", $date), m("payslip", $pid), m("code", $key), m("description", sprint($fringename[$id][$key])), m("qty", 1), m("amount", $fringebens[$id][$key]));
                $frinupd->setCols($cols);
                $frinupd->run(DB_INSERT);
            }
        }
        if ($fringe_loan[$id] > 0) {
            $cols = grp(m("emp", $data["empnum"]), m("year", EMP_YEAR), m("period", $month), m("fdate", $date), m("payslip", $pid), m("code", "FRINLOAN"), m("description", "Loan Fringe Benefit"), m("qty", 1), m("amount", $fringe_loan[$id]));
            $frinupd->setCols($cols);
            $frinupd->run(DB_INSERT);
        }
        if ($fringe_medical[$id] > 0) {
            $cols = grp(m("emp", $data["empnum"]), m("year", EMP_YEAR), m("period", $month), m("fdate", $date), m("payslip", $pid), m("code", "FRINMED"), m("description", "Medical Fringe Benefit"), m("qty", 1), m("amount", $fringe_medical[$id]));
            $frinupd->setCols($cols);
            $frinupd->run(DB_INSERT);
        }
        if ($fringe_car1[$id] > 0) {
            $cols = grp(m("emp", $data["empnum"]), m("year", EMP_YEAR), m("period", $month), m("fdate", $date), m("payslip", $pid), m("code", "FRINCAR1"), m("description", "Fringe Benefit: Vehicle 1"), m("qty", 1), m("amount", $fringe_car1[$id]));
            $frinupd->setCols($cols);
            $frinupd->run(DB_INSERT);
        }
        if ($fringe_car2[$id] > 0) {
            $cols = grp(m("emp", $data["empnum"]), m("year", EMP_YEAR), m("period", $month), m("fdate", $date), m("payslip", $pid), m("code", "FRINCAR2"), m("description", "Fringe Benefit: Vehicle 2"), m("qty", 1), m("amount", $fringe_car2[$id]));
            $frinupd->setCols($cols);
            $frinupd->run(DB_INSERT);
        }
        // allowances
        if (isset($allowid[$id]) && is_array($allowid[$id]) && count($allowid[$id]) > 0) {
            foreach ($allowid[$id] as $k => $dummy) {
                if (($allowances[$id][$k] = sprint($allowances[$id][$k])) <= 0) {
                    continue;
                }
                db_conn('cubit');
                $sql = "\n\t\t\t\t\tINSERT INTO emp_inc (\n\t\t\t\t\t\temp, year, period, week, date, payslip, type, code, \n\t\t\t\t\t\tdescription, qty, rate, amount, ex\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$data['empnum']}', '" . EMP_YEAR . "', '{$month}', '{$week}', '{$date}', '{$pid}', '" . $allowid[$id][$k] . "', '', \n\t\t\t\t\t\t'" . $allowname[$id][$k] . "', '1', '0', '" . $allowances[$id][$k] . "', ''\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("unable to insert data.1");
                if ($con) {
                    $allowaccs[$id][$k] = $salacc;
                }
                $Sl = "UPDATE employees SET balance=balance+(" . $allowances[$id][$k] . ") WHERE empnum = '{$data['empnum']}'";
                $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
                empledger($data['empnum'], $allowaccs[$id][$k], $date, $refnum, "Allowance", $allowances[$id][$i], "c");
                writetrans($allowaccs[$id][$k], $salconacc, $date, $refnum, $allowances[$id][$k], "Allowances for employee, {$data['fnames']} {$data['sname']}.");
            }
        }
        /*		db_conn('cubit');
        		# Deductions
        		$i = 0;
        		$sql = "SELECT * FROM salded WHERE div = '".USER_DIV."' ORDER BY deduction";
        		$deductRslt = db_exec ($sql) or errDie ("Unable to select deductions from database.");
        		if (pg_numrows ($deductRslt) >0) {
        
        			while ($myDeduct = pg_fetch_array ($deductRslt)) {
        
        				db_conn('cubit');
        
        				# check if employee has deduction
        				$sql = "SELECT * FROM empdeduct WHERE dedid='$myDeduct[id]' AND empnum='$data[empnum]' AND div = '".USER_DIV."'";
        				$empDeductRslt = db_exec ($sql) or errDie ("Unable to select Deduction info from database.");
        				if (pg_numrows ($empDeductRslt) > 0) {
        					$dataDeduct = pg_fetch_array ($empDeductRslt);
        					if ( ($deductions[$id][$i]=sprint($deductions[$id][$i])) > 0 ) {
        						# Debit salaries control acc and credit  acc
        						$Sl="INSERT INTO emp_ded(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES
        							('$data[empnum]','$year','$month','$date','$pid','$myDeduct[id]','','$myDeduct[deduction]','1','0','".$deductions[$id][$i]."')";
        						$Ri=db_exec($Sl) or errDie("unable to insert data.2");
        					}
        
        					if ( ($employer_deductions[$id][$i]=sprint($employer_deductions[$id][$i])) > 0 ) {
        						$Sl="INSERT INTO emp_com(emp,year,period,date,payslip,type,code,description,qty,rate,amount) VALUES
        							('$data[empnum]','$year','$month','$date','$pid','$myDeduct[id]','','$myDeduct[deduction]','1','0','".$employer_deductions[$id][$i]."')";
        						//$Ri=db_exec($Sl) or errDie("unable to insert data1.");
        					}
        
        					///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        					db_conn('cubit');
        
        					$Sl = "UPDATE employees SET balance=balance-(".$deductions[$id][$i].") WHERE empnum = '$data[empnum]'";
        					$Rp = db_exec($Sl) or errDie("Unable to get employee details.");
        
        					empledger($data['empnum'], $myDeduct['accid'], $date, $refnum,"Deduction" , $deductions[$id][$i], "d");
        
        					///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        					writetrans($salconacc, $dedaccs[$id][$i], $date, $refnum, $deductions[$id][$i], "Deductions for employee, $data[fnames] $data[sname].");
        
             				$i++;
        				}
        			}
        		}*/
        # Deductions
        if (isset($deductid[$id]) && is_array($deductid[$id]) && count($deductid[$id]) > 0) {
            foreach ($deductid[$id] as $k => $dummy) {
                if (($deductions[$id][$k] = sprint($deductions[$id][$k])) <= 0) {
                    continue;
                }
                db_conn('cubit');
                # Debit salaries control acc and credit  acc
                $sql = "\n\t\t\t\t\tINSERT INTO emp_ded (\n\t\t\t\t\t\temp, year, period, week, date, payslip, type, code, \n\t\t\t\t\t\tdescription, qty, rate, amount\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$data['empnum']}', '" . EMP_YEAR . "', '{$month}', '{$week}', '{$date}', '{$pid}', '" . $deductid[$id][$k] . "', '', \n\t\t\t\t\t\t'" . $deductname[$id][$k] . "', '1', '0', '" . $deductions[$id][$k] . "'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("unable to insert data.2");
                $sql = "UPDATE employees SET balance=balance-(" . $deductions[$id][$k] . ") WHERE empnum = '{$data['empnum']}'";
                $rslt = db_exec($sql) or errDie("Unable to get employee details.");
                empledger($data['empnum'], $dedaccs[$id][$k], $date, $refnum, "Deduction", $deductions[$id][$k], "d");
                writetrans($salconacc, $dedaccs[$id][$k], $date, $refnum, $deductions[$id][$k], "Deductions for employee, {$data['fnames']} {$data['sname']}.");
            }
        }
        db_conn('cubit');
        $Sl = "SELECT * FROM rbs ORDER BY name";
        $Rl = db_exec($Sl) or errDie("Unable to get data.");
        if (pg_num_rows($Rl) > 0) {
            while ($td = pg_fetch_array($Rl)) {
                $rbsa[$id][$td['id']] = sprint($rbsa[$id][$td['id']]);
                db_conn('cubit');
                $sql = "\n\t\t\t\t\tINSERT INTO emp_inc (\n\t\t\t\t\t\temp, year, period, week, date, payslip, type, code, description, \n\t\t\t\t\t\tqty, rate, amount, ex\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$data['empnum']}', '" . EMP_YEAR . "', '{$month}', '{$week}', '{$date}', '{$pid}', '{$td['id']}', '', '{$td['name']}', \n\t\t\t\t\t\t'1', '0', '" . $rbsa[$id][$td['id']] . "', 'RBS'\n\t\t\t\t\t)";
                db_exec($sql) or errDie("unable to insert data.3");
                $sql = "UPDATE employees SET balance=balance+(" . $rbsa[$id][$td['id']] . ") WHERE empnum = '{$data['empnum']}'";
                db_exec($sql) or errDie("Unable to get employee details.");
                empledger($data['empnum'], $td['account'], $date, $refnum, "Reimbursement", $rbsa[$id][$td['id']], "c");
                writetrans($td['account'], $salconacc, $date, $refnum, $rbsa[$id][$td['id']], "Reimbursement for employee, {$data['fnames']} {$data['sname']}.");
            }
        }
        if (isset($subsname)) {
            foreach ($subsname[$id] as $sid => $sn) {
                if (empty($subsamt[$id][$sid]) || $subsamt[$id][$sid] <= 0) {
                    continue;
                }
                $samt = sprint($subsamt[$id][$sid]);
                $i++;
                db_conn('cubit');
                $cols = grp(m("emp", $data["empnum"]), m("year", EMP_YEAR), m("period", $month), m("week", $week), m("date", $date), m("payslip", $pid), m("type", $sid), m("code", ""), m("description", $subsname[$id][$sid]), m("qty", 1), m("rate", 0), m("amount", $samt), m("ex", "SUBS"));
                $subin = new dbUpdate("emp_inc", "cubit", $cols);
                $subin->run(DB_INSERT);
                $cols = grp(m("balance", raw("balance+({$samt})")));
                $subin->setTable("employees");
                $subin->setOpt($cols, wgrp(m("empnum", $data["empnum"])));
                $subin->run(DB_UPDATE);
                empledger($data["empnum"], $subsacc[$id][$sid], $date, $refnum, "Subsistence Allowance: " . $subsname[$id][$sid], $samt, "c");
                writetrans($subsacc[$id][$sid], $salconacc, $date, $refnum, $samt, "Subsistence Allownace (" . $subsname[$id][$sid] . ") for employee, {$data['fnames']} {$data['sname']}.");
            }
        }
        if ($paidamount[$id] > 0) {
            if ($data['paytype'] == "Cash") {
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                db_conn('cubit');
                $Sl = "UPDATE employees SET balance=balance-({$paidamount[$id]}) WHERE empnum = '{$data['empnum']}'";
                $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
                empledger($data['empnum'], $cash_account, $date, $refnum, "Payment(Cash)", $paidamount[$id], "d");
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                writetrans($salconacc, $cash_account, $date, $refnum, $paidamount[$id], "Salary Payment(Cash) for employee,  {$data['fnames']} {$data['sname']}.");
            } elseif ($data['paytype'] == "Ledger Account") {
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                db_conn('cubit');
                $Sl = "UPDATE employees SET balance=balance-({$paidamount[$id]}) WHERE empnum = '{$data['empnum']}'";
                $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
                empledger($data['empnum'], $account[$id], $date, $refnum, "Payment(Ledger Account)", $paidamount[$id], "d");
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                writetrans($salconacc, $account[$id], $date, $refnum, $paidamount[$id], "Salary Payment(Ledger Account) for employee,  {$data['fnames']} {$data['sname']}.");
            } else {
                $accid[$id] += 0;
                core_connect();
                $sql = "SELECT * FROM bankacc WHERE accid = '{$accid[$id]}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
                # check if link exists
                if (pg_numrows($rslt) < 1) {
                    return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.";
                }
                $bank = pg_fetch_array($rslt);
                $bankacc = $bank["accnum"];
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                db_conn('cubit');
                $Sl = "UPDATE employees SET balance=balance-({$paidamount[$id]}) WHERE empnum = '{$data['empnum']}'";
                $Rp = db_exec($Sl) or errDie("Unable to get employee details.");
                empledger($data['empnum'], $bankacc, $date, $refnum, "Payment(Bank)", $paidamount[$id], "d");
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                if ($paidamount[$id] > 0) {
                    writetrans($salconacc, $bankacc, $date, $refnum, $paidamount[$id], "Salary Payment for employee(Bank),  {$data['fnames']} {$data['sname']}.");
                    banktrans($accid[$id], "withdrawal", $date, "{$data['fnames']} {$data['sname']}", "Salary Payment for employee,  {$data['fnames']} {$data['sname']}", 0, $paidamount[$id], $salconacc, $data['empnum']);
                }
            }
        }
        db_conn('cubit');
        if ($comp_uif[$id] > 0) {
            $Sl = "INSERT INTO emp_com(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','UIFC','','UIF','1','0','{$comp_uif[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data1.");
        }
        if ($emp_uif[$id] > 0) {
            $Sl = "INSERT INTO emp_ded(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','UIFE','','UIF','1','0','{$emp_uif[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data3.");
        }
        if ($sdl[$id] > 0) {
            $Sl = "INSERT INTO emp_com(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','SDL','','SDL','1','0','{$sdl[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data2.");
        }
        if ($paye[$id] > 0) {
            $Sl = "INSERT INTO emp_ded(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','PAYE','','PAYE','1','0','{$paye[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data3.");
        }
        if ($basic_sal[$id] > 0) {
            $Sl = "INSERT INTO emp_inc(emp,year,period,week,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','INC','','Basic Salary','','1','0','{$basic_sal[$id]}','')";
            $Ri = db_exec($Sl) or errDie("unable to insert data4.");
        }
        if ($data["loanpayslip"] > 0) {
            $Sl = "INSERT INTO emp_inc(emp,year,period,week,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\n\t\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','LOAN','','Employee Loan','','1','0','{$data['loanpayslip']}','')";
            $Ri = db_exec($Sl) or errDie("unable to insert loan data for employee income on payslip.");
            $sql = "UPDATE employees SET loanpayslip='0' WHERE empnum='{$data['empnum']}'";
            $rslt = db_exec($sql) or errDie("Error updating loan information for payslip.");
        }
        if ($bonus[$id] > 0 && $data["payprd"] != "f" && $data["payprd"] != "w") {
            $Sl = "INSERT INTO emp_inc(emp,year,period,week,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','INCB','','Bonus','','1','0','{$bonus[$id]}','')";
            $Ri = db_exec($Sl) or errDie("unable to insert data5.");
        } else {
            if ($bonus[$id] > 0) {
                $Sl = "INSERT INTO emp_inc(emp,year,period,week,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','INCB','','Special Bonus/Additional Salary','','1','0','{$bonus[$id]}','')";
                $Ri = db_exec($Sl) or errDie("unable to insert data5.");
            }
        }
        if ($annual[$id] > 0) {
            $Sl = "INSERT INTO emp_inc(emp,year,period,week,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','INCAB','','Annual Bonus','','1','0','{$annual[$id]}','')";
            $Ri = db_exec($Sl) or errDie("unable to insert data5.");
        }
        if ($commission[$id] > 0) {
            $Sl = "INSERT INTO emp_inc(emp,year,period,week,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','INCC','','Commission','','1','0','{$commission[$id]}','')";
            $Ri = db_exec($Sl) or errDie("unable to insert data6.");
        }
        if ($abonus[$id] > 0) {
            $Sl = "INSERT INTO emp_inc(emp,year,period,week,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','INCAB','','Bonus','','1','0','{$abonus[$id]}','')";
            $Ri = db_exec($Sl) or errDie("unable to insert data6a.");
        }
        if ($all_travel[$id] > 0) {
            $Sl = "INSERT INTO emp_inc(emp,year,period,week,date,payslip,type,code,description,pension,qty,rate,amount,ex) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','INCT','','Travel Allowance','','1','0','{$all_travel[$id]}','')";
            $Ri = db_exec($Sl) or errDie("unable to insert data7.");
        }
        if ($loaninstall[$id] > 0) {
            $Sl = "INSERT INTO emp_ded(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','DEDL','','Loan Repayment','1','0','{$loaninstall[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data8.");
        }
        if ($comp_pension[$id] > 0) {
            $Sl = "INSERT INTO emp_com(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','COMP','','Pension','1','0','{$comp_pension[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data9.");
        }
        if ($emp_pension[$id] > 0) {
            $Sl = "INSERT INTO emp_ded(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','DEDP','','Pension','1','0','{$emp_pension[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data10.");
        }
        if ($comp_provident[$id] > 0) {
            $Sl = "INSERT INTO emp_com(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','COMV','','Provident','1','0','{$comp_provident[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data9.");
        }
        if ($emp_provident[$id] > 0) {
            $Sl = "INSERT INTO emp_ded(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','DEDV','','Provident','1','0','{$emp_provident[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data10.");
        }
        if ($comp_other[$id] > 0) {
            $Sl = "INSERT INTO emp_com(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','COMO','','Other Deductions','1','0','{$comp_other[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data9.");
        }
        if ($emp_other[$id] > 0) {
            $Sl = "INSERT INTO emp_ded(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','DEDO','','Other Deductions','1','0','{$emp_other[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data10.");
        }
        if ($comp_ret[$id] > 0) {
            $Sl = "INSERT INTO emp_com(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','COMR','','Retirement Annuity Fund','1','0','{$comp_ret[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data9.");
        }
        if ($emp_ret[$id] > 0) {
            $Sl = "INSERT INTO emp_ded(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','DEDR','','Retirement Annuity Fund','1','0','{$emp_ret[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data10.");
        }
        if ($data["fringe_car1_contrib"] > 0) {
            $Sl = "INSERT INTO emp_ded(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','DEDR','','Motorcar 1 Contribution for Use','1','0','{$data['fringe_car1_contrib']}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data10.");
        }
        if ($data["fringe_car2_contrib"] > 0) {
            $Sl = "INSERT INTO emp_ded(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','DEDR','','Motorcar 2 Contribution for Use','1','0','{$data['fringe_car2_contrib']}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data10.");
        }
        if ($comp_medical[$id] > 0) {
            $Sl = "INSERT INTO emp_com(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','COMM','','Medical Contribution','1','0','{$comp_medical[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data.11");
        }
        if ($emp_medical[$id] > 0) {
            $Sl = "INSERT INTO emp_ded(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','DEDM','','Medical Contribution','1','0','{$emp_medical[$id]}')";
            $Ri = db_exec($Sl) or errDie("unable to insert data.12");
        }
        if ($overamt[$id] > 0) {
            $Sl = "INSERT INTO emp_inc(emp,year,period,week,date,payslip,type,code,description,qty,rate,amount,ex) VALUES\n\t\t\t('{$data['empnum']}','" . EMP_YEAR . "','{$month}','{$week}','{$date}','{$pid}','INCO','','Over Time','1','0','{$overamt[$id]}','')";
            $Ri = db_exec($Sl) or errDie("unable to insert data.13");
        }
        $ecost += 0;
        db_conn('cubit');
        $Sl = "SELECT * FROM empc WHERE emp='{$data['empnum']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) > 0) {
            while ($cdata = pg_fetch_array($Ri)) {
                db_conn('cubit');
                $sql = "SELECT * FROM costcenters WHERE ccid = '{$cdata['cid']}'";
                $ccRslt = db_exec($sql) or errDie("Unable to retrieve Cost centers from database.");
                $cc = pg_fetch_array($ccRslt);
                $amount = sprint($ecost * $cdata['amount'] / 100);
                db_conn(PRD_DB);
                $sql = "\n\t\t\t\t\tINSERT INTO cctran (\n\t\t\t\t\t\tccid, trantype, typename, edate, description, \n\t\t\t\t\t\tamount, username, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cc['ccid']}', 'ct', 'Salary', '{$date}', 'Salary for employee,  {$data['fnames']} {$data['sname']}', \n\t\t\t\t\t\t'{$amount}', '" . USER_NAME . "', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
            }
        }
        $batch_setting = getCSetting("PRINT_PSLIPS_BATCH");
        if (isset($batch_setting) and $batch_setting == "yes") {
            if ($printslip != "n") {
                $out .= "{$pid}|";
            }
        } else {
            if ($printslip != "n") {
                $out .= "nhprinter('salwages/payslip-print.php?id={$pid}',{$pid});";
            }
        }
    }
    $batch_setting = getCSetting("PRINT_PSLIPS_BATCH");
    if (isset($batch_setting) and $batch_setting == "yes") {
        $out .= "',{$pid});</script>";
    } else {
        if ($printslip != "n") {
            $out .= "</script>";
            //spmove('../main.php');</script>";
        }
    }
    if ($printslip == "n") {
        $out = "\n\t\t<h3>Process Employee Salaries</h3>\n\t\tSuccessfully processed salaries for selected employees.<br /><br />";
    }
    /* update printslip setting */
    setCSetting("EMP_PRINTSLIP", $printslip);
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    //$out="";
    return $out;
}
function write($HTTP_VARS)
{
    extract($HTTP_VARS);
    if (isset($back)) {
        return enter($HTTP_VARS);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($id, "num", 1, 20, "Invalid employee number.");
    $v->isOk($bankid, "num", 1, 20, "Invalid bank number.");
    $v->isOk($paidamount, "float", 1, 10, "Invalid amount.");
    if (isset($account)) {
        $v->isOk($account, "num", 1, 100, "Invalid account.");
    }
    $ydate = mkdate($date_year, $date_month, $date_day);
    $v->isOk($ydate, "date", 1, 1, "Invalid payment date 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;
    }
    //$date=date("d-m-Y");
    $salconacc = gethook("accnum", "salacc", "name", "salaries control");
    $cash_account = gethook("accnum", "salacc", "name", "cash");
    pglib_transaction("BEGIN");
    $refnum = getrefnum($ydate);
    $paidamount = sprint($paidamount);
    db_conn('cubit');
    $Sl = "SELECT * FROM employees WHERE empnum='{$id}'";
    $Ri = db_exec($Sl) or errDie("Unable to get data.");
    if (pg_num_rows($Ri) < 1) {
        return "Invalid employee.";
    }
    $edata = pg_fetch_array($Ri);
    /* if we came from the cashbook, always use bank payment */
    if ($bankpay && $bankpay == "t") {
        $edata["paytype"] = "Cheque";
    } else {
        $bankpay = "f";
    }
    db_conn('cubit');
    $Sl = "UPDATE employees SET balance=balance-'{$paidamount}' WHERE empnum = '{$id}' AND div = '" . USER_DIV . "'";
    $Ri = db_exec($Sl) or errDie("Unable to get employee details.");
    // 	if($edata['paytype']=="Cash") {
    //
    // 		writetrans($salconacc, $cash_account, $date, $refnum, $paidamount, "Salary Payment(Cash) for employee,  $edata[fnames] $edata[sname].");
    //
    // 		empledger($id, $cash_account, $ydate, $refnum,"Payment(Cash)" ,  $paidamount, "d");
    //
    // 	}
    if ($edata['paytype'] == "Ledger Account") {
        writetrans($salconacc, $account, $ydate, $refnum, $paidamount, "Salary Payment(Ledger Account) for employee,  {$edata['fnames']} {$edata['sname']}.");
        empledger($id, $account, $ydate, $refnum, "Payment(Ledger Account)", $paidamount, "d");
    } else {
        core_connect();
        if ($edata["paytype"] == "Cash") {
            $bank = qryAccountsName("Cash on Hand", "accid");
            $bankacc = $bank["accid"];
        } else {
            $sql = "SELECT * FROM bankacc WHERE accid = '{$bankid}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
            # check if link exists
            if (pg_numrows($Rslt) < 1) {
                return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.";
            }
            $bank = pg_fetch_array($Rslt);
            $bankacc = $bank["accnum"];
            banktrans($bankid, "withdrawal", $ydate, "{$edata['fnames']} {$edata['sname']}", "Salary Payment for employee,  {$edata['fnames']} {$edata['sname']}", 0, $paidamount, $salconacc, $edata['empnum']);
        }
        writetrans($salconacc, $bankacc, $ydate, $refnum, $paidamount, "Salary Payment for employee,  {$edata['fnames']} {$edata['sname']}.");
        empledger($id, $bankacc, $ydate, $refnum, "Payment(Bank)", $paidamount, "d");
    }
    pglib_transaction("COMMIT");
    $out = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Payment Processed</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Employee payment has been processed.</td>\n\t\t\t</tr>\n\t\t</table>";
    return $out;
}