function update($_POST)
{
    # Get Vars ( banked[] )
    extract($_POST);
    # check if anything is selected
    if (!isset($banked)) {
        $err = "<li class='err'> Please Select at least one entry to update.";
        return cashbook($_POST, $err);
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    $refnum = getrefnum();
    /*refnum*/
    db_conn('core');
    $rid = pglib_lastid("save_bank_recon", "id");
    $rid++;
    # Record all trans
    foreach ($banked as $key => $cashid) {
        # Connect to database
        db_Connect();
        $sql = "SELECT * FROM cashbook WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $cashRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve details from database.", SELF);
        $cash = pg_fetch_array($cashRslt);
        # Set record as banked
        db_connect();
        $sql = "UPDATE cashbook SET banked = 'yes',rid='{$rid}' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to set bank deposit as banked in Cubit.", SELF);
    }
    // Connect to database
    db_connect();
    $sql = "SELECT * FROM cashbook WHERE bankid = '{$bankid}' AND banked = 'no' AND div = '" . USER_DIV . "' ORDER BY date DESC";
    $cashRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank transactions from database.", SELF);
    $sql = "SELECT * FROM bankacct WHERE bankid= '{$bankid}' AND div = '" . USER_DIV . "'";
    $bankRslt = db_exec($sql);
    $bank = pg_fetch_array($bankRslt);
    $cur = CUR;
    $amtd = "amount";
    if ($bank['btype'] == 'int') {
        $currs = getSymbol($bank['fcid']);
        $cur = $currs['symbol'];
        $amtd = "famount";
    }
    $tot = 0;
    $totr = 0;
    $totp = 0;
    $recpts = "";
    $paymnts = "";
    while ($cash = pg_fetch_array($cashRslt)) {
        if ($cash['trantype'] == "deposit") {
            $recpts .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$cash['date']}</td>\n\t\t\t\t\t<td>{$cash['descript']}</td>\n\t\t\t\t\t<td align='right'>{$cur} {$cash[$amtd]}</td>\n\t\t\t\t</tr>";
            $totr += $cash[$amtd];
        } else {
            $paymnts .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$cash['date']}</td>\n\t\t\t\t\t<td>{$cash['descript']}</td>\n\t\t\t\t\t<td align='right'>{$cur} {$cash[$amtd]}</td>\n\t\t\t\t</tr>";
            $totp += $cash[$amtd];
        }
        $tot += $cash[$amtd];
    }
    $reconbal = sprint($cbal + ($totr - $totp));
    # get hook account number
    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.";
    }
    $banklnk = pg_fetch_array($rslt);
    # Get bank balance
    $sql = "SELECT (debit - credit) as bal FROM trial_bal WHERE period='12' AND accid = '{$banklnk['accnum']}' AND div = '" . USER_DIV . "'";
    $brslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    $bal = pg_fetch_array($brslt);
    if ($bank['btype'] == 'int') {
        $bal['bal'] = $bank['fbalance'];
    }
    $diff = sprint($reconbal - $bal['bal']);
    $derr = "";
    if ($diff != 0) {
        $derr = "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><b class='err'>Bank statement and computer balance not balancing by</b></td>\n\t\t\t\t<td align='right'>{$cur} {$diff}</td>\n\t\t\t</tr>";
    }
    $totp = sprint($totp);
    // Layout
    $update = "\n\t\t<center>\n\t\t<h3>Bank Reconciliation Output</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form1'>\n\t\t\t<input type='hidden' name='key' value='save'>\n\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t<table cellpadding='2' cellspacing='0' border=0 bordercolor='#000000' width='80%'>\n\t\t\t<tr>\n\t\t\t\t<td colspan='10'>\n\t\t\t\t\t<table cellpadding='2' cellspacing='0' border=0 bordercolor='#000000' width=100%>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Bank Account : </b>{$bank['accname']}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td align='right'><b>Prepared By : </b>" . USER_NAME . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><b>Closing Balance As per Bank Statement : </b>{$cur} {$cbal}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td><b>Plus Outstanding Receipts :</b></td>\n\t\t\t</tr>\n\t\t\t<!--<tr><th>Date</th><th>Reference</th><th>Amount</th></tr>-->\n\t\t\t{$recpts}\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='right'><b>Sub Total</b></td>\n\t\t\t\t<td align='right'>{$cur} {$totr}</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td><b>Less Outstanding Payments :</b></td>\n\t\t\t</tr>\n\t\t\t<!--<tr><th>Date</th><th>Reference</th><th>Amount</th></tr>-->\n\t\t\t{$paymnts}\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='right'><b>Sub Total</b></td>\n\t\t\t\t<td align='right'>{$cur} {$totp}</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br><td></tr>\n\t\t\t{$derr}\n\t\t\t<tr><td><br><td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><b>Reconciled Bank Balance</b></td>\n\t\t\t\t<td align='right'>{$cur} {$reconbal}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><b>Computer Bank Balance</b></td>\n\t\t\t\t<td align='right'>{$cur} {$bal['bal']}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><b>Diff</b></td>\n\t\t\t\t<td align='right'>{$cur} {$diff}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><br></td>\n\t\t\t\t<td align='right'>____________</td>\n\t\t\t</tr>";
    $upcode = base64_encode($update);
    $button = "</table></form>";
    core_connect();
    $gendate = date("Y-m-d");
    $sql = "\n\t\tINSERT INTO save_bank_recon (\n\t\t\tbankid, gendate, recon, div\n\t\t) VALUES (\n\t\t\t'{$bankid}', '{$gendate}', '{$upcode}', '" . USER_DIV . "'\n\t\t)";
    $saveRslt = db_exec($sql) or errDie("Unable to save bank recon to database", SELF);
    $update .= $button;
    $OUTPUT = $update;
    require "../tmpl-print.php";
}
function add()
{
    core_connect();
    # Get Petty cash account
    $cashacc = gethook("accnum", "bankacc", "name", "Petty Cash");
    # Get account name for thy lame User's Sake
    $accRslt = get("core", "*", "accounts", "accid", $cashacc);
    if (pg_numrows($accRslt) < 1) {
        return "<li class='err'> Petty Cash Account not found.</li>";
    }
    $acc = pg_fetch_array($accRslt);
    # Check available funds
    $cashacc = gethook("accnum", "bankacc", "name", "Petty Cash");
    core_connect();
    $sql = "SELECT (debit - credit) as bal FROM trial_bal WHERE month='" . PRD_DB . "' AND accid = '{$cashacc}' AND div = '" . USER_DIV . "'";
    $accbRslt = db_exec($sql);
    if (pg_numrows($accbRslt) < 1) {
        return "<li class='err'> Petty Cash Account not found.</li>";
    }
    $accb = pg_fetch_array($accbRslt);
    $accb['bal'] = sprint($accb['bal']);
    # mourn if the is no money
    if ($accb['bal'] < 1) {
        return "\n\t\t\t<li class='err'> There are no Petty Cash funds available.</li>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='petty-trans.php'>Transfer funds to petty cash account</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
    }
    // Layout
    $add = "\n\t\t<h3>Funds transfer to Bank</h3>\n\t\t<table " . TMPL_tblDflts . " width='300'>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t<tr>\n\t\t\t\t<th>Field</th>\n\t\t\t\t<th>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Bank Account</td>\n\t\t\t\t<td valign='center'>\n\t\t\t\t\t<select name='bankid'>";
    db_connect();
    $sql = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '" . USER_DIV . "'";
    $banks = db_exec($sql);
    if (pg_numrows($banks) < 1) {
        return "<li class='err'> There are no accounts held at the selected Bank.</li>\n\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
    }
    while ($bacc = pg_fetch_array($banks)) {
        $add .= "<option value='{$bacc['bankid']}'>({$bacc['acctype']}) {$bacc['accname']} - {$bacc['bankname']}</option>";
    }
    if (!isset($date_day)) {
        $trans_date_setting = getCSetting("USE_TRANSACTION_DATE");
        if (isset($trans_date_setting) and $trans_date_setting == "yes") {
            $trans_date_value = getCSetting("TRANSACTION_DATE");
            $date_arr = explode("-", $trans_date_value);
            $date_year = $date_arr[0];
            $date_month = $date_arr[1];
            $date_day = $date_arr[2];
        } else {
            $date_year = date("Y");
            $date_month = date("m");
            $date_day = date("d");
        }
    }
    $add .= "\n\t\t\t\t\t</select>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t        <tr class='" . bg_class() . "'>\n\t        \t<td>Date</td>\n\t        \t<td>" . mkDateSelect("date", $date_year, $date_month, $date_day) . "</td>\n\t        </tr>\n\t        <tr class='" . bg_class() . "'>\n\t        \t<td>Received from</td>\n\t        \t<td valign='center'><input size='20' name='name' value='Petty Cash'></td>\n\t        </tr>\n\t        <tr class='" . bg_class() . "'>\n\t        \t<td>Description</td>\n\t        \t<td valign='center'><textarea cols='18' rows='2' name='descript'></textarea></td>\n\t        </tr>\n\t        <tr class='" . bg_class() . "'>\n\t        \t<td>Cheque Number</td>\n\t        \t<td valign='center'><input size='10' name='cheqnum'></td>\n\t        </tr>\n\t        <tr class='" . bg_class() . "'>\n\t        \t<td>Amount</td>\n\t        \t<td valign='center'>" . CUR . " <input type='text' size='10' name='amount'>&nbsp;&nbsp;Max : " . CUR . " {$accb['bal']}<input type='hidden' name='max' value='{$accb['bal']}'></td>\n\t        </tr>\n\t        <tr class='" . bg_class() . "'>\n\t        \t<td>Petty Cash Account</td>\n\t        \t<td><input type='hidden' name='accinv' value='{$acc['accid']}'>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t        </tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td><input type='button' value='< Cancel' onClick='javascript:history.back();'></td>\n\t\t\t\t<td valign='center'><input type='submit' value='Confirm >'></td>\n\t\t\t</tr>\n\t\t</table>";
    # main table (layout with menu)
    $OUTPUT = "\n\t\t\t<center>\n\t        <table width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td width='65%' align='left'>{$add}</td>\n\t\t\t\t\t<td valign='top' align='center'>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='65%'>\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<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        </table>";
    return $OUTPUT;
}
function add()
{
    # Suppliers Drop down selections
    db_connect();
    $sql = "SELECT cusnum,cusname,surname FROM customers WHERE location != 'int' AND div = '" . USER_DIV . "' ORDER BY surname,cusname";
    $cusRslt = db_exec($sql);
    $numrows = pg_numrows($cusRslt);
    if (empty($numrows)) {
        return "<li> There are no Debtors in Cubit.</li>";
    }
    $cust = "<select name='cusid'>";
    while ($cus = pg_fetch_array($cusRslt)) {
        $cust .= "<option value='{$cus['cusnum']}'>{$cus['cusname']} {$cus['surname']}</option>";
    }
    $cust .= "</select>";
    core_connect();
    # Get Petty cash account
    $cashacc = gethook("accnum", "bankacc", "name", "Petty Cash");
    # Get account name for thy lame User's Sake
    $accRslt = get("core", "*", "accounts", "accid", $cashacc);
    if (pg_numrows($accRslt) < 1) {
        return "<li class='err'> Petty Cash Account not found.</li>";
    }
    $acc = pg_fetch_array($accRslt);
    # Check available funds
    $cashacc = gethook("accnum", "bankacc", "name", "Petty Cash");
    core_connect();
    $sql = "SELECT (debit - credit) as bal FROM trial_bal WHERE month='" . PRD_DB . "' AND accid = '{$cashacc}' AND div = '" . USER_DIV . "'";
    $accbRslt = db_exec($sql);
    if (pg_numrows($accbRslt) < 1) {
        return "<li class='err'> Petty Cash Account not found.</li>";
    }
    $accb = pg_fetch_array($accbRslt);
    $accb['bal'] = sprint($accb['bal']);
    if (!isset($date_day)) {
        $trans_date_setting = getCSetting("USE_TRANSACTION_DATE");
        if (isset($trans_date_setting) and $trans_date_setting == "yes") {
            $trans_date_value = getCSetting("TRANSACTION_DATE");
            $date_arr = explode("-", $trans_date_value);
            $date_year = $date_arr[0];
            $date_month = $date_arr[1];
            $date_day = $date_arr[2];
        } else {
            $date_year = date("Y");
            $date_month = date("m");
            $date_day = date("d");
        }
    }
    // layout
    $add = "\n\t\t<h3>New Petty Cash Payment</h3>\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t<input type='hidden' name='cashacc' value='{$cashacc}'>\n\t\t\t<tr>\n\t\t\t\t<th>Field</th>\n\t\t\t\t<th>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Petty Cash Account</td>\n\t\t\t\t<td valign='center'>{$acc['topacc']}/{$acc['accnum']} {$acc['accname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Available Funds</td>\n\t\t\t\t<td>" . CUR . " {$accb['bal']}<input type='hidden' name='max' value='{$accb['bal']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>" . REQ . "Date</td>\n\t\t\t\t<td>" . mkDateSelect("date", $date_year, $date_month, $date_day) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>" . REQ . "Customer paid to</td>\n\t\t\t\t<td valign='center'>{$cust}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Description</td>\n\t\t\t\t<td valign='center'><textarea col='20' rows='5' name='descript'></textarea></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>" . REQ . "Amount</td>\n\t\t\t\t<td valign='center'>" . CUR . " <input type='text' size='10' name='amount'></td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td><input type='button' value='&laquo; Cancel' onClick='javascript:history.back();'></td>\n\t\t\t\t<td valign='center'><input type='submit' value='Add &raquo;'></td>\n\t\t\t</tr>\n\t\t</table>";
    # main table (layout with menu)
    $OUTPUT = "\n\t\t<center>\n\t\t<table width='100%'>\n\t\t\t<tr>\n\t\t\t\t<td width='65%' align='left'>{$add}</td>\n\t\t\t\t<td valign='top' align='center'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='65%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
function getactual()
{
    # get petty cash account
    $pcacc = gethook("accnum", "bankacc", "name", "Petty Cash");
    core_connect();
    $pcbalRs = db_exec("SELECT sum(credit) as credit, sum(debit) as debit FROM trial_bal WHERE period='" . PRD_DB . "' AND accid = '{$pcacc}'");
    $pcbal = pg_fetch_array($pcbalRs);
    $bankct = $pcbal['credit'];
    $bankdt = $pcbal['debit'];
    # get bank balances
    db_connect();
    $sql = "SELECT bankid FROM bankacct WHERE div = '" . USER_DIV . "'";
    $bankRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank account details from database.", SELF);
    while ($bnk = pg_fetch_array($bankRslt)) {
        $bacc = gethook("accnum", "bankacc", "accid", $bnk['bankid']);
        core_connect();
        $bbalRs = db_exec("SELECT sum(credit) as credit, sum(debit) as debit FROM trial_bal WHERE accid = '{$bacc}'");
        $bbal = pg_fetch_array($bbalRs);
        $bankct += $bbal['credit'];
        $bankdt += $bbal['debit'];
    }
    # get cash on hand
    db_conn("exten");
    $sql = "SELECT pca FROM departments  WHERE div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve departments from database.", SELF);
    while ($dept = pg_fetch_array($deptRslt)) {
        core_connect();
        $deptbalRs = db_exec("SELECT sum(credit) as credit, sum(debit) as debit FROM trial_bal WHERE accid = '{$dept['pca']}'");
        $deptbal = pg_fetch_array($deptbalRs);
        $bankct += $deptbal['credit'];
        $bankdt += $deptbal['debit'];
    }
    $ret['debit'] = sprint($bankdt);
    $ret['credit'] = sprint($bankct);
    return $ret;
}
Exemplo n.º 5
0
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return enter($_POST);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 20, "Invalid Bank ID.");
    foreach ($amount as $key => $value) {
        # check all vars
        $v->isOk($to[$key], "string", 1, 255, "Invalid receipient/depositor.");
        $v->isOk($trantype[$key], "string", 1, 20, "Invalid transaction type.");
        $v->isOk($descript[$key], "string", 0, 255, "Invalid description.");
        $v->isOk($ref[$key], "string", 0, 255, "Invalid reference <b>[{$key}]</b>.");
        $v->isOk($cheqnum[$key], "num", 0, 20, "Invalid cheque number <b>[{$key}]</b>.");
        $v->isOk($amount[$key], "float", 1, 8, "Invalid amount <b>[{$key}]</b>.");
        $v->isOk($accinv[$key], "num", 1, 20, "Invalid account involved <b>[{$key}]</b>.");
        $v->isOk($date[$key], "date", 1, 15, "Invalid date <b>[{$key}]</b>.");
        if (strtotime($date[$key]) >= strtotime($blocked_date_from) and strtotime($date[$key]) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
            return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Processes
    db_connect();
    # Begin Transaction
    pglib_transaction("BEGIN");
    # Some info
    $bankacc = getbankaccid($bankid);
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    foreach ($amount as $key => $amt) {
        $totamt = $amount[$key];
        if ($chrgvat[$key] == "exc") {
            $totamt += $vat[$key];
        } elseif ($chrgvat[$key] == "inc") {
            $amount[$key] -= $vat[$key];
        } else {
            $vat[$key] = "No VAT";
        }
        if ($cheqnum[$key] == '') {
            $cheqnum[$key] = 0;
        }
        if (!isset($batch)) {
            $refnum = getrefnum();
            if (strtolower($trantype[$key]) == 'deposit') {
                $vatacc = gethook("accnum", "salesacc", "name", "VAT", "1");
                writetrans($bankacc, $accinv[$key], $date[$key], $refnum, $amount[$key], $descript[$key]);
                if ($vat[$key] != 0) {
                    # DT(Bank), CT(VAT)
                    $vat[$key] += 0;
                    writetrans($bankacc, $vatacc, $date[$key], $refnum, $vat[$key], $descript[$key] . " VAT");
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode[$key]}'";
                    $Rt = db_exec($Sl) or errDie("Unable to get data.");
                    $vd = pg_fetch_array($Rt);
                    vatr($vatcode[$key], $date[$key], "OUTPUT", $vd['code'], $refnum, $descript[$key] . " VAT", $totamt, $vat[$key]);
                }
            } else {
                $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                writetrans($accinv[$key], $bankacc, $date[$key], $refnum, $amount[$key], $descript[$key]);
                if ($vat[$key] != 0) {
                    # DT(Bank), CT(VAT)
                    $vat[$key] += 0;
                    writetrans($vatacc, $bankacc, $date[$key], $refnum, $vat[$key], $descript[$key] . " VAT");
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode[$key]}'";
                    $Rt = db_exec($Sl) or errDie("Unable to get data.");
                    $vd = pg_fetch_array($Rt);
                    vatr($vatcode[$key], $date[$key], "INPUT", $vd['code'], $refnum, $descript[$key] . " VAT", -$totamt, -$vat[$key]);
                }
            }
            $vat[$key] += 0;
            db_connect();
            $sql = "\n\t\t\t\tINSERT INTO cashbook (\n\t\t\t\t\tbankid, trantype, date, name, descript, cheqnum, \n\t\t\t\t\tamount, banked, accinv, div,chrgvat,vat,reference\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$bankid}', lower('{$trantype[$key]}'), '{$date[$key]}', '{$to[$key]}', '{$descript[$key]}', '{$cheqnum[$key]}', \n\t\t\t\t\t'{$totamt}', 'no', '{$accinv[$key]}', '" . USER_DIV . "','{$chrgvat[$key]}', '{$vat[$key]}','{$ref[$key]}'\n\t\t\t\t)";
            $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        } else {
            db_connect();
            $vat[$key] += 0;
            $sql = "\n\t\t\t\tINSERT INTO batch_cashbook (\n\t\t\t\t\tbankid, trantype, date, name, descript, cheqnum, \n\t\t\t\t\tamount, banked, accinv, div, chrgvat, vat, vatcode, \n\t\t\t\t\treference\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$bankid}', lower('{$trantype[$key]}'), '{$date[$key]}', '{$to[$key]}', '{$descript[$key]}', '{$cheqnum[$key]}', \n\t\t\t\t\t'{$totamt}', 'no', '{$accinv[$key]}', '" . USER_DIV . "','{$chrgvat[$key]}','{$vat[$key]}','{$vatcode[$key]}', \n\t\t\t\t\t'{$ref[$key]}'\n\t\t\t\t)";
            $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        }
    }
    # Get bank details
    $bankAccRslt = get("cubit", "*", "bankacct", "bankid", $bankid);
    $bankacc = pg_fetch_array($bankAccRslt);
    pglib_transaction("COMMIT");
    if (!isset($batch)) {
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Statement Recorded</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>New Statement Details for account, <b>{$bankacc['accname']} ({$bankacc['accnum']})</b><br>held at <b>{$bankacc['bankname']}</b>, was successfully added to Cubit.</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    } else {
        $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Batch entries recorded</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>New batch items for account, <b>{$bankacc['accname']} ({$bankacc['accnum']})</b><br>held at <b>{$bankacc['bankname']}</b>, was successfully added to Cubit.</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    # Main table (layout with menu)
    $OUTPUT = "\n\t\t<center>\n\t\t<table width='90%'>\n\t\t\t<tr valign='top'>\n\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t<td align='center'>" . mkQuickLinks(ql("bank-pay-add.php", "Add Bank Payment"), ql("bank-recpt-add.php", "Add Bank Receipt"), ql("cashbook-view.php", "View Cash Book"), ql("batch-cashbook-view.php", "View Batch Cashbook")) . "\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    # Processes
    db_connect();
    # Get vars
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return add($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 10, "Invalid Date Entry.");
    $v->isOk($name, "string", 1, 255, "Invalid Person/Business paid to/received from.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amount, "float", 1, 10, "Invalid amount.");
    foreach ($accinv as $key => $vaccid) {
        $v->isOk($vaccid, "num", 1, 20, "Invalid Account (account involved).");
        $v->isOk($accamt[$key], "float", 1, 10, "Invalid amount.");
        $v->isOk($chrgvat[$key], "string", 1, 4, "Invalid VAT option.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    /* -- Start Hooks -- */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    # Get hook account number
    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.";
    }
    $banklnk = pg_fetch_array($rslt);
    /* -- End Hooks -- */
    # Refnum
    $refnum = getrefnum();
    $amounts = "";
    $accids = "";
    $vats = "";
    $chrgvats = "";
    $vatcodes = "";
    $gamt = 0;
    pglib_transaction("BEGIN");
    foreach ($accinv as $key => $vaccid) {
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode[$key]}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $vatp = $vd['vat_amount'];
        # Start Rattling vat
        $totamt = $accamt[$key];
        $vat = $getvat[$key];
        if ($chrgvat[$key] == "exc") {
            //	$vat = sprint(($vatp/100) * $accamt[$key]);
            $totamt += $vat;
        } elseif ($chrgvat[$key] == "inc") {
            //	$vat = sprint(($accamt[$key]/(100 + $vatp)) * $vatp);
            $accamt[$key] -= $vat;
        } else {
            //	$vat = 0;
        }
        $totamt = sprint($totamt);
        $amounts .= "|{$totamt}";
        $vatcodes .= "|{$vatcode[$key]}";
        $accids .= "|{$vaccid}";
        $vats .= "|{$vat}";
        $chrgvats .= "|{$chrgvat[$key]}";
        $gamt = sprint($gamt + $totamt);
    }
    # Date format
    $date = explode("-", $date);
    $date = $date[2] . "-" . $date[1] . "-" . $date[0];
    $cheqnum = 0 + $cheqnum;
    db_connect();
    $sql = "UPDATE batch_cashbook SET bankid = '{$bankid}', trantype = 'withdrawal', date = '{$date}', name = '{$name}',";
    $sql .= "descript = '{$descript}', cheqnum = '{$cheqnum}', amount = '{$gamt}', banked = 'no', accids = '{$accids}',";
    $sql .= "amounts = '{$amounts}', chrgvats = '{$chrgvats}', vats = '{$vats}', div = '" . USER_DIV . "',";
    $sql .= "vatcodes = '{$vatcodes}', reference = '{$reference}' WHERE cashid = '{$id}'";
    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    pglib_transaction("COMMIT");
    # Status report
    $write = "\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Bank Payment</th>\n\t\t</tr>\n\t\t<tr class='datacell'>\n\t\t\t<td>Bank Payment added to cash book.</td>\n\t\t</tr>\n\t</table>\n\t<p>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='cashbook-view.php'>View Cash Book</a></td>\n\t\t</tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function write()
{
    extract($_REQUEST);
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    $sndate = "{$ninv_year}-{$ninv_month}-{$ninv_day}";
    if (!checkdate($ninv_month, $ninv_day, $ninv_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    pglib_transaction("BEGIN");
    // Get invoice info
    $sql = "SELECT * FROM cubit.nons_invoices WHERE invid='{$invid}' AND div='" . USER_DIV . "'";
    $inv_rslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($inv_rslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($inv_rslt);
    $TOTAL = $inv["subtot"] + $inv["vat"];
    $notenum = pglib_lastid("cubit.nons_inv_notes", "noteid");
    $notenum++;
    // Add to the non stock credit notes
    $sql = "\r\n\t\tINSERT INTO cubit.nons_inv_notes (\r\n\t\t\tinvid, invnum, cusname, cusaddr, cusvatno, chrgvat, \r\n\t\t\tdate, subtot, vat, total, username, prd, notenum, ctyp, \r\n\t\t\tremarks, div\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['chrgvat']}', \r\n\t\t\t'{$sndate}', '{$inv['subtot']}', '{$inv['vat']}', '{$TOTAL}', '" . USER_NAME . "', '" . PRD_DB . "', '{$notenum}', '{$inv['ctyp']}', \r\n\t\t\t'{$inv['remarks']}', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to save credit note.");
    $noteid = pglib_lastid("cubit.nons_inv_notes", "noteid");
    $sql = "SELECT count(id) FROM cubit.nons_inv_items WHERE invid='{$invid}'";
    $count_rslt = db_exec($sql) or errDie("Unable to retrieve amount of items.");
    $item_count = pg_fetch_result($count_rslt, 0);
    $i = 0;
    $page = 0;
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM cubit.nons_inv_items WHERE invid='{$invid}' AND id='{$id}'";
        $item_rslt = db_exec($sql) or errDie("Unable to retrieve item.");
        $item_data = pg_fetch_array($item_rslt);
        if ($item_data['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        // Time for a new page ??
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $products[$page][] = "\r\n\t\t\t<tr valign='top'>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>\r\n\t\t\t\t\t{$ex} {$item_data['description']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000'>\r\n\t\t\t\t\t{$item_data['qty']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000' align='right' nowrap>\r\n\t\t\t\t\t" . CUR . " {$item_data['unitcost']}&nbsp;\r\n\t\t\t\t</td>\r\n\t\t\t\t<td align='right' nowrap>" . CUR . " {$item_data['amt']}&nbsp;</td>\r\n\t\t\t</tr>";
        $i++;
        // Create credit note item
        $sql = "\r\n\t\t\tINSERT INTO cubit.nons_note_items (\r\n\t\t\t\tnoteid, qty, description, amt, unitcost, \r\n\t\t\t\tvatcode\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$noteid}', '{$qtys[$key]}', '{$item_data['description']}', '{$amts[$key]}', '{$item_data['unitcost']}', \r\n\t\t\t\t'{$item_data['vatex']}'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to create credit note item.");
        $sql = "SELECT grpid FROM cubit.assets WHERE id='{$item_data['asset_id']}'";
        $group_rslt = db_exec($sql) or errDie("Unable to retrieve group.");
        $group_id = pg_fetch_result($group_rslt, 0);
        $discount = $inv["discount"] / $item_count;
        $amt = $item_data["amt"];
        // Update royalty report and detail report
        $sql = "\r\n\t\t\tINSERT INTO hire.revenue (\r\n\t\t\t\tgroup_id, asset_id, total, discount, credit\r\n\t\t\t) VALUES (\r\n\t\t\t\t'{$group_id}', '{$item_data['asset_id']}', '-{$amt}', '-{$discount}', '1'\r\n\t\t\t)";
        db_exec($sql) or errDie("Unable to update revenue.");
        $i++;
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t</tr>";
        }
    }
    // Retrieve customer debt account
    $sql = "\r\n\t\tSELECT debtacc FROM exten.departments \r\n\t\t\tLEFT JOIN cubit.customers ON departments.deptid=customers.deptid\r\n\t\tWHERE cusnum='{$inv['cusid']}'";
    $dept_rslt = db_exec($sql) or errDie("Unable to retrieve departments.");
    $debtacc = pg_fetch_result($dept_rslt, 0);
    $hireacc = $inv["accid"];
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "vat");
    $refnum = getrefnum();
    writetrans($hireacc, $debtacc, $sndate, $refnum, $inv["subtot"], "Non-Stock Invoice No. {$inv['invnum']} Credit Note No. {$noteid} Customer\r\n\t\t{$inv['cusname']}");
    if ($inv["vat"] != 0) {
        writetrans($vatacc, $debtacc, $sndate, $refnum, $inv["vat"], "Non-Stock Invoice No. {$inv['invnum']} Credit Note No. {$noteid} VAT.\r\n\t\tCustomer {$inv['cusname']}");
    }
    // Record on the statement
    $sql = "\r\n\t\tINSERT INTO cubit.stmnt (\r\n\t\t\tcusnum, invid, amount, date, type, \r\n\t\t\tdiv\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['cusid']}', '{$noteid}', '-{$TOTAL}', '{$sndate}', 'Non-Stock Credit Note, for invoice {$inv['invnum']}', \r\n\t\t\t'" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to insert to customer statement.");
    // Update the customer (Make the balance less)
    $sql = "UPDATE cubit.customers SET balance=(balance-'{$TOTAL}') WHERE cusnum='{$inv['cusid']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Update the customer (Make the balance less)
    $sql = "UPDATE cubit.open_stmnt SET balance=(balance-'{$TOTAL}') WHERE cusnum='{$inv['cusid']}'";
    db_exec($sql) or errDie("Unable to update customer balance.");
    // Create ledger record
    custledger($inv["cusid"], $hireacc, $sndate, $noteid, "Non-Stock Credit Note {$noteid}", $TOTAL, "c");
    custCT($inv["total"], $inv["cusid"], $inv["odate"]);
    // Update non-stock invoice
    $sql = "UPDATE cubit.nons_invoices SET balance=(balance-'{$TOTAL}') WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to update non-stock invoice.");
    $sql = "\r\n\t\tINSERT INTO cubit.salesrec (\r\n\t\t\tedate, invid, invnum, debtacc, vat, total, typ, div\r\n\t\t) VALUES (\r\n\t\t\t'{$sndate}', '{$noteid}', '{$notenum}', '0', '{$inv['vat']}', '{$TOTAL}', 'nnon', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to record in sales.");
    $sql = "\r\n\t\tINSERT INTO cubit.sj (\r\n\t\t\tcid, name, des, date, \r\n\t\t\texl, vat, inc, div\r\n\t\t) VALUES (\r\n\t\t\t'{$inv['cusid']}', '{$inv['cusname']}', 'Credit Note: {$noteid} Invoice {$inv['invnum']}', '{$sndate}', \r\n\t\t\t'-" . ($TOTAL - $inv["vat"]) . "', '{$inv['vat']}', '" . -sprint($TOTAL) . "', '" . USER_DIV . "'\r\n\t\t)";
    db_exec($sql) or errDie("Unable to record in sj.");
    $sql = "UPDATE cubit.nons_invoices SET accepted='note' WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to update invoice.");
    com_invoice($inv["salespn"], -($TOTAL - $inv["vat"]), 0, $inv["invnum"], $sndate);
    $cc = "\r\n\t\t<script>\r\n\t\t\tCostCenter('ct', 'Credit Note', '{$sndate}',\r\n\t\t\t'Non Stock Credit Note No.{$noteid}', '" . ($TOTAL - $inv["vat"]) . "', '');\r\n\t   </script>";
    // Reverse the amounts on the coastal reports -----------------------------
    $sql = "UPDATE hire.assets_hired SET value=0 WHERE invid='{$inv['hire_invid']}'";
    db_exec($sql) or errDie("Unable to update asset hired records.");
    // Vat
    $sql = "SELECT id FROM cubit.vatcodes WHERE code='01'";
    $vd_rslt = db_exec($sql) or errDie("Unable to retrieve vatcodes.");
    $vd_id = pg_fetch_result($vd_rslt, 0);
    vatr($vd_id, $sndate, "OUTPUT", "01", $refnum, "Non-Stock Sales, invoice No.{$inv['invnum']}", $TOTAL, $inv["vat"]);
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank.");
    $bank_data = pg_fetch_array($bank_rslt);
    // Retrieve customer information
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer.");
    $cust_data = pg_fetch_array($cust_rslt);
    if ($inv['cusid'] == "0") {
        $cust_data['surname'] = $inv['cusname'];
        $cust_data['addr1'] = $inv['cusaddr'];
        $cust_data['paddr1'] = $inv['cusaddr'];
    }
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $details .= "\r\n\t\t\t<center>\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td align='left' rowspan='2'><img src='../compinfo/getimg.php' width='230' height='47'></td>\r\n\t\t\t\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t\t\t\t<td align='right'><font size='5'><b>Tax Credit Note</b></font></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t\t<td valign='top'>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Credit Note No:</b> {$noteid}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$inv['invnum']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td align='center'><font size='4'><b>Credit Note To:</b></font></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cust_data['surname']}</b></td>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\r\n\t\t\t\t\t\t\t\t<td>&nbsp</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000' align='right'><b>Unit Price</b></td>\r\n\t\t\t\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t{$products_out}\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td>{$remarks}</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\r\n\t\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>\r\n\t\t\t\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t\t\t\t<td><b>Trade Discount:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['discount']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['subtot']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " {$inv['vat']}</b></td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t\t\t\t<td nowrap><b>" . CUR . " " . sprint($TOTAL) . "</b></td>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>";
    }
    pglib_transaction("COMMIT");
    $OUTPUT = $details;
    require "../tmpl-print.php";
}
function details($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    # format date
    $inv['odate'] = explode("-", $inv['odate']);
    $inv['odate'] = $inv['odate'][2] . "-" . $inv['odate'][1] . "-" . $inv['odate'][0];
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # Put in product
    while ($stk = pg_fetch_array($stkdRslt)) {
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatex']}'";
        $Ri = db_exec($Sl);
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $stk['vatex'] = "y";
        }
        if ($stk['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        $products .= "\r\n\t\t\t<tr valign='top'>\r\n\t\t\t\t<td style='border-right: 2px solid #000' nowrap>{$ex} {$stk['description']}</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000' align='right'>{$stk['qty']}</td>\r\n\t\t\t\t<td style='border-right: 2px solid #000' align='right'>{$stk['unitcost']}</td>\r\n\t\t\t\t<td align='right'>" . CUR . " {$stk['amt']}</td>\r\n\t\t\t</tr>";
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*refnum*/
    /* --- Updates ---- */
    db_connect();
    # Get selected stock in this invoice
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    /* -- Format the remarks boxlet -- */
    //	$inv["remarks"] = "<table border='1'><tr><td>Remarks:<br>$inv[remarks]</td></tr></table>";
    if ($inv['chrgvat'] == "yes") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "no") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;";
    /* -- Final Layout -- */
    $details = "\r\n\t\t<center>\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='left'><img src='compinfo/getimg.php' width='230' height='47'>{$barcode}</td>\r\n\t\t\t\t\t<td align='left'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t<td align='right'><font size='5'><b>Quote</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . COMP_ADDRESS . "&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> " . COMP_REGNO . "</b>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> " . COMP_VATNO . "&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> " . COMP_TEL . "&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> " . COMP_FAX . "&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td><b>Date</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$inv['odate']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Quote No:</b> {$inv['invid']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$sp}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='center'><font size='4'><b>Quote To:</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$inv['cusname']}</b></td>\r\n\t\t\t\t\t<td width='33%'><b>Address</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000' valign='bottom'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t<td>" . nl2br($inv["cusaddr"]) . "</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT:</b> {$inv['chrgvat']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;'><b>Description</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;' align='right'><b>Qty</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000;' align='right'><b>Unit Price</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000' align='right'><b>Amount</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$products}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$inv['remarks']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000' width='60%'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t<td align='right' nowrap><b>" . CUR . " {$inv['subtot']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>VAT @ " . TAX_VAT . "%:</b></td>\r\n\t\t\t\t\t<td align='right' nowrap><b>" . CUR . " {$inv['vat']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t<td align='right' nowrap><b>" . CUR . " {$inv['total']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td></td>\r\n\t\t\t\t\t<td nowrap></td>\r\n\t\t\t</table>\r\n\t\t</table>";
    $OUTPUT = $details;
    require "tmpl-print.php";
}
function update($_POST)
{
    # Get Vars ( banked[] )
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # Check if anything is selected
    if (!isset($banked)) {
        $err = "<li class=err> Please Select at least one entry to update.";
        return cashbook($_POST, $err);
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    $refnum = getrefnum();
    /*refnum*/
    # Record all trans
    $tot = 0;
    $totr = 0;
    $totp = 0;
    $recpts = "";
    $paymnts = "";
    foreach ($banked as $key => $cashid) {
        // Connect to database
        db_Connect();
        $sql = "SELECT * FROM cashbook WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $cashRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve details from database.", SELF);
        $cash = pg_fetch_array($cashRslt);
        # Set record as banked
        db_connect();
        $sql = "UPDATE cashbook SET banked = 'yes' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to set bank deposit as banked in Cubit.", SELF);
    }
    // Connect to database
    db_Connect();
    $sql = "SELECT * FROM cashbook WHERE bankid = '{$bankid}' AND banked = 'no' AND div = '" . USER_DIV . "' ORDER BY date DESC";
    $cashRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank transactions from database.", SELF);
    $tot = 0;
    $totr = 0;
    $totp = 0;
    $recpts = "";
    $paymnts = "";
    while ($cash = pg_fetch_array($cashRslt)) {
        if ($cash['trantype'] == "deposit") {
            $recpts .= "<tr><td>{$cash['date']}</td><td>{$cash['descript']}</td><td align=right>" . CUR . " {$cash['amount']}</td></tr>";
            $totr += $cash['amount'];
        } else {
            $paymnts .= "<tr><td>{$cash['date']}</td><td>{$cash['descript']}</td><td align=right>" . CUR . " {$cash['amount']}</td></tr>";
            $totp += $cash['amount'];
        }
        $tot += $cash['amount'];
    }
    $reconbal = sprint($cbal + ($totr - $totp));
    # Get account name for bank account
    db_connect();
    $sql = "SELECT accname, bankname FROM bankacct WHERE bankid= '{$bankid}' AND div = '" . USER_DIV . "'";
    $bankRslt = db_exec($sql);
    $bank = pg_fetch_array($bankRslt);
    # Get hook account number
    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.";
    }
    $banklnk = pg_fetch_array($rslt);
    # Get bank balance
    $sql = "SELECT (debit - credit) as bal FROM trial_bal WHERE period='" . PRD_DB . "' AND accid = '{$banklnk['accnum']}' AND div = '" . USER_DIV . "'";
    $brslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    $bal = pg_fetch_array($brslt);
    $diff = $reconbal - $bal['bal'];
    $derr = "";
    if ($diff != 0) {
        $derr = "<tr><td colspan=2><b class=err>Bank statement and computer balance not balancing by</b></td><td align=right>" . CUR . " {$diff}</td></tr>";
    }
    // Layout
    $update = "<table border=1>\n\t<tr><th colspan=3><h3>Bank Reconciliation Output</h3></th></tr>\n\t<tr><td></td></tr>\n\t<tr><td colspan=3>\n\t\t<table cellpadding='2' cellspacing='0' border=0 bordercolor='#000000' width=100%>\n\t\t\t<tr><td><b>Bank Account : </b>{$bank['accname']}</td><td></td><td align=right><b>Prepared By : </b>" . USER_NAME . "</td></tr>\n\t\t\t<tr><td><b>Closing Balance As per Bank Statement : </b>" . CUR . " {$cbal}</td><td></td></tr>\n\t\t</table>\n\t</td></tr>\n\t<tr><td><br><br></td></tr>\n\t<tr><td colspan=3><b>Plus Outstanding Receipts :</b></td></tr>\n\t<tr><th>Date</th><th>Reference</th><th>Amount</th></tr>\n\t{$recpts}\n\t<tr><td colspan=2><br></td><td align=right>____________</td></tr>\n\t<tr><td colspan=2 align=right><b>Sub Total</b></td><td align=right>" . CUR . " {$totr}</td></tr>\n\t<tr><td><br><br></td></tr>\n\t<tr><td colspan=3><b>Less Outstanding Payments :</b></td></tr>\n\t<tr><th>Date</th><th>Reference</th><th>Amount</th></tr>\n\t{$paymnts}\n\t<tr><td colspan=2><br></td><td align=right>____________</td></tr>\n\t<tr><td colspan=2 align=right><b>Sub Total</b></td><td align=right>" . CUR . " {$totp}</td></tr>\n\t<tr><td><br><td></tr>\n\t{$derr}\n\t<tr><td><br><td></tr>\n\t<tr><td colspan=2><br></td><td align=right>____________</td></tr>\n\t<tr><td colspan=2><b>Reconciled Bank Balance</b></td><td align=right>" . CUR . " {$reconbal}</td></tr>\n\t<tr><td colspan=2><b>Computer Bank Balance</b></td><td align=right>" . CUR . " {$bal['bal']}</td></tr>\n\t<tr><td colspan=2><br></td><td align=right>____________</td></tr>\n\t<tr><td colspan=2><b>Diff</b></td><td align=right>" . CUR . " {$diff}</td></tr>\n\t<tr><td colspan=2><br></td><td align=right>____________</td></tr>\n\t</table>";
    # Send the stream
    include "temp.xls.php";
    return Stream("BankRecon", $update);
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($supinv, "string", 0, 255, "Invalid supp inv.");
    # used to generate errors
    $error = "asa@";
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return details($_POST, $err);
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $td = $pur['pdate'];
    # check if purchase has been received
    if ($pur['invcd'] == "y") {
        $error = "<li class=err> Error : purchase number <b>{$pur['purnum']}</b> has already been invoiced.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($supRslt) < 1) {
        // code here
    } else {
        $sup = pg_fetch_array($supRslt);
    }
    # Get department info
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class=err> - Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $Ri = db_exec($sql);
    $refnum = getrefnum();
    while ($id = pg_fetch_array($Ri)) {
        db_connect();
        # get selamt from selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$id['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        if ($id['svat'] == 0) {
            $exvat = "y";
        } else {
            $exvat = "";
        }
        $vr = pvatcalc($id['amt'], $pur['vatinc'], $exvat);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Purchase {$pur['purnum']} Supplier : {$pur['supname']}.", $iamount, $ivat);
    }
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    # Record the payment on the statement
    db_connect();
    $sdate = date("Y-m-d");
    $DAte = date("Y-m-d");
    db_connect();
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$pur['total']}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$pur['supid']}','{$pur['pdate']}', '{$dept['credacc']}', '{$pur['total']}', 'Stock Received - Purchase {$pur['purnum']}', '{$refnum}','{$pur['purnum']}','" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # Debit Stock Control and Credit Creditors control
    writetrans($wh['conacc'], $dept['credacc'], $td, $refnum, $pur['total'] - $pur['vat'], "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Transfer vat
    writetrans($vatacc, $dept['credacc'], $td, $refnum, $pur['vat'], "Vat Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
    # Ledger Records
    suppledger($pur['supid'], $wh['conacc'], $td, $pur['purid'], "Purchase No. {$pur['purnum']} received.", $pur['total'], 'c');
    db_connect();
    /* End Transactions */
    /* Make transaction record  for age analysis */
    db_connect();
    # update the supplier age analysis (make balance less)
    if (ext_ex2("suppurch", "purid", $pur['purnum'], "supid", $pur['supid'])) {
        # Found? Make amount less
        $sql = "UPDATE suppurch SET balance = (balance + '{$pur['total']}') WHERE supid = '{$pur['supid']}' AND purid = '{$pur['purnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    } else {
        /* Make transaction record for age analysis */
        $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, div) VALUES('{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$pur['total']}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
    }
    /* Make transaction record  for age analysis */
    # commit updating
    //1 ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    /* Start moving if purchase */
    if ($pur['received'] == "y") {
        if (strlen($pur['appdate']) < 8) {
            $pur['appdate'] = date("Y-m-d");
        }
        # copy purchase
        db_conn(PRD_DB);
        $sql = "INSERT INTO purchases(purid, deptid, supid, supname, supaddr, supno, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, shipping, remarks, refno, received, done, div, purnum, supinv,ordernum,appname,appdate)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}','{$supinv}','{$pur['ordernum']}','{$pur['appname']}','{$pur['appdate']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
        /*-- Cost varience -- */
        $nsubtot = sprint($pur['total'] - $pur['vat']);
        if ($pur['rsubtot'] > $nsubtot) {
            $diff = sprint($pur['rsubtot'] - $nsubtot);
            # Debit Stock Control and Credit Creditors control
            writetrans($wh['conacc'], $cvacc, $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        } elseif ($nsubtot > $pur['rsubtot']) {
            $diff = sprint($nsubtot - $pur['rsubtot']);
            # Debit Stock Control and Credit Creditors control
            writetrans($cvacc, $wh['conacc'], $td, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        }
        /*-- End Cost varience -- */
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert purchase items
            db_conn(PRD_DB);
            $sql = "INSERT INTO pur_items(purid, whid, stkid, qty, rqty, unitcost, amt, svat, ddate, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        # begin updating
        db_connect();
        # Remove the purchase from running DB
        $sql = "DELETE FROM purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Record where purchase is
        $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('loc', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
        $movRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Remove those purchase items from running DB
        $sql = "DELETE FROM pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        /* End moving purchase received */
        # commit updating
    } else {
        # insert Order to DB
        $sql = "UPDATE purchases SET invcd = 'y',supinv='{$supinv}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Final Layout
    $write = "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>Purchase Invoiced</th></tr>\n\t\t<tr class='bg-even'><td>Purchase Invoice from Supplier <b>{$pur['supname']}</b> has been recorded.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class='bg-odd'><td><a href='purchase-view.php'>View purchases</a></td></tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function bwrite($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($prd, "num", 1, 20, "Invalid period Database number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            if ($qty > $qts[$keys]) {
                $v->isOk($qty, "num", 0, 0, "Error : Quantity for product number : <b>" . ($keys + 1) . "</b> is more that Qty Orderd");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get Order info
    db_conn($prd);
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # Get selected supplier info
    db_connect();
    if ($pur['ctyp'] == 's') {
        $supid = $pur['typeid'];
        $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql) or errDie("Unable to get supplier");
        if (pg_numrows($supRslt) < 1) {
            $error = "<li class='err'> Supplier not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $sup = pg_fetch_array($supRslt);
            $pur['supplier'] = $sup['supname'];
            $pur['supaddr'] = $sup['supaddr'];
            # Get department info
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$sup['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $supacc = $dept['credacc'];
        }
    } elseif ($pur['ctyp'] == 'c') {
        $deptid = $pur['typeid'];
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Department not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = $dept['pca'];
        }
    }
    # Insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    if (isset($qtys)) {
        # amount of stock in
        $totstkamt = array();
        $resub = 0;
        # Get subtotal
        foreach ($qtys as $keys => $value) {
            # Skip zeros
            if ($qtys[$keys] < 1) {
                continue;
            }
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        }
        $SUBTOTAL = array_sum($amt);
        $revat = 0;
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            $sql = "SELECT * FROM nons_pur_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # Calculate cost amount bought
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
            /* delivery charge */
            # Calculate percentage from subtotal
            $perc[$keys] = $amt[$keys] / $SUBTOTAL * 100;
            # Get percentage from shipping charges
            $shipc[$keys] = $perc[$keys] / 100 * $shipchrg;
            # add delivery charges
            $amt[$keys] += $shipc[$keys];
            /* end delivery charge */
            # the subtotal + delivery charges
            $resub += $amt[$keys];
            # calculate vat
            $svat[$keys] = svat($amt[$keys], $stkd['amt'], $stkd['svat']);
            # received vat
            $revat += $svat[$keys];
            # make amount vat free
            if ($pur['vatinc'] == "yes") {
                $amt[$keys] = $amt[$keys] - $svat[$keys];
            }
            # Update Order items
            $sql = "\n\t\t\t\t\tUPDATE nons_pur_items \n\t\t\t\t\tSET rqty = (rqty + '{$qtys[$keys]}'), accid = '{$stkacc[$keys]}' \n\t\t\t\t\tWHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            # keep records for transactions
            if (isset($totstkamt[$stkacc[$keys]])) {
                $totstkamt[$stkacc[$keys]] += $amt[$keys];
            } else {
                $totstkamt[$stkacc[$keys]] = $amt[$keys];
            }
            # check if there are any outstanding items
            $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            # if none the set to received
            if (pg_numrows($stkdRslt) < 1) {
                # update surch_int(received = 'y')
                $sql = "\n\t\t\t\t\t\tUPDATE nons_purchases \n\t\t\t\t\t\tSET received = 'y', supplier = '{$pur['supplier']}', supaddr = '{$pur['supaddr']}' \n\t\t\t\t\t\tWHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF);
            }
        }
    }
    # Update Order on the DB
    if ($pur['part'] == 'y') {
        # Update Order on the DB
        $sql = "\n\t\t\t\tUPDATE nons_purchases \n\t\t\t\tSET ctyp = '{$ctyp}', typeid = '{$typeid}', refno = '{$refno}', remarks = '{$remarks}' \n\t\t\t\tWHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    } else {
        # Update Order on the DB
        $sql = "\n\t\t\t\tUPDATE nons_purchases \n\t\t\t\tSET ctyp = '{$ctyp}', typeid = '{$typeid}', refno = '{$refno}', remarks = '{$remarks}' \n\t\t\t\tWHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    }
    /* Transactions */
    $refnum = getrefnum(date("d-m-Y"));
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    $detadd = "";
    if (isset($supid)) {
        $detadd = " from Supplier {$sup['supname']}";
    }
    $sdate = $pur['pdate'];
    $tpp = 0;
    $ccamt = 0;
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        # Debit Stock and Credit Suppliers control
        writetrans($stkacc, $supacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $wamt, "Cash Order");
    }
    # vat
    $vatamt = $revat;
    # Add vat if not included
    if ($pur['vatinc'] == 'no') {
        $retot = $resub + $vatamt;
    } elseif ($pur['vatinc'] == "novat") {
        $retot = $resub;
        $vatamt = 0;
    } else {
        $retot = $resub;
    }
    if (isset($supid)) {
        # Ledger Records
        $DAte = $pur['pdate'];
        suppledger($sup['supid'], $stkacc, $DAte, $pur['purid'], "Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'c');
    }
    if ($vatamt != 0) {
        # Debit bank and credit the account involved
        writetrans($vatacc, $supacc, date("d-m-Y"), $refnum, $vatamt, "Non-Stock Purchase VAT paid on Non-Stock Order No. {$pur['purnum']} {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $vatamt, "Cash Order VAT");
        # Record the payment on the statement
        db_connect();
        $sdate = $pur['pdate'];
    }
    if (isset($supid)) {
        $DAte = $pur['pdate'];
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$retot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "\n\t\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\t\tsupid, edate, cacc, amount, descript, ref, ex, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$sup['supid']}','{$DAte}', '{$dept['credacc']}', '{$retot}', 'Non Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t\t)";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        db_connect();
        # update the supplier age analysis (make balance less)
        /* Make transaction record for age analysis */
        $sql = "\n\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$sup['supid']}', '{$pur['purnum']}', '{$DAte}', '{$retot}', '" . USER_DIV . "'\n\t\t\t\t)";
        $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    }
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End Transactions */
    /* Start moving if Order received */
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        # copy Order
        db_conn($pur['prd']);
        $sql = "\n\t\t\t\tINSERT INTO nons_purchases (\n\t\t\t\t\tpurid, deptid, supplier, supaddr, terms, pdate, ddate, \n\t\t\t\t\tshipchrg, shipping, subtot, total, balance, vatinc, vat, \n\t\t\t\t\tremarks, refno, received, done, ctyp, typeid, div, purnum\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', \n\t\t\t\t\t'{$pur['shipchrg']}', '{$pur['shipping']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', \n\t\t\t\t\t'{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '{$pur['ctyp']}', '{$pur['typeid']}', '" . USER_DIV . "', '{$pur['purnum']}'\n\t\t\t\t)";
        $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Order to Cubit.", SELF);
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert Order items
            db_conn($pur['prd']);
            $sql = "\n\t\t\t\t\tINSERT INTO nons_pur_items (\n\t\t\t\t\t\tpurid, cod, des, qty, unitcost, amt, \n\t\t\t\t\t\tsvat, ddate, accid, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', \n\t\t\t\t\t\t'{$stktc['svat']}', '{$stktc['ddate']}', '{$stktc['accid']}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        db_connect();
        # Remove the Order from running DB
        $sql = "DELETE FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Remove those Order items from running DB
        $sql = "DELETE FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    }
    /* End moving Order received */
    $cc = "<script> CostCenter('ct', 'Non-Stock Purchase', '{$pur['pdate']}', 'Non Stock Purchase No.{$pur['purnum']}', '" . ($retot - $vatamt) . "', ''); </script>";
    // Final Layout
    $write = "\n\t\t{$cc}\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Non-Stock Order received</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Non-Stock Order receipt has been recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='nons-purchase-view.php'>View Orders</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 14, "Invalid Date.");
    $v->isOk($out, "float", 1, 40, "Invalid out amount.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 40, "Invalid amount.");
    $v->isOk($setamt, "float", 1, 40, "Invalid Settlement Amount.");
    $v->isOk($setvat, "string", 1, 10, "Invalid Settlement VAT Option.");
    $v->isOk($setvatcode, "string", 1, 40, "Invalid Settlement VAT code");
    $v->isOk($cusid, "num", 1, 40, "Invalid customer number.");
    $v->isOk($out1, "float", 0, 40, "Invalid paid amount(current).");
    $v->isOk($out2, "float", 0, 40, "Invalid paid amount(30).");
    $v->isOk($out3, "float", 0, 40, "Invalid paid amount(60).");
    $v->isOk($out4, "float", 0, 40, "Invalid paid amount(90).");
    $v->isOk($out5, "float", 0, 40, "Invalid paid amount(120).");
    $v->isOk($overpay, "float", 1, 20, "Invalid Overpay Amount.");
    if (isset($invids)) {
        foreach ($invids as $key => $value) {
            $v->isOk($invids[$key], "num", 1, 50, "Invalid Invoice No.");
            $v->isOk($paidamt[$key], "float", 1, 40, "Invalid amount to be paid.");
            $v->isOk($stock_setamt[$key], "float", 1, 40, "Invalid Settlement Discount Amount");
        }
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . confirm($_POST);
    }
    /* get bank account id of cash on hand account IF this entry is cash */
    if (($bank_acc = getbankaccid($bankid)) === false or $bankid == "0") {
        //old function didnt check if cash is selected ... if(($bank_acc = getbankaccid($bankid)) === false) {
        $sql = "SELECT accid FROM core.accounts WHERE accname='Cash on Hand'";
        $rslt = db_exec($sql);
        if (pg_num_rows($rslt) < 1) {
            if ($bankid == 0) {
                return "There is no 'Cash on Hand' account, there was one, but\n\t\t\t\t\t**s not there now, you must have deleted it, if you want\n\t\t\t\t\tto use cash functionality please create a 'Cash on Hand' account.";
            } else {
                return "Invalid bank acc.";
            }
        }
        $bank_acc = pg_fetch_result($rslt, 0);
    }
    $cus = qryCustomer($cusid, "cusnum, deptid, cusname, surname");
    $dept = qryDepartment($cus["deptid"], "debtacc");
    $refnum = getrefnum();
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # date format
    $sdate = explode("-", $date);
    $_SESSION["global_day"] = $sdate[2];
    $_SESSION["global_month"] = $sdate[1];
    $_SESSION["global_year"] = $sdate[0];
    //	$sdate = $sdate[2]."-".$sdate[1]."-".$sdate[0];
    $sdate = "{$date_year}-{$date_month}-{$date_day}";
    $cheqnum = 0 + $cheqnum;
    $pay = "";
    $accdate = $sdate;
    //	$accdate = "$date_year-$date_month-$date_day";
    /* Paid invoices */
    $invidsers = "";
    $rinvids = "";
    $amounts = "";
    $invprds = "";
    $rages = "";
    $setamts = "";
    #get settlement accid
    $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Debtors Settlement Discount'";
    $run_setacc = db_exec($get_setacc) or errDie("Unable to get settlement account information");
    $setaccid = pg_fetch_result($run_setacc, 0, 0);
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    $amt += $overpay;
    /* OPTION 3 : ALLOCATE TO EACH INVOICE (confirm) */
    if ($all == 2) {
        $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt}'::numeric(16,2)) WHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        if (isset($invids)) {
            foreach ($invids as $key => $value) {
                $ii = $invids[$key];
                # some logic ...
                # because the customer account should be 0 when paid fully, we need
                # to also deduct the settlement amount ...
                $paidamt[$key] = $paidamt[$key] + $stock_setamt[$key];
                # with the amount added to the paid amount, we tract it using a new
                # seperate setamt db column
                if (!isset($itype[$key]) && !isset($ptype[$key])) {
                    $sql = "SELECT prd,invnum,odate FROM cubit.invoices WHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.invoices\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2))\n\t\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);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt\n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2))\n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    # record the payment on the statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, date, type, div, allocation_date, docref, \n\t\t\t\t\t\t\tallocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "', \n\t\t\t\t\t\t\t'{$sdate}', 'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}', '{$reference}', \n\t\t\t\t\t\t\t'" . abs($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, \n\t\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', \n\t\t\t\t\t\t\t\t'{$sdate}', 'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    #deduct setamt for records ...
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$key] - $stock_setamt[$key], "c");
                    db_connect();
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    if ($inv['prd'] == "0") {
                        $inv['prd'] = PRD_DB;
                    }
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                } elseif (!isset($ptype[$key])) {
                    $sql = "\n\t\t\t\t\t\tSELECT prd,invnum,descrip,age,odate \n\t\t\t\t\t\tFROM cubit.nons_invoices \n\t\t\t\t\t\tWHERE invid ='{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce the invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.nons_invoices \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\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);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    if (!isset($inv['odate']) or strlen($inv['odate']) < 1) {
                        $inv['odate'] = $sdate;
                    }
                    // add payment to statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\tamount, \n\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t'" . ($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "', \n\t\t\t\t\t\t\t'{$sdate}', 'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', \n\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($paidamt[$key] - $stock_setamt[$key] - ($paidamt[$key] - $stock_setamt[$key]) * 2) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, \n\t\t\t\t\t\t\t\tdate, type, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', \n\t\t\t\t\t\t\t\t'{$sdate}', 'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$key], "c");
                    db_connect();
                    //recordCT($paidamt[$key], $cus['cusnum'],$inv['age'],$accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|0";
                    $rages .= "|{$inv['age']}";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                } else {
                    /* pos invoices */
                    $sqls = array();
                    for ($i = 1; $i <= 12; ++$i) {
                        $sqls[] = "\n\t\t\t\t\t\t\tSELECT '{$i}' AS prd,invid,invnum,odate \n\t\t\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\tWHERE invid='{$invids[$key]}' AND div='" . USER_DIV . "'";
                    }
                    $sql = implode(" UNION ", $sqls);
                    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                    if (pg_numrows($invRslt) < 1) {
                        return "<li class='err'>Invalid Invoice Number.</li>";
                    }
                    $inv = pg_fetch_array($invRslt);
                    // reduce the invoice balance
                    $sql = "\n\t\t\t\t\t\tUPDATE \"{$inv['prd']}\".pinvoices \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\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);
                    $sql = "\n\t\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\t\tSET balance = (balance - {$paidamt[$key]}::numeric(16,2)) \n\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    // add payment to statement
                    $sql = "\n\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\ttype, div, \n\t\t\t\t\t\t\tallocation_date, docref, allocation_balance\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($paidamt[$key] - $stock_setamt[$key]) * -1 . "', '{$sdate}', \n\t\t\t\t\t\t\t'Payment for POS Invoice No. {$inv['invnum']}', '" . USER_DIV . "', \n\t\t\t\t\t\t\t'{$inv['odate']}', '{$reference}', '" . abs(($paidamt[$key] - $stock_setamt[$key]) * -1) . "'\n\t\t\t\t\t\t)";
                    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    #record the settlement discount on the statement
                    if ($stock_setamt[$key] > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, \n\t\t\t\t\t\t\t\tamount, date, \n\t\t\t\t\t\t\t\ttype, \n\t\t\t\t\t\t\t\tdiv, allocation_date, docref, allocation_balance\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', \n\t\t\t\t\t\t\t\t'" . ($stock_setamt[$key] - $stock_setamt[$key] * 2) . "', '{$sdate}', \n\t\t\t\t\t\t\t\t'Settlement Discount for Invoice No.{$inv['invnum']} Ref. {$refnum}', \n\t\t\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}', '{$reference}', '" . abs($stock_setamt[$key] - $stock_setamt[$key] * 2) . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                    }
                    custledger($cus['cusnum'], $bank_acc, $sdate, $inv['invnum'], "Payment for POS Invoice No. {$inv['invnum']}", $paidamt[$key], "c");
                    //recordCT($paidamt[$key], $cus['cusnum'],"0",$accdate);
                    $rinvids .= "|{$invids[$key]}";
                    $amounts .= "|{$paidamt[$key]}";
                    $invprds .= "|{$inv['prd']}";
                    $rages .= "|0";
                    $invidsers .= " - {$inv['invnum']}";
                    $setamts .= "|{$stock_setamt[$key]}";
                }
            }
        }
        if (open()) {
            db_conn('cubit');
            $Sl = "SELECT * FROM cubit.open_stmnt WHERE balance>0 AND cusnum='{$cusid}' ORDER BY date";
            $Ri = db_exec($Sl) or errDie("Unable to get open items.");
            //$open_out=$out;
            $ox = "";
            $i = 0;
            while ($od = pg_fetch_array($Ri)) {
                $oid = $od['id'];
                if (!isset($open_amount[$oid]) || $open_amount[$oid] == 0) {
                    continue;
                }
                $ox .= "\n\t\t\t\t\t<input type='hidden' size='20' name='open[{$oid}]' value='{$oid}'>\n\t\t\t\t\t<input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>\n\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t<td>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t</tr>";
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$open_amount[$oid]} ::numeric(16,2)) \n\t\t\t\t\tWHERE id = '{$oid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                // record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date, docref, allocation_balance\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cus['cusnum']}', '0', '" . -$open_amount[$oid] . "', '{$sdate}', \n\t\t\t\t\t\t'Payment received', '" . USER_DIV . "', '{$accdate}', '{$reference}', '" . abs($open_amount[$oid]) . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $bank_acc, $sdate, 0, "Payment received", $open_amount[$oid], "c");
                recordCT($open_amount[$oid], $cus['cusnum'], 0, $accdate);
            }
        }
        // record the payment record
        $cols = grp(m("bankid", $bankid), m("trantype", "deposit"), m("date", $sdate), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheqnum), m("amount", $amt), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference), m("div", USER_DIV));
        $dbobj = new dbUpdate("cashbook", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        $cashbook_id = pglib_lastid("cashbook", "cashid");
        writetrans($bank_acc, $dept['debtacc'], $accdate, $refnum, $amt, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
    }
    /* start moving invoices */
    // move invoices that are fully paid
    $sql = "SELECT * FROM cubit.invoices WHERE balance='0' AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    while ($x = pg_fetch_array($invbRslt)) {
        if (($prd = $x['prd']) == "0") {
            $prd = PRD_DB;
        }
        // move invoice
        $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
        $dbobj = new dbUpdate("invoices", $prd, $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        // record movement
        $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
        $dbobj->setTable("movinv", "cubit");
        $dbobj->setOpt($cols);
        $dbobj->run();
        $dbobj->free();
        // move invoice items
        $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
        $inv_items->run();
        while ($xi = $inv_items->fetch_array()) {
            $xi['vatcode'] += 0;
            $xi['account'] += 0;
            $xi['del'] += 0;
            $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
            $dbobj->setTable("inv_items", $prd);
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
        }
        /* remove invoice from cubit schema */
        $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
        $dbobj->run();
        $dbobj->setTable("inv_items", "cubit");
        $dbobj->run();
    }
    #do journal for the settlement discount here ... now ...
    if ($setamt > 0) {
        db_conn('core');
        #calculate the settlement vat ... and amt
        if (isset($setvat) and $setvat == 'inc') {
            db_connect();
            $get_vcode = "SELECT * FROM vatcodes WHERE id = '{$setvatcode}' LIMIT 1";
            $run_vcode = db_exec($get_vcode) or errDie("Unable to get vatcode informtion.");
            if (pg_numrows($run_vcode) < 1) {
                return "<li class='err'>Settlement Discount VAT Code Not Set.</li>";
            }
            $vd = pg_fetch_array($run_vcode);
            #vat inc ... recalculate the amts
            $setvatamt = sprint($setamt * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
            $setamt = sprint($setamt - $setvatamt);
            #process the vat amt ...
            writetrans($vatacc, $dept['debtacc'], $accdate, $refnum, $setvatamt, "VAT Received on Settlement Discount (Ref.{$refnum}) for Customer : {$cus['cusname']} {$cus['surname']}");
            vatr($vd['id'], $accdate, "OUTPUT", $vd['code'], $refnum, "VAT for Settlement Discount (Ref.{$refnum}) for Customer : {$cus['cusname']} {$cus['surname']}", ($setamt + $setvatamt) * -1, $setvatamt * -1);
        } else {
            #no vat for set amt ... do nothing
            $setvatamt = 0;
        }
        custledger($cus['cusnum'], $setaccid, $accdate, $refnum, "Settlement Discount (Ref.{$refnum})", $setamt + $setvatamt, "c");
        writetrans($setaccid, $dept['debtacc'], $accdate, $refnum, $setamt, "Settlement Discount (Ref.{$refnum}) For {$cus['cusname']} {$cus['surname']}");
        db_connect();
        #record this paid settlement discount for reporting ...
        $settl_sql = "\n\t\t\tINSERT INTO settlement_cus (\n\t\t\t\tcustomer, amt, setamt, setvatamt, setvat, setvatcode, tdate, sdate, refnum\n\t\t\t) VALUES (\n\t\t\t\t'{$cus['cusnum']}', '{$amt}', '{$setamt}', '{$setvatamt}', '{$setvat}', '{$setvatcode}', '{$accdate}', 'now', '{$refnum}'\n\t\t\t)";
        $run_settl = db_exec($settl_sql) or errDie("Unable to get debtor settlement information.");
    }
    //	$overpay = sprint ($amt - array_sum($paidamt));
    if (!isset($overpay) or $overpay < 0) {
        $overpay = 0.0;
    }
    if ($overpay > 0) {
        recordCT($overpay, $cus['cusnum'], 0, $accdate);
        $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$overpay), m("date", $sdate), m("type", "Payment Received (Receipt " . pglib_lastid("cashbook", "cashid") . ")"), m("div", USER_DIV), m("allocation_date", $accdate), m("docref", $reference));
        $dbobj = new dbUpdate("stmnt", "cubit", $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        custledger($cus['cusnum'], $bank_acc, $sdate, "PAYMENT", "Payment received.", $overpay, "c");
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // status report
    //	$write = "
    //				<table ".TMPL_tblDflts." width='100%'>
    //					<tr>
    //						<th>Bank Receipt</th>
    //					</tr>
    //					<tr class='".bg_class()."'>
    //						<td>Bank Receipt added to cash book.</td>
    //					</tr>
    //				</table>
    //			";
    //
    //	$OUTPUT = "<center>
    //        <table width='90%'>
    //        <tr valign='top'>
    //        	<td width='50%'>$write</td>
    //	        <td align='center'>"
    //				.mkQuickLinks(
    //					ql("bank-pay-add.php", "Add Bank Payment"),
    //					ql("bank-recpt-add.php", "Add Bank Receipt"),
    //					ql("bank-recpt-inv.php", "Add Customer Payment"),
    //					ql("cashbook-view.php", "View Cash Book")
    //				)."
    //			</td>
    //		</tr>
    //		</table>";
    //	return $OUTPUT;
    if (isset($print_recpt) and $print_recpt == "yes") {
        $showreceipt = "printer ('bank/bank-recpt-inv-print.php?recid={$cashbook_id}');";
    } else {
        $showreceipt = "";
    }
    return "\n\t\t<script>\n\t\t\tmove ('../customers-view.php?offset=0&fval=&filter=surname&nozerobal=yes');\n\t\t\t{$showreceipt}\n\t\t</script>";
}
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($from_day, "num", 1, 2, "Invalid Day for the 'From' date.");
    $v->isOk($from_month, "num", 1, 2, "Invalid month for the 'From' date..");
    $v->isOk($from_year, "num", 1, 4, "Invalid year for the 'From' date..");
    $v->isOk($to_day, "num", 1, 2, "Invalid Day for the 'To' date.");
    $v->isOk($to_month, "num", 1, 2, "Invalid month for the 'To' date..");
    $v->isOk($to_year, "num", 1, 4, "Invalid year for the 'To' date..");
    # lets mix the date
    $from = $from_day . "-" . $from_month . "-" . $from_year;
    $to = $to_day . "-" . $to_month . "-" . $to_year;
    # 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;
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # Get bank details
    $bankRslt = get("cubit", "accname,bankname,fcid", "bankacct", "bankid", $bankid);
    $bank = pg_fetch_array($bankRslt);
    $Sl = "SELECT * FROM currency WHERE fcid='{$bank['fcid']}'";
    $Ry = db_exec($Sl) or errDie("Unable to get currency");
    if (pg_numrows($Ry) > 0) {
        $curdata = pg_fetch_array($Ry);
        $fc = $curdata['symbol'];
    }
    $s1 = "";
    $s2 = "";
    $s3 = "";
    $s4 = "";
    $s5 = "";
    $order = "order by date desc, cheqnum asc";
    if (isset($order)) {
        if ($order == "order by date desc, cheqnum asc") {
            $s2 = "selected";
        } elseif ($order == "order by date desc, cheqnum desc") {
            $s3 = "selected";
        } elseif ($order == "order by cheqnum asc") {
            $s4 = "selected";
        } elseif ($order == "order by cheqnum desc") {
            $s5 = "selected";
        } else {
            $s1 = "selected";
        }
    } else {
        $s1 = "selected";
    }
    // Set up table to display in
    # Receipts
    $OUTPUT = "\n\t<center>\n\t<h3>Batch Cash Book Entries<br><br>Account : {$bank['accname']} - {$bank['bankname']}<br>Period : {$from} to {$to}</h3>\n\t<table " . TMPL_tblDflts . ">\n\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t<input type='hidden' name='key' value='viewcash'>\n\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t<input type='hidden' name='from_day' value='{$from_day}'>\n\t\t<input type='hidden' name='from_month' value='{$from_month}'>\n\t\t<input type='hidden' name='from_year' value='{$from_year}'>\n\t\t<input type='hidden' name='to_day' value='{$to_day}'>\n\t\t<input type='hidden' name='to_month' value='{$to_month}'>\n\t\t<input type='hidden' name='to_year' value='{$to_year}'>\n\t</table>\n\t<p>\n\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t<tr>\n\t\t\t<td colspan='7'><h4>Receipts</h4></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th> Date</th>\n\t\t\t<th>Bank Account Name</th>\n\t\t\t<th>Cheque Number</th>\n\t\t\t<th>Received From : </th>\n\t\t\t<th>Description</th>\n\t\t\t<th>Ledger Account</th>\n\t\t\t<th>Amount</th>\n\t\t</tr>";
    $rtotal = 0;
    // Received total amount
    // Connect to database
    db_Connect();
    # date format
    $from = explode("-", $from);
    $from = $from[2] . "-" . $from[1] . "-" . $from[0];
    $to = explode("-", $to);
    $to = $to[2] . "-" . $to[1] . "-" . $to[0];
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    # Get hook account number
    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.";
    }
    $banklnk = pg_fetch_array($rslt);
    db_Connect();
    $sql = "SELECT * FROM batch_cashbook WHERE  date >= '{$from}' AND date <= '{$to}' AND trantype='deposit' AND bankid='{$bankid}' AND div = '" . USER_DIV . "' {$order}";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank deposits details from database.", SELF);
    $numrows = pg_numrows($accntRslt);
    if ($numrows < 1) {
        //$OUTPUT .= "<tr><td colspan='7' align='center'><li class='err'>There are no batch Payments/cheques received for the selected period.</td></tr>";
    } else {
        for ($i = 0; $i < $numrows; $i++) {
            $accnt = pg_fetch_array($accntRslt, $i);
            if (!isset($pro[$accnt['cashid']])) {
                continue;
            }
            //	if($accnt['bt']=="receipt") {
            $refnum = getrefnum();
            if (strlen($accnt['accids']) > 0) {
                $accids = explode("|", $accnt['accids']);
                $vatcodes = explode("|", $accnt['vatcodes']);
                $amounts = explode("|", $accnt['amounts']);
                $vats = explode("|", $accnt['vats']);
                $chrgvats = explode("|", $accnt['chrgvats']);
                $refnum = getrefnum();
                $descript = $accnt['descript'];
                //$date = date("Y-m-d");
                $date = $accnt['date'];
                foreach ($amounts as $key => $amount) {
                    # SQL Array Rule: Thou shalt skip Zero Reference
                    if ($key < 1) {
                        continue;
                    }
                    $accid = $accids[$key];
                    $vat = $vats[$key];
                    $chrgvat = $chrgvats[$key];
                    $amount -= $vat;
                    $vatcode = $vatcodes[$key];
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}'";
                    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                    $vd = pg_fetch_array($Ri);
                    if ($accnt['trantype'] != "deposit") {
                        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "a");
                        # DT(account involved), CT(bank)
                        //							writetrans($accid, $banklnk['accnum'], $date, $refnum, ($amount-$vat), $descript);
                        writetrans($accid, $banklnk['accnum'], $date, $refnum, $amount, $descript);
                        if ($vat != 0) {
                            # DT(Vat), CT(Bank)
                            writetrans($vatacc, $banklnk['accnum'], $date, $refnum, $vat, $descript);
                            vatr($vd['id'], $accnt['date'], "INPUT", $vd['code'], $refnum, $accnt['descript'], -$amount, -$vat);
                        }
                    } else {
                        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                        # DT(bank), CT(account invoilved)
                        //							writetrans($banklnk['accnum'], $accid, $date, $refnum, ($amount-$vat), $descript);
                        writetrans($banklnk['accnum'], $accid, $date, $refnum, $amount, $descript);
                        if ($vat != 0) {
                            # DT(Vat), CT(Bank)
                            vatr($vd['id'], $accnt['date'], "OUTPUT", $vd['code'], $refnum, $accnt['descript'], $amount, $vat);
                            writetrans($banklnk['accnum'], $vatacc, $date, $refnum, $vat, $descript);
                        }
                    }
                }
                db_connect();
                $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accids, amounts, chrgvats, vats, reference, div) VALUES ('{$accnt['bankid']}', 'deposit', '{$accnt['date']}', '{$accnt['name']}', '{$accnt['descript']}', '{$accnt['cheqnum']}', '{$accnt['amount']}', 'no', '{$accnt['accids']}', '{$accnt['amounts']}', '{$accnt['chrgvats']}', '{$accnt['vats']}', '{$accnt['reference']}', '" . USER_DIV . "')";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                db_connect();
                $Sl = "DELETE FROM batch_cashbook WHERE cashid='{$accnt['cashid']}'";
                $Ri = db_exec($Sl);
            } else {
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes WHERE id='{$accnt['vatcode']}'";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $vd = pg_fetch_array($Ri);
                # record the payment record
                db_connect();
                $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div, vatcode, reference) VALUES ('{$bankid}', 'deposit', '{$accnt['date']}', '{$accnt['name']}', '{$accnt['descript']}', '{$accnt['cheqnum']}', '{$accnt['amount']}', '{$accnt['vat']}', '{$accnt['chrgvat']}', 'no', '{$accnt['accinv']}', '" . USER_DIV . "', '{$accnt['vatcode']}', '{$accnt['reference']}')";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                vatr($vd['id'], $accnt['date'], "OUTPUT", $vd['code'], $refnum, $accnt['descript'], $accnt['amount'], $accnt['vat']);
                # DT(account involved), CT(bank)
                writetrans($banklnk['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $accnt['amount'] - $accnt['vat'], $accnt['descript']);
                if ($accnt['vat'] != 0) {
                    # DT(Vat), CT(Bank)
                    writetrans($banklnk['accnum'], $vatacc, $accnt['date'], $refnum, $accnt['vat'], $accnt['descript']);
                }
                //		}
                db_connect();
                $Sl = "DELETE FROM batch_cashbook WHERE cashid='{$accnt['cashid']}'";
                $Ri = db_exec($Sl);
                continue;
                if (strlen($accnt['accids']) > 0) {
                    $acc['accname'] = "<a href=# onClick=openSmallWindow('multi-acc-popup.php?cashid={$accnt['cashid']}')>Multiple Accounts</a>";
                    $acc['accname'] = "";
                    $acc['accno'] = "";
                } else {
                    # Get account name for the account involved
                    $AccRslt = get("core", "accname, topacc, accnum", "accounts", "accid", $accnt['accinv']);
                    $acc = pg_fetch_array($AccRslt);
                    $acc['accno'] = "{$acc['topacc']}/{$acc['accnum']}";
                }
                # Get account name for bank account
                db_connect();
                $sql = "SELECT accname,btype FROM bankacct WHERE bankid= '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
                $bnameRslt = db_exec($sql);
                $bname = pg_fetch_array($bnameRslt);
                $rtotal += $accnt['amount'];
                // add to rtotal
                $accnt['amount'] = sprint($accnt['amount']);
                $accnt['date'] = ext_rdate($accnt['date']);
                if ($bname['btype'] != "loc") {
                    $ex = "/ {$fc} {$accnt['famount']}";
                } else {
                    $ex = "";
                }
                $OUTPUT .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>{$accnt['date']}</td>\n\t\t\t\t\t\t\t\t<td align='center'>{$bname['accname']}</td>\n\t\t\t\t\t\t\t\t<td align='center'>{$accnt['cheqnum']}</td>\n\t\t\t\t\t\t\t\t<td align='center'>{$accnt['name']}</td>\n\t\t\t\t\t\t\t\t<td>{$accnt['descript']}</td>\n\t\t\t\t\t\t\t\t<td>{$acc['accno']}  {$acc['accname']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$accnt['amount']} {$ex}</td>";
                if ($accnt['banked'] == "no" && $accnt['opt'] != 'n') {
                    //$OUTPUT .= "<td><a href='batch-enytry-delete.php?id=$accnt[cashid]'>Delete</td>";
                    $OUTPUT .= "<input type='hidden' name='pro[" . $accnt['cashid'] . "]' value='1'>";
                    // $OUTPUT .= "<td><a href='../bank/cheq-cancel.php?cashid=$accnt[cashid]'>Cancel</td>";
                }
                $OUTPUT .= "</tr>";
            }
        }
        # print the total
        $OUTPUT .= "\n\t\t\t<tr class='" . bg_class() . "''>\n\t\t\t\t<td colspan='6'><b>Total Receipts</b></td>\n\t\t\t\t<td><b>" . CUR . " " . sprintf("%01.2f", $rtotal) . "</b></td>\n\t\t\t</tr>";
    }
    # Seperate the tables with two rows
    $OUTPUT .= "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='7'><br></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='7'><br></td>\n\t\t\t\t\t</tr>";
    # Payments
    $OUTPUT .= "\n\t\t<tr>\n\t\t\t<td colspan='7'><h4>Payments</h4></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th>Date</th>\n\t\t\t<th>Bank Account Name</th>\n\t\t\t<th>Cheque Number</th>\n\t\t\t<th>Paid to: </th>\n\t\t\t<th>Description</th>\n\t\t\t<th>Ledger Account</th>\n\t\t\t<th>Amount</th>\n\t\t</tr>";
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    # Get hook account number
    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.";
    }
    $banklnk = pg_fetch_array($rslt);
    $ptotal = 0;
    // payments total
    // Connect to database
    db_Connect();
    $sql = "SELECT * FROM batch_cashbook WHERE date >= '{$from}' AND date <= '{$to}' AND trantype='withdrawal' AND bankid='{$bankid}' AND div = '" . USER_DIV . "' {$order}";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank deposits details from database.", SELF);
    if (pg_numrows($accntRslt) < 1) {
        //$OUTPUT .= "<tr><td colspan=7 align=center><li class=err>There are batch no Payments made for the selected period.</td></tr>";
    } else {
        # Display all bank payments
        for ($i = 0; $accnt = pg_fetch_array($accntRslt); $i++) {
            if (!isset($pro[$accnt['cashid']])) {
                continue;
            }
            if ($accnt['bt'] == "payment") {
                $refnum = getrefnum();
                if (strlen($accnt['accids']) > 0) {
                    $accids = explode("|", $accnt['accids']);
                    $vatcodes = explode("|", $accnt['vatcodes']);
                    $amounts = explode("|", $accnt['amounts']);
                    $vats = explode("|", $accnt['vats']);
                    $chrgvats = explode("|", $accnt['chrgvats']);
                    $refnum = getrefnum();
                    $descript = $accnt['descript'];
                    //$date = date("Y-m-d");
                    $date = $accnt['date'];
                    foreach ($amounts as $key => $amount) {
                        # SQL Array Rule: Thou shalt skip Zero Reference
                        if ($key < 1) {
                            continue;
                        }
                        $accid = $accids[$key];
                        $vat = $vats[$key];
                        $chrgvat = $chrgvats[$key];
                        $amount -= $vat;
                        $vatcode = $vatcodes[$key];
                        db_conn('cubit');
                        $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}'";
                        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                        $vd = pg_fetch_array($Ri);
                        if ($accnt['trantype'] != "deposit") {
                            $vatacc = gethook("accnum", "salesacc", "name", "VAT", "a");
                            # DT(account involved), CT(bank)
                            //							writetrans($accid, $banklnk['accnum'], $date, $refnum, $amount-$vat, $descript);
                            writetrans($accid, $banklnk['accnum'], $date, $refnum, $amount, $descript);
                            if ($vat != 0) {
                                # DT(Vat), CT(Bank)
                                writetrans($vatacc, $banklnk['accnum'], $date, $refnum, $vat, $descript);
                                vatr($vd['id'], $accnt['date'], "INPUT", $vd['code'], $refnum, $accnt['descript'], -$amount, -$vat);
                            }
                        } else {
                            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                            # DT(bank), CT(account invoilved)
                            writetrans($banklnk['accnum'], $accid, $date, $refnum, $amount, $descript);
                            if ($vat != 0) {
                                # DT(Vat), CT(Bank)
                                writetrans($banklnk['accnum'], $vatacc, $date, $refnum, $vat, $descript);
                                vatr($vd['id'], $accnt['date'], "OUTPUT", $vd['code'], $refnum, $accnt['descript'], $amount, $vat);
                            }
                        }
                    }
                    db_connect();
                    $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accids, amounts, chrgvats, vats, div, vatcode, reference) VALUES ('{$accnt['bankid']}', 'withdrawal', '{$accnt['date']}', '{$accnt['name']}', '{$accnt['descript']}', '{$accnt['cheqnum']}', '{$accnt['amount']}', 'no', '{$accnt['accids']}', '{$accnt['amounts']}', '{$accnt['chrgvats']}', '{$accnt['vats']}', '" . USER_DIV . "','{$accnt['vatcode']}', '{$accnt['reference']}')";
                    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                } else {
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$accnt['vatcode']}'";
                    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                    $vd = pg_fetch_array($Ri);
                    # Record the payment record
                    db_connect();
                    $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div, vatcode, reference) VALUES ('{$bankid}', 'withdrawal', '{$accnt['date']}', '{$accnt['name']}', '{$accnt['descript']}', '{$accnt['cheqnum']}', '{$accnt['amount']}', '{$accnt['vat']}', '{$accnt['chrgvat']}', 'no', '{$accnt['accinv']}', '" . USER_DIV . "','{$accnt['vatcode']}', '{$accnt['reference']}')";
                    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                    vatr($vd['id'], $accnt['date'], "INPUT", $vd['code'], $refnum, $accnt['descript'], -$accnt['amount'], -$accnt['vat']);
                    # DT(account involved), CT(bank)
                    writetrans($accnt['accinv'], $banklnk['accnum'], $accnt['date'], $refnum, $accnt['amount'] - $accnt['vat'], $accnt['descript']);
                    if ($accnt['vat'] != 0) {
                        # DT(Vat), CT(Bank)
                        writetrans($vatacc, $banklnk['accnum'], $accnt['date'], $refnum, $accnt['vat'], $accnt['descript']);
                    }
                }
                db_connect();
                $Sl = "DELETE FROM batch_cashbook WHERE cashid='{$accnt['cashid']}'";
                $Ri = db_exec($Sl);
                continue;
                if (strlen($accnt['accids']) > 0) {
                    $acc['accname'] = "<a href=# onClick=openSmallWindow('multi-acc-popup.php?cashid={$accnt['cashid']}')>Multiple Accounts</a>";
                    $acc['accno'] = "";
                } else {
                    # get account name for the account involved
                    $AccRslt = get("core", "accname, topacc, accnum", "accounts", "accid", $accnt['accinv']);
                    $acc = pg_fetch_array($AccRslt);
                    $acc['accno'] = "{$acc['topacc']}/{$acc['accnum']}";
                }
                # get account name for bank account
                db_connect();
                $sql = "SELECT accname,btype FROM bankacct WHERE bankid= '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
                $bnameRslt = db_exec($sql);
                $bname = pg_fetch_array($bnameRslt);
                $ptotal += $accnt['amount'];
                //add to total
                $accnt['amount'] = sprint($accnt['amount']);
                $accnt['date'] = ext_rdate($accnt['date']);
                if ($bname['btype'] != "loc") {
                    $ex = "/ {$fc} {$accnt['famount']}";
                } else {
                    $ex = "";
                }
                $OUTPUT .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>{$accnt['date']}</td>\n\t\t\t\t\t\t\t<td align='center'>{$bname['accname']}</td>\n\t\t\t\t\t\t\t<td align='center'>{$accnt['cheqnum']}</td>\n\t\t\t\t\t\t\t<td align='center'>{$accnt['name']}</td>\n\t\t\t\t\t\t\t<td>{$accnt['descript']}</td>\n\t\t\t\t\t\t\t<td>{$acc['accno']}  {$acc['accname']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$accnt['amount']} {$ex}</td>";
                if ($accnt['banked'] == "no" && $accnt['opt'] != 'n') {
                    //$OUTPUT .= "<td><a href='batch-enytry-delete.php?id=$accnt[cashid]'>Delete</td>";
                    $OUTPUT .= "<input type='hidden' name='pro[" . $accnt['cashid'] . "]' value='1'>";
                    //$OUTPUT .= "<td><a href='../bank/cheq-return.php?cashid=$accnt[cashid]'>Returned/Unpaid</td>";
                    // $OUTPUT .= "<td><a href='../bank/cheq-cancel.php?cashid=$accnt[cashid]'>Cancel</td>";
                }
                $OUTPUT .= "</tr>";
            } elseif ($accnt['bt'] == "transfer") {
                $refnum = getrefnum();
                extract($accnt);
                db_connect();
                $sql = "SELECT accname, bankname FROM bankacct WHERE bankid = '{$bankid}' AND div = '" . USER_DIV . "'";
                $fbankRslt = db_exec($sql);
                $fbank = pg_fetch_array($fbankRslt);
                $sql = "SELECT accname, bankname FROM bankacct WHERE bankid = '{$rid}' AND div = '" . USER_DIV . "'";
                $tbankRslt = db_exec($sql);
                $tbank = pg_fetch_array($tbankRslt);
                $faccid = getbankaccid($bankid);
                $taccid = getbankaccid($rid);
                # write trans
                writetrans($taccid, $faccid, $date, $refnum, $amount, $descript);
                # Record the payment record
                db_connect();
                $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, div, reference) VALUES ('{$bankid}', 'withdrawal', '{$date}', '{$tbank['accname']} - {$tbank['bankname']}', '{$descript}', '{$cheqnum}', '{$amount}', 'no', '{$taccid}', '" . USER_DIV . "', '{$reference}')";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                $lcashid = pglib_lastid("cashbook", "cashid");
                $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accinv, div, reference) VALUES ('{$rid}', 'deposit', '{$date}', '{$fbank['accname']} - {$fbank['bankname']}', '{$descript}', '{$cheqnum}', '{$amount}', 'no', '{$faccid}', '" . USER_DIV . "', '{$reference}')";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                $lcashid2 = pglib_lastid("cashbook", "cashid");
                # restore link
                $sql = "UPDATE cashbook SET lcashid = '{$lcashid2}' WHERE cashid = '{$lcashid}'";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                $sql = "UPDATE cashbook SET lcashid = '{$lcashid}' WHERE cashid = '{$lcashid2}'";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                db_connect();
                $Sl = "DELETE FROM batch_cashbook WHERE cashid='{$accnt['cashid']}'";
                $Ri = db_exec($Sl);
            } else {
                $refnum = getrefnum();
                if (strlen($accnt['accids']) > 0) {
                    $accids = explode("|", $accnt['accids']);
                    $vatcodes = explode("|", $accnt['vatcodes']);
                    $amounts = explode("|", $accnt['amounts']);
                    $vats = explode("|", $accnt['vats']);
                    $chrgvats = explode("|", $accnt['chrgvats']);
                    $refnum = getrefnum();
                    $descript = $accnt['descript'];
                    $date = $accnt["date"];
                    foreach ($amounts as $key => $amount) {
                        # SQL Array Rule: Thou shalt skip Zero Reference
                        if ($key < 1) {
                            continue;
                        }
                        $accid = $accids[$key];
                        $vat = $vats[$key];
                        $chrgvat = $chrgvats[$key];
                        //$amount -= $vat;
                        $vatcode = $vatcodes[$key];
                        db_conn('cubit');
                        $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}'";
                        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                        $vd = pg_fetch_array($Ri);
                        if ($accnt['trantype'] != "deposit") {
                            $vatacc = gethook("accnum", "salesacc", "name", "VAT", "a");
                            # DT(account involved), CT(bank)
                            writetrans($accid, $banklnk['accnum'], $date, $refnum, $amount - $vat, $descript);
                            if ($vat != 0) {
                                # DT(Vat), CT(Bank)
                                writetrans($vatacc, $banklnk['accnum'], $date, $refnum, $vat, "{$descript}");
                                vatr($vd['id'], $accnt['date'], "INPUT", $vd['code'], $refnum, $accnt['descript'], -$amount, -$vat);
                            }
                        } else {
                            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                            # DT(bank), CT(account invoilved)
                            writetrans($banklnk['accnum'], $accid, $date, $refnum, $amount - $vat, $descript);
                            if ($vat != 0) {
                                # DT(Vat), CT(Bank)
                                writetrans($banklnk['accnum'], $vatacc, $date, $refnum, $vat, "{$descript}");
                                vatr($vd['id'], $accnt['date'], "OUTPUT", $vd['code'], $refnum, $accnt['descript'], $amount, $vat);
                            }
                        }
                    }
                    db_connect();
                    $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accids, amounts, chrgvats, vats, div, vatcode, reference) VALUES ('{$accnt['bankid']}', 'withdrawal', '{$accnt['date']}', '{$accnt['name']}', '{$accnt['descript']}', '{$accnt['cheqnum']}', '{$accnt['amount']}', 'no', '{$accnt['accids']}', '{$accnt['amounts']}', '{$accnt['chrgvats']}', '{$accnt['vats']}', '" . USER_DIV . "','{$accnt['vatcode']}', '{$accnt['reference']}')";
                    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                } else {
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes WHERE id='{$accnt['vatcode']}'";
                    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                    $vd = pg_fetch_array($Ri);
                    # Record the payment record
                    db_connect();
                    $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div, vatcode, reference) VALUES ('{$bankid}', 'withdrawal', '{$accnt['date']}', '{$accnt['name']}', '{$accnt['descript']}', '{$accnt['cheqnum']}', '{$accnt['amount']}', '{$accnt['vat']}', '{$accnt['chrgvat']}', 'no', '{$accnt['accinv']}', '" . USER_DIV . "','{$accnt['vatcode']}', '{$accnt['reference']}')";
                    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                    vatr($vd['id'], $accnt['date'], "INPUT", $vd['code'], $refnum, $accnt['descript'], -$accnt['amount'], -$accnt['vat']);
                    # DT(account involved), CT(bank)
                    writetrans($accnt['accinv'], $banklnk['accnum'], $accnt['date'], $refnum, $accnt['amount'] - $accnt['vat'], $accnt['descript']);
                    if ($accnt['vat'] != 0) {
                        # DT(Vat), CT(Bank)
                        writetrans($vatacc, $banklnk['accnum'], $accnt['date'], $refnum, $accnt['vat'], $accnt['descript']);
                    }
                }
                db_connect();
                $Sl = "DELETE FROM batch_cashbook WHERE cashid='{$accnt['cashid']}'";
                $Ri = db_exec($Sl);
                continue;
                if (strlen($accnt['accids']) > 0) {
                    $acc['accname'] = "<a href=# onClick=openSmallWindow('multi-acc-popup.php?cashid={$accnt['cashid']}')>Multiple Accounts</a>";
                    $acc['accno'] = "";
                } else {
                    # get account name for the account involved
                    $AccRslt = get("core", "accname, topacc, accnum", "accounts", "accid", $accnt['accinv']);
                    $acc = pg_fetch_array($AccRslt);
                    $acc['accno'] = "{$acc['topacc']}/{$acc['accnum']}";
                }
                # get account name for bank account
                db_connect();
                $sql = "SELECT accname,btype FROM bankacct WHERE bankid= '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
                $bnameRslt = db_exec($sql);
                $bname = pg_fetch_array($bnameRslt);
                $ptotal += $accnt['amount'];
                //add to total
                $accnt['amount'] = sprint($accnt['amount']);
                $accnt['date'] = ext_rdate($accnt['date']);
                if ($bname['btype'] != "loc") {
                    $ex = "/ {$fc} {$accnt['famount']}";
                } else {
                    $ex = "";
                }
                $OUTPUT .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>{$accnt['date']}</td>\n\t\t\t\t\t\t\t<td align='center'>{$bname['accname']}</td>\n\t\t\t\t\t\t\t<td align='center'>{$accnt['cheqnum']}</td>\n\t\t\t\t\t\t\t<td align='center'>{$accnt['name']}</td>\n\t\t\t\t\t\t\t<td>{$accnt['descript']}</td>\n\t\t\t\t\t\t\t<td>{$acc['accno']}  {$acc['accname']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$accnt['amount']} {$ex}</td>";
                if ($accnt['banked'] == "no" && $accnt['opt'] != 'n') {
                    //$OUTPUT .= "<td><a href='batch-enytry-delete.php?id=$accnt[cashid]'>Delete</td>";
                    $OUTPUT .= "<input type='hidden' name='pro[" . $accnt['cashid'] . "]' value='1'>";
                    //$OUTPUT .= "<td><a href='../bank/cheq-return.php?cashid=$accnt[cashid]'>Returned/Unpaid</td>";
                    // $OUTPUT .= "<td><a href='../bank/cheq-cancel.php?cashid=$accnt[cashid]'>Cancel</td>";
                }
                $OUTPUT .= "</tr>";
            }
        }
        # print the total
        $OUTPUT .= "\n\t\t\t<tr class='" . bg_class() . "''>\n\t\t\t\t<td colspan='6'><b>Total Payments</b></td>\n\t\t\t\t<td><b>" . CUR . " " . sprintf("%01.2f", $ptotal) . "</b></td>\n\t\t\t</tr>";
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $OUTPUT = "\n\t\t\t\t<table " . TMPL_tblDflts . " width='25%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Done</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t<td>Batch entries have been processed.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table><br>" . mkQuickLinks(ql("../core/acc-new2.php", "Add New Account"));
    return $OUTPUT;
}
function write($_POST)
{
    extract($_POST);
    if (isset($back)) {
        unset($_POST["back"]);
        return alloc($_POST);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($rec_amount, "num", 1, 5, "Invalid amount of entries.");
    for ($t = 0; $t < $rec_amount; $t++) {
        if (!isset($descript[$t]) or !isset($reference[$t]) or !isset($setamt[$t]) or empty($descript[$t]) or empty($reference[$t]) or empty($setamt[$t])) {
            continue;
        }
        $v->isOk($bankid[$t], "num", 1, 30, "Invalid Bank Account.");
        $v->isOk($date[$t], "date", 1, 14, "Invalid Date.");
        $v->isOk($out[$t], "float", 1, 40, "Invalid out amount.");
        $v->isOk($descript[$t], "string", 0, 255, "Invalid Description.");
        $v->isOk($reference[$t], "string", 0, 50, "Invalid Reference Name/Number.");
        $v->isOk($cheqnum[$t], "num", 0, 30, "Invalid Cheque number.");
        $v->isOk($amt[$t], "float", 1, 40, "Invalid amount.");
        $v->isOk($setamt[$t], "float", 1, 40, "Invalid Settlement amount.");
        $v->isOk($setvat[$t], "string", 1, 10, "Invalid Settlement VAT Option.");
        $v->isOk($setvatcode[$t], "string", 1, 40, "Invalid Settlement VAT code");
        $v->isOk($cusid[$t], "num", 1, 40, "Invalid customer number.");
        $v->isOk($out1[$t], "float", 0, 40, "Invalid paid amount(currant).");
        $v->isOk($out2[$t], "float", 0, 40, "Invalid paid amount(30).");
        $v->isOk($out3[$t], "float", 0, 40, "Invalid paid amount(60).");
        $v->isOk($out4[$t], "float", 0, 40, "Invalid paid amount(90).");
        $v->isOk($out5[$t], "float", 0, 40, "Invalid paid amount(120).");
        if (isset($invids[$t])) {
            foreach ($invids[$t] as $key => $value) {
                $v->isOk($invids[$t][$key], "num", 1, 50, "Invalid Invoice No.");
                $v->isOk($paidamt[$t][$key], "float", 1, 40, "Invalid amount to be paid.");
            }
        }
        if (strtotime($date[$t]) >= strtotime($blocked_date_from) and strtotime($date[$t]) <= 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>";
        }
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . confirm($_POST);
    }
    for ($t = 0; $t < $rec_amount; $t++) {
        if (!isset($descript[$t]) or !isset($reference[$t]) or !isset($setamt[$t]) or empty($descript[$t]) or empty($reference[$t]) or empty($setamt[$t])) {
            continue;
        }
        /* get bank account id */
        if (($bank_acc[$t] = getbankaccid($bankid[$t])) === false) {
            $sql = "SELECT accid FROM core.accounts WHERE accname='Cash on Hand'";
            $rslt = db_exec($sql);
            if (pg_num_rows($rslt) < 1) {
                if ($bankid[$t] == 0) {
                    return "There is no 'Cash on Hand' account, there was one, but\n\t\t\t\t\t\t**s not there now, you mudst have deleted it, if you want\n\t\t\t\t\t\tto use cash functionality please create a 'Cash on Hand' account.";
                } else {
                    return "Invalid bank acc.";
                }
            }
            $bank_acc[$t] = pg_fetch_result($rslt, 0);
        }
        $cus = qryCustomer($cusid[$t], "cusnum, deptid, cusname, surname");
        $dept = qryDepartment($cus["deptid"], "debtacc");
        $refnum = getrefnum();
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        # date format
        $sdate[$t] = explode("-", $date[$t]);
        $sdate[$t] = $sdate[$t][2] . "-" . $sdate[$t][1] . "-" . $sdate[$t][0];
        $cheqnum[$t] = 0 + $cheqnum[$t];
        $pay = "";
        $accdate[$t] = $sdate[$t];
        /* Paid invoices */
        $invidsers = "";
        $rinvids = "";
        $amounts = "";
        $invprds = "";
        $rages = "";
        /* OPTION 1 : AUTO ALLOCATE (write) */
        if ($all == 0) {
            # update the customer (make balance less)
            $sql = "UPDATE cubit.customers SET balance = (balance - '{$amt[$t]}'::numeric(13,2))\n\t\t\t\t\tWHERE cusnum = '{$cus['cusnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            if (isset($invids[$t])) {
                foreach ($invids[$t] as $key => $value) {
                    $ii = $invids[$t][$key];
                    $pp = $paidamt[$t][$key];
                    /* OPTION 1: STOCK INVOICES */
                    if (!isset($itype[$t][$ii]) && !isset($ptype[$t][$ii])) {
                        $sql = "SELECT prd,invnum,odate FROM cubit.invoices\n\t\t\t\t\t\t\t\tWHERE invid ='{$ii}' AND div = '" . USER_DIV . "'";
                        $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                        if (pg_numrows($invRslt) < 1) {
                            return "<li class='err'>Invalid Invoice Number.</li>";
                        }
                        $inv = pg_fetch_array($invRslt);
                        $inv['invnum'] += 0;
                        // reduce invoice balance
                        $sql = "UPDATE cubit.invoices \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        $sql = "UPDATE cubit.open_stmnt \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                        $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        # record the payment on the statement
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($pp - $pp * 2) . "', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                        custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $paidamt[$t][$key], "c");
                        $rinvids .= "|{$invids[$t]}[{$key}]";
                        $amounts .= "|{$pp}";
                        if ($inv['prd'] == "0") {
                            $inv['prd'] = PRD_DB;
                        }
                        $invprds .= "|{$inv['prd']}";
                        $rages .= "|0";
                        $invidsers .= " - {$inv['invnum']}";
                        /* OPTION 1: NONS STOCK INVOICES */
                    } else {
                        if (!isset($ptype[$t][$ii])) {
                            $sql = "SELECT prd,invnum,descrip,age,odate FROM cubit.nons_invoices\n\t\t\t\t\t\t\t\tWHERE invid ='{$ii}' AND div = '" . USER_DIV . "'";
                            $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                            if (pg_numrows($invRslt) < 1) {
                                return "<li class='err'>Invalid Invoice Number.</li>";
                            }
                            $inv = pg_fetch_array($invRslt);
                            $inv['invnum'] += 0;
                            # reduce the money that has been paid
                            $sql = "UPDATE cubit.nons_invoices\n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            $sql = "UPDATE cubit.open_stmnt\n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2))\n\t\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            # record the payment on the statement
                            $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($pp - $pp * 2) . "', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $paidamt[$t][$key], "c");
                            recordCT($pp, $cus['cusnum'], $inv['age'], $accdate[$t]);
                            $rinvids .= "|{$ii}";
                            $amounts .= "|{$pp}";
                            $invprds .= "|0";
                            $rages .= "|{$inv['age']}";
                            $invidsers .= " - {$inv['invnum']}";
                        } else {
                            /* pos invoices */
                            $sqls = array();
                            for ($i = 1; $i <= 12; ++$i) {
                                $sqls[] = "SELECT '{$i}' AS prd,invid,invnum,odate FROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\t\t\tWHERE invid='{$ii}' AND div='" . USER_DIV . "'";
                            }
                            $sql = implode(" UNION ", $sqls);
                            $invRslt = db_exec($sql) or errDie("Unable to retrieve invoice details from database.");
                            if (pg_numrows($invRslt) < 1) {
                                return "<li class='err'>Invalid Invoice Number.</li>";
                            }
                            $inv = pg_fetch_array($invRslt);
                            // reduce the invoice balance
                            $sql = "UPDATE \"{$inv['prd']}\".pinvoices \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2)) \n\t\t\t\t\t\t\t\tWHERE invid = '{$ii}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            $sql = "UPDATE cubit.open_stmnt \n\t\t\t\t\t\t\t\tSET balance = (balance - {$pp}::numeric(13,2)) \n\t\t\t\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                            $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                            # record the payment on the statement
                            $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, date, type, div, allocation_date\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}','{$inv['invnum']}', '" . ($pp - $pp * 2) . "','{$sdate[$t]}', 'Payment for Non Stock Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t\t\t)";
                            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']}", $paidamt[$t][$key], "c");
                            recordCT($paidamt[$t][$key], $cus['cusnum'], 0, $accdate[$t]);
                            $rinvids .= "|{$invids[$t]}[{$key}]";
                            $amounts .= "|{$paidamt[$t]}[{$key}]";
                            $invprds .= "|{$inv['prd']}";
                            //$rages .= "|$inv[age]";
                            $invidsers .= " - {$inv['invnum']}";
                        }
                    }
                }
            }
            $cols = grp(m("bankid", $bankid[$t]), m("trantype", "deposit"), m("date", $sdate[$t]), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheqnum[$t]), m("amount", $amt[$t]), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference[$t]), m("div", USER_DIV));
            $dbobj = new dbUpdate("cashbook", "cubit", $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            /*
            $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript,
            			cheqnum, amount, banked, accinv, cusnum, rinvids, amounts,
            			invprds, rages, reference, div)
            		VALUES ('$bankid', 'deposit', '$sdate', '$cus[cusname] $cus[surname]',
            			'',
            			'$cheqnum', '$amt', 'no', '$dept[debtacc]', '$cus[cusnum]',
            			'$rinvids', '$amounts', '$invprds', '$rages', '$reference',
            			'".USER_DIV."')";
            $Rslt = db_exec ($sql) or errDie ("Unable to add bank payment to database.",SELF);
            */
            $refnum = getrefnum($accdate[$t]);
            writetrans($bank_acc[$t], $dept['debtacc'], $accdate[$t], $refnum, $amt[$t], "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
            db_conn('cubit');
            if ($out > 0) {
                /* START OPEN ITEMS */
                $openstmnt = new dbSelect("open_stmnt", "cubit", grp(m("where", "balance>0 AND cusnum='{$cusid[$t]}'"), m("order", "date")));
                $openstmnt->run();
                $open_out[$t] = $out[$t];
                $i = 0;
                $ox = "";
                while ($od = $openstmnt->fetch_array()) {
                    if ($open_out[$t] == 0) {
                        continue;
                    }
                    $oid = $od['id'];
                    if ($open_out[$t] >= $od['balance']) {
                        $open_amount[$t][$oid] = $od['balance'];
                        $open_out[$t] = sprint($open_out[$t] - $od['balance']);
                        $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$t}][{$oid}]' value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$t}][{$oid}]' value='{$open_amount[$t]}[{$oid}]'>" . CUR . " {$open_amount[$t]}[{$oid}]</td>\n\t\t\t\t\t\t\t</tr>";
                        $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'" . $open_amount[$t][$oid] . "' WHERE id='{$oid}'";
                        $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                    } elseif ($open_out < $od['balance']) {
                        $open_amount[$t][$oid] = $open_out[$t];
                        $open_out = 0;
                        $ox .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$t}][{$oid}]' value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$t}][{$oid}]' value='{$open_amount[$t]}[{$oid}]'>" . CUR . " {$open_amount[$t]}[{$oid}]</td>\n\t\t\t\t\t\t\t</tr>";
                        $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'" . $open_amount[$t][$oid] . "' WHERE id='{$oid}'";
                        $Ri = db_exec($Sl) or errDie("Unable to update statement.");
                    }
                    $i++;
                }
                if (open()) {
                    $bout[$t] = $out[$t];
                    $out[$t] = $open_out[$t];
                    if ($out > 0) {
                        $sql = "\n\t\t\t\t\t\t\tINSERT INTO cubit.open_stmnt (\n\t\t\t\t\t\t\t\tcusnum, invid, amount, balance, date, \n\t\t\t\t\t\t\t\ttype, st, div\n\t\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t\t'{$cus['cusnum']}', '0', '-{$out[$t]}', '-{$out[$t]}', '{$sdate[$t]}', \n\t\t\t\t\t\t\t\t'Payment Received', 'n', '" . USER_DIV . "'\n\t\t\t\t\t\t\t)";
                        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                        //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";
                    }
                    $out[$t] = $bout[$t];
                } else {
                    //$confirm .="<tr class='bg-even'><td colspan=4><b>A general transaction will credit the client's account with ".CUR." $out </b></td></tr>";}
                }
            }
            if ($out[$t] > 0) {
                recordCT($out[$t], $cus['cusnum'], 0, $accdate[$t]);
                $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$out[$t]), m("date", $sdate[$t]), m("type", "Payment Received"), m("div", USER_DIV), m("allocation_date", $accdate[$t]));
                $dbobj = new dbUpdate("stmnt", "cubit", $cols);
                $dbobj->run(DB_INSERT);
                $dbobj->free();
                custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], "PAYMENT", "Payment received.", $out[$t], "c");
            }
        }
        /* start moving invoices */
        // move invoices that are fully paid
        $sql = "SELECT * FROM cubit.invoices WHERE balance=0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
        $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        while ($x = pg_fetch_array($invbRslt)) {
            if (($prd = $x['prd']) == "0") {
                $prd = PRD_DB;
            }
            // move invoice
            $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
            $dbobj = new dbUpdate("invoices", $prd, $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            // record movement
            $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
            $dbobj->setTable("movinv", "cubit");
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
            // move invoice items
            $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
            $inv_items->run();
            while ($xi = $inv_items->fetch_array()) {
                $xi['vatcode'] += 0;
                $xi['account'] += 0;
                $xi['del'] += 0;
                $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
                $dbobj->setTable("inv_items", $prd);
                $dbobj->setOpt($cols);
                $dbobj->run();
                $dbobj->free();
            }
            /* remove invoice from cubit schema */
            $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
            $dbobj->run();
            $dbobj->setTable("inv_items", "cubit");
            $dbobj->run();
        }
        /* start moving invoices */
        // move invoices that are fully paid
        $sql = "SELECT * FROM cubit.invoices WHERE balance=0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
        $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
        while ($x = pg_fetch_array($invbRslt)) {
            if (($prd = $x['prd']) == "0") {
                $prd = PRD_DB;
            }
            // move invoice
            $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
            $dbobj = new dbUpdate("invoices", $prd, $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            // record movement
            $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
            $dbobj->setTable("movinv", "cubit");
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
            // move invoice items
            $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
            $inv_items->run();
            while ($xi = $inv_items->fetch_array()) {
                $xi['vatcode'] += 0;
                $xi['account'] += 0;
                $xi['del'] += 0;
                $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
                $dbobj->setTable("inv_items", $prd);
                $dbobj->setOpt($cols);
                $dbobj->run();
                $dbobj->free();
            }
            /* remove invoice from cubit schema */
            $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
            $dbobj->run();
            $dbobj->setTable("inv_items", "cubit");
            $dbobj->run();
        }
        #do journal for the settlement discount here ... now ...
        if ($setamt[$t] > 0) {
            db_conn('core');
            #get settlement accid
            $get_setacc = "SELECT accid FROM accounts WHERE accname = 'Debtors Settlement Discount'";
            $run_setacc = db_exec($get_setacc) or errDie("Unable to get settlement account information");
            $setaccid = pg_fetch_result($run_setacc, 0, 0);
            #calculate the settlement vat ... and amt
            if (isset($setvat[$t]) and $setvat[$t] == 'inc') {
                db_connect();
                $get_vcode = "SELECT * FROM vatcodes WHERE id = '{$setvatcode[$t]}' LIMIT 1";
                $run_vcode = db_exec($get_vcode) or errDie("Unable to get vatcode informtion.");
                if (pg_numrows($run_vcode) < 1) {
                    return "<li class='err'>Settlement Discount VAT Code Not Set.</li>";
                }
                $vd = pg_fetch_array($run_vcode);
                #vat inc ... recalculate the amts
                $setvatamt = sprint($setamt[$t] * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
                $setamt[$t] = sprint($setamt[$t] - $setvatamt);
                $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
                $svattot = sprint($setamt[$t] + $setvatamt - ($setamt[$t] + $setvatamt) * 2);
                $svatamt = sprint($setvatamt - $setvatamt * 2);
                #process the vat amt ...
                writetrans($vatacc, $dept['debtacc'], $accdate[$t], $refnum, $setvatamt, "VAT Received on Settlement Discount for Customer : {$cus['cusname']} {$cus['surname']}");
                vatr($vd['id'], $accdate[$t], "OUTPUT", $vd['code'], $refnum, "VAT for Settlement Discount for Customer : {$cus['cusname']} {$cus['surname']}", $svattot, $svatamt);
            } else {
                #no vat for set amt ... do nothing
                $setvatamt = 0;
                $svattot = 0;
                $svatamt = 0;
            }
            writetrans($setaccid, $dept['debtacc'], $accdate[$t], $refnum, sprint($setamt[$t]), "Settlement Discount For {$cus['cusname']} {$cus['surname']}");
            custledger($cus['cusnum'], $bank_acc[$t], $sdate[$t], "{$refnum}", "Payment Settlement Discount Received.", sprint($setamt[$t] + $setvatamt), "c");
            $sql = "\n\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cus['cusnum']}', '0', '" . $svattot . "', '{$sdate[$t]}', \n\t\t\t\t\t'Settlement Discount for Payment. Ref {$refnum}', '" . USER_DIV . "', '{$accdate[$t]}'\n\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            db_connect();
            #record this paid settlement discount for reporting ...
            $settl_sql = "\n\t\t\t\tINSERT INTO settlement_cus (\n\t\t\t\t\tcustomer, amt, setamt, setvatamt, setvat, \n\t\t\t\t\tsetvatcode, tdate, sdate, refnum\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$cus['cusnum']}', '{$amt[$t]}', '{$setamt[$t]}', '{$setvatamt}', '{$setvat[$t]}', \n\t\t\t\t\t'{$setvatcode[$t]}', '{$accdate[$t]}', 'now', '{$refnum[$t]}'\n\t\t\t\t)";
            $run_settl = db_exec($settl_sql) or errDie("Unable to get debtor settlement information.");
        }
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    }
    // status report
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>Bank Receipt</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Bank Receipt added to cash book.</td>\n\t\t\t</tr>\n\t\t</table>";
    $OUTPUT = "\n\t\t<center>\n\t\t<table width='90%'>\n\t\t\t<tr valign='top'>\n\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t<td align='center'>" . mkQuickLinks(ql("bank-pay-add.php", "Add Bank Payment"), ql("bank-recpt-add.php", "Add Bank Receipt"), ql("bank-recpt-inv.php", "Add Customer Payment"), ql("cashbook-view.php", "View Cash Book")) . "\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    # used to generate errors
    $error = "asa@";
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($pur['pdate']) >= strtotime($blocked_date_from) and strtotime($pur['pdate']) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    # check if Order has been received
    if ($pur['invcd'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$pur['purnum']}</b> has already been invoiced.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    if (pg_numrows($supRslt) < 1) {
        // code here
    } else {
        $sup = pg_fetch_array($supRslt);
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class=err>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* --- Transactions --- */
    db_conn(PRD_DB);
    $refnum = getrefnum();
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    # Record the payment on the statement
    db_connect();
    $sdate = date("Y-m-d");
    $taxamt = $pur['tax'] * -1;
    $ltotal = sprint($pur['total'] * $pur['xrate']);
    $ltax = sprint($pur['tax'] * $pur['xrate']);
    db_connect();
    # update all supplies xchange rate first
    xrate_update($pur['fcid'], $pur['xrate'], "suppurch", "id");
    sup_xrate_update($pur['fcid'], $pur['xrate']);
    db_connect();
    # Update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance + '{$ltotal}'), fbalance = (fbalance + '{$pur['total']}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $DAte = date("Y-m-d");
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript, ref, ex, div) VALUES('{$pur['supid']}','{$pur['pdate']}', '{$dept['credacc']}','{$pur['total']}','International - Stock Received', '{$refnum}','{$pur['purnum']}', '" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['jobnum']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        return "Please select the vatcode for all your stock.";
    }
    $vd = pg_fetch_array($Ri);
    vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "VAT for Purchase No. {$pur['purnum']}", -($ltotal + $ltax), -$ltax);
    # Debit Stock Control and Credit Creditors control
    writetrans($wh['conacc'], $dept['credacc'], $pur['pdate'], $refnum, $ltotal - $ltax, "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
    # Debit bank and credit the account involved
    writetrans($vatacc, $dept['credacc'], $pur['pdate'], $refnum, $ltax, "Tax Paid on International Orders No. {$pur['purnum']} from Supplier {$sup['supname']}.");
    # Ledger Records
    suppledger($pur['supid'], $wh['stkacc'], $pur['pdate'], $pur['purid'], "International Order No. {$pur['purnum']} received.", $ltotal, 'c');
    db_connect();
    /* --- End Transactions --- */
    /* Make transaction record  for age analysis */
    $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, fcid, fbalance, div) VALUES('{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$ltotal}', '{$pur['fcid']}', '{$pur['total']}', '" . USER_DIV . "')";
    $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    /* Make transaction record  for age analysis */
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* Start moving if Order received and invoiced */
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        # Copy Order
        db_conn($pur['prd']);
        $sql = "INSERT INTO purch_int(purid, deptid, supid, supaddr, terms, pdate, ddate, xrate, fcid, curr, tax, shipchrg, fshipchrg, duty, subtot, total, balance, fbalance, remarks, refno, received, done, div, purnum)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['xrate']}', '{$pur['fcid']}', '{$pur['curr']}', '{$pur['tax']}', '{$pur['shipchrg']}', '{$pur['fshipchrg']}', '{$pur['duty']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['fbalance']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
        /*-- Cost varience -- */
        $nsubtot = sprint($pur['total'] - $pur['tax']);
        $nsubtot = sprint($nsubtot * $pur['xrate']);
        if ($pur['rlsubtot'] > $nsubtot) {
            $diff = sprint($pur['rlsubtot'] - $nsubtot);
            # Debit Stock Control and Credit Creditors control
            writetrans($wh['conacc'], $cvacc, $pur['pdate'], $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        } elseif ($nsubtot > $pur['rlsubtot']) {
            $diff = sprint($nsubtot - $pur['rlsubtot']);
            # Debit Stock Control and Credit Creditors control
            writetrans($cvacc, $wh['conacc'], $pur['pdate'], $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        }
        /*-- End Cost varience -- */
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert Order items
            db_conn($pur['prd']);
            $sql = "INSERT INTO purint_items(purid, whid, stkid, qty, unitcost, cunitcost, duty, dutyp, amt, ddate, recved, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['cunitcost']}', '{$stktc['duty']}', '{$stktc['dutyp']}', '{$stktc['amt']}', '{$stktc['ddate']}', 'y', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        db_connect();
        # Remove the Order from running DB
        $sql = "DELETE FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Record where Order is
        $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('int', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
        $movRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Remove those Order items from running DB
        $sql = "DELETE FROM purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    } else {
        # Insert Order to DB
        $sql = "UPDATE purch_int SET invcd = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
    }
    /* End moving Order received */
    // Final Layout
    $write = "\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>International Purchase Invoiced</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Purchase Invoice from Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='purch-int-view.php'>View International Orders</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $write;
}
function write($_GET)
{
    $showvat = TRUE;
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid Invoice number.");
    $sndate = $ninv_year . "-" . $ninv_month . "-" . $ninv_day;
    if (!checkdate($ninv_month, $ninv_day, $ninv_year)) {
        $v->addError($sdate, "Invalid Date.");
    }
    $td = $sndate;
    foreach ($ids as $key => $id) {
        $v->isOk($id, "num", 1, 20, "Invalid Item number.");
        $v->isOk($qtys[$key], "float", 1, 20, "Invalid Item quantity.");
        $v->isOk($amts[$key], "float", 1, 20, "Invalid Item amount.");
    }
    $v->isOk($subtot, "float", 1, 20, "Invalid sub-total amount.");
    $v->isOk($vat, "float", 1, 20, "Invalid vat amount.");
    $v->isOk($total, "float", 1, 20, "Invalid total amount.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM hire.hire_nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    db_conn("hire");
    $noteid = pglib_lastid("hire_nons_inv_notes", "noteid");
    $noteid++;
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    /* --- Start Products Display --- */
    $refnum = getrefnum();
    /*refnum*/
    $real_noteid = divlastid('note', USER_DIV);
    $vattot = 0;
    $amttot = 0;
    db_connect();
    # Products layout
    $products = array();
    $i = 0;
    $page = 0;
    foreach ($ids as $key => $id) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        $sql = "SELECT * FROM hire.hire_nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatex']}'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        $temp = $stkd['vatex'];
        if ($vd['zero'] == "Yes") {
            $stkd['vatex'] = "y";
        }
        $t = $inv['chrgvat'];
        //	$VATP = TAX_VAT;
        $VATP = $vd['vat_amount'];
        $stkacc = $stkd['accid'];
        # keep records for transactions
        if (isset($totstkamt[$stkacc])) {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] += $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] += vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($stkd['amt'] - vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        } else {
            if ($stkd['vatex'] == "y") {
                $totstkamt[$stkacc] = $amts[$key];
                $va = 0;
                $inv['chrgvat'] = "";
            } else {
                $totstkamt[$stkacc] = vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']);
                $va = sprint($amts[$key] - vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']));
                if ($inv['chrgvat'] == "no") {
                    $va = sprint($amts[$key] * $VATP / 100);
                }
            }
        }
        #add this entry's vat to a total
        $vattot = $vattot + $va;
        vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.", -vats($amts[$key], $inv['chrgvat'], $vd['vat_amount']) - $va, -$va);
        $inv['chrgvat'] = $t;
        $sql = "UPDATE hire.hire_nons_inv_items SET rqty = (rqty + '{$qtys[$key]}') WHERE id = '{$stkd['id']}'";
        $sRslt = db_exec($sql);
        if ($stkd['vatex'] == 'y') {
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        $stkd['vatex'] = $temp;
        #add this entry's amt to a total
        $amttot = $amttot + $amts[$key];
        $sql = "INSERT INTO hire.hire_nons_note_items(noteid, qty, description, amt, unitcost, vatcode) VALUES('{$noteid}', '{$qtys[$key]}', '{$stkd['description']}', '{$amts[$key]}', '{$stkd['unitcost']}', '{$stkd['vatex']}')";
        $stkdRslt = db_exec($sql);
        #the credit note entry will get any remark entered here ? so we dont update the invoice entry ...
        //	db_conn("cubit");
        //	$sql = "UPDATE nons_invoices SET remarks='$remarks' WHERE invid='$invid'";
        //	$rslt = db_exec($sql) or errDie("Unable to save the comments to Cubit.");
        $products[$page][] = "\r\n\t\t\t\t\t\t<tr valign='top'>\r\n\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$stkd['description']}&nbsp;</td>\r\n\t\t\t\t\t\t\t<td style='border-right: 2px solid #000'>{$qtys[$key]}&nbsp;</td>\r\n\t\t\t\t\t\t\t<td style='border-right: 2px solid #000' align='right' nowrap>" . CUR . " {$stkd['unitcost']}&nbsp;</td>\r\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$amts[$key]}&nbsp;</td>\r\n\t\t\t\t\t\t</tr>";
        $i++;
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "\r\n\t\t\t\t \t\t\t<tr>\r\n\t\t\t\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t \t\t\t\t<td>&nbsp;</td>\r\n\t\t\t\t \t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($subtot);
    $VAT = sprint($vat);
    $TOTAL = sprint($total);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "vat");
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    // print $inv['ctyp']; exit;
    db_connect();
    $tot_post = 0;
    # bank  % cust
    if ($inv['ctyp'] == 's') {
        $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        $cus = pg_fetch_array($custRslt);
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<li class=err>Department not Found.";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $tpp = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            $tot_post += $wamt;
            writetrans($stkacc, $dept['debtacc'], $td, $refnum, $wamt, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} Customer {$inv['cusname']}.");
        }
        if ($VAT != 0) {
            $tot_post += $VAT;
            writetrans($vatacc, $dept['debtacc'], $td, $refnum, $VAT, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT. Customer {$inv['cusname']}.");
        }
        $tot_dif = sprint($tot_post - $TOTAL);
        if ($tot_dif > 0) {
            writetrans($dept['debtacc'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($varacc, $dept['debtacc'], $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        }
    } elseif ($inv['ctyp'] == 'b') {
        $dept['debtacc'] = getbankaccid($inv['accid']);
        $amounts = "";
        $accids = "";
        $vats = "";
        $chrgvats = "";
        $gamt = 0;
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            # Cook vars
            $amounts .= "|{$wamt}";
            $accids .= "|{$stkacc}";
            $vats .= "|0";
            $chrgvats .= "|no";
            # Debit Customer and Credit stock
            $tot_post += $wamt;
            writetrans($stkacc, $dept['debtacc'], $td, $refnum, $wamt, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid}.");
        }
        # Debit bank and credit the account involved
        if ($VAT != 0) {
            # Cook vars
            $amounts .= "|{$VAT}";
            $accids .= "|{$vatacc}";
            $vats .= "|0";
            $chrgvats .= "|no";
            $tot_post += $VAT;
            writetrans($vatacc, $dept['debtacc'], $td, $refnum, $VAT, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT.");
        }
    } else {
        $cusacc = $inv['accid'];
        $sdate = date("Y-m-d");
        # record transaction  from data
        foreach ($totstkamt as $stkacc => $wamt) {
            # Debit Customer and Credit stock
            $tot_post += $wamt;
            writetrans($stkacc, $cusacc, $td, $refnum, $wamt, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid}.");
            pettyrec($cusacc, $td, "dt", "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid}.", $wamt, "Account Sale Credit note");
        }
        # Debit bank and credit the account involved
        $tot_post += $VAT;
        writetrans($vatacc, $cusacc, $td, $refnum, $VAT, "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT.");
        pettyrec($cusacc, $td, "dt", "Non-Stock invoice No. {$inv['invnum']} Credit note No.{$real_noteid} VAT.", $VAT, "Account Sale Credit note VAT");
        $tot_dif = sprint($tot_post - $TOTAL);
        if ($tot_dif > 0) {
            writetrans($cusacc, $varacc, $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        } elseif ($tot_dif < 0) {
            $tot_dif = $tot_dif * -1;
            writetrans($varacc, $cusacc, $td, $refnum, $tot_dif, "Sales Variance on Credit note No.{$real_noteid}");
        }
    }
    $sdate = date("Y-m-d");
    db_connect();
    if ($inv['ctyp'] == 's') {
        # Record the payment on the statement
        $sql = "\r\n\t\t\tINSERT INTO stmnt \r\n\t\t\t\t(cusnum, invid, amount, date, type, div, allocation_date) \r\n\t\t\tVALUES \r\n\t\t\t\t('{$inv['cusid']}', '{$real_noteid}', '-{$TOTAL}','{$td}', 'Non Stock Credit Note, for invoice {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance less)
        $sql = "UPDATE customers SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE cusnum = '{$inv['cusid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Update the customer (make balance less)
        $sql = "UPDATE open_stmnt SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Make ledge record
        custledger($inv['cusid'], $stkacc, $td, $real_noteid, "Non Stock Credit note {$real_noteid}", $TOTAL, "c");
        #record entry for age analysis ...
        #this function seems a little ... broken
        //custfCT($TOTAL, $inv['cusid'], $inv['age']);
        #lets rather use the system wide function and send it the invoice transaction date to do the entry for that age
        custCT($TOTAL, $inv['cusid'], $inv['odate']);
    } elseif ($inv['ctyp'] == 'cb') {
        $date = date("Y-m-d");
        # Record the Receipt record
        db_connect();
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, banked, accids, amounts,  chrgvats, vats, div,accinv) VALUES ('{$inv['jobid']}', 'withdrawal', '{$td}', '{$inv['cusname']}', 'Nons Stock Credit note for invoice {$inv['invnum']}', '0', '{$TOTAL}', 'no', '', '0', '{$inv['chrgvat']}', '0', '" . USER_DIV . "','{$stkacc}')";
        die($sql);
        $Rslt = db_exec($sql) or errDie("Unable to add bank Receipt to database.", SELF);
    }
    db_connect();
    $sql = "UPDATE hire.hire_nons_invoices SET balance = (balance - '{$TOTAL}'::numeric(13,2)) WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
    # write note
    $sql = "INSERT INTO hire.hire_nons_inv_notes(invid, invnum, cusname, cusaddr, cusvatno, chrgvat, date, subtot, vat, total, username, prd, notenum, ctyp, remarks, div)";
    $sql .= " VALUES('{$inv['invid']}', '{$inv['invnum']}', '{$inv['cusname']}', '{$inv['cusaddr']}', '{$inv['cusvatno']}', '{$inv['chrgvat']}', '{$td}', {$SUBTOT}, {$VAT}, {$TOTAL}, '" . USER_NAME . "', '" . PRD_DB . "', '{$real_noteid}', '{$inv['ctyp']}', '{$remarks}', '" . USER_DIV . "')";
    $rslt = db_exec($sql) or errDie("Unable to create template Non-Stock Invoice.", SELF);
    # write note items
    foreach ($ids as $key => $id) {
        $sql = "SELECT * FROM hire.hire_nons_inv_items  WHERE invid = '{$invid}' AND id = '{$id}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $nstk = pg_fetch_array($stkdRslt);
    }
    $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\r\n\tVALUES('{$td}', '{$noteid}', '{$real_noteid}', '0', '{$VAT}', '{$TOTAL}', 'nnon', '" . USER_DIV . "')";
    $recRslt = db_exec($sql);
    $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\r\n\t('{$inv['cusid']}','{$inv['cusname']}','Credit Note: {$real_noteid}, Invoice {$inv['invnum']}','{$td}','" . -sprint($TOTAL - $VAT) . "','-{$VAT}','" . -sprint($TOTAL) . "','" . USER_DIV . "')";
    $Ri = db_exec($Sl);
    com_invoice($inv['salespn'], -($TOTAL - $VAT), 0, $inv['invnum'], $td);
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    $cc = "<script> CostCenter('ct', 'Credit Note', '{$td}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($TOTAL - $VAT) . "', ''); </script>";
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company information from Cubit.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve the banking information
    db_conn("cubit");
    $sql = "SELECT * FROM bankacct WHERE bankid='2' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank information from Cubit.");
    $bank_data = pg_fetch_array($bank_rslt);
    // Retrieve customer information
    db_conn("cubit");
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
    $cust_data = pg_fetch_array($cust_rslt);
    if ($inv['cusid'] == "0") {
        $cust_data['surname'] = $inv['cusname'];
        $cust_data['addr1'] = $inv['cusaddr'];
        $cust_data['paddr1'] = $inv['cusaddr'];
    }
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;\r\n\t";
    // 	$nolr_borders = "
    // 		border-top: 2px solid #000;
    // 		border-left: none;
    // 		border-right: none;
    // 		border-bottom: none;
    // 	";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $vattot = sprint($vattot);
        $amttot = sprint($amttot);
        $details .= "<center>\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='left' rowspan='2'><img src='compinfo/getimg.php' width=230 height=47></td>\r\n\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Credit Note</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t</tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Credit Note No:</b> {$real_noteid}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$inv['invnum']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Proforma Inv No:</b> {$inv['docref']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='center'><font size='4'><b>Credit Note To:</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cust_data['surname']}</b></td>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "</td>\r\n\t\t\t\t\t<td>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000' align='right'><b>Unit Price</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$products_out}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$remarks}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Terms:</b> {$inv['terms']} days</b></td>\r\n\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$SUBTOT}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$VAT}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t<td nowrap><b>" . CUR . " {$TOTAL}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t<tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\t\t";
    }
    #fix teh date
    $date_arr = explode("-", $date);
    $cdate = "{$date_arr['2']}-{$date_arr['1']}-{$date_arr['0']}";
    // Retrieve template settings from Cubit
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve the template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        $OUTPUT = "\r\n\t\t\t<script>\r\n\t\t\t\tCostCenter('ct', 'Credit Note', '{$cdate}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($TOTAL - $VAT) . "', '');\r\n\t\t\t</script>\r\n\t\t\t{$details}";
        require "tmpl-print.php";
    } else {
        $OUTPUT = "\r\n\t\t\t<script>\r\n\t\t\t\tCostCenter('ct', 'Credit Note', '{$cdate}', 'Non Stock Credit Note No.{$real_noteid}', '" . ($TOTAL - $VAT) . "', '');\r\n\t\t\t\tmove(\"{$template}?noteid={$noteid}&type=nonsnote\");\r\n\t\t\t</script>";
        require "template.php";
    }
}
Exemplo n.º 17
0
function bank($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cashid, "num", 1, 4, "Invalid Reference number.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # 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");
    # If tis customer payment
    if ($accnt['cusnum'] > 0) {
        db_connect();
        # Get invoice Ids and Amounts
        $invids = explode("|", $accnt['rinvids']);
        $amounts = explode("|", $accnt['amounts']);
        $invprds = explode("|", $accnt['invprds']);
        $rages = explode("|", $accnt['rages']);
        # Return the amount that was surppose to be paid to invoices
        foreach ($invids as $key => $invid) {
            db_connect();
            # Skip all nulls and check existance
            if ($invids[$key] > 0 && ext_ex("invoices", "invid", $invids[$key]) && $invprds[$key] != 0) {
                db_connect();
                $sql = "UPDATE invoices SET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
            } elseif ($invids[$key] > 0 && ext_ex("nons_invoices", "invid", $invids[$key]) && $invprds[$key] == 0) {
                db_connect();
                $sql = "UPDATE nons_invoices SET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                custDTA($amounts[$key], $accnt['cusnum'], $rages[$key]);
            } elseif ($invids[$key] > 0) {
                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])) {
                    }
                }
            }
        }
        # Begin updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        db_connect();
        # Update the customer (make balance more)
        $sql = "UPDATE customers SET balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE 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\t(cusnum, invid, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES('{$accnt['cusnum']}', '0', '{$accnt['amount']}','{$sdate}', 'Cheque/Payment for Invoices Cancelled.', '" . USER_DIV . "', '{$accnt['date']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        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 = "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 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);
        }
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        # Make ledge record
        custledger($accnt['cusnum'], $bank['accnum'], $sdate, "cancel", "Payment for Invoices Cancelled.", $accnt['amount'], "d");
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = date("Y-m-d");
        # debit customer account, credit bank account (customer takes money back)
        writetrans($accnt['accinv'], $bank['accnum'], $date, $refnum, $accnt['amount'], $descript);
    } elseif ($accnt['supid'] > 0) {
        db_connect();
        # Begin updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        $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']}', '{$sdate}', '{$bank['accnum']}', '{$accnt['cheqnum']}', 'Cheque/Payment to Supplier Cancelled.', '{$accnt['amount']}', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        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);
        }
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        suppledger($accnt['supid'], $bank['accnum'], $sdate, $accnt['cheqnum'], "Payment to Supplier Cancelled", $accnt['amount'], "c");
        db_connect();
        $descript = $accnt['descript'] . " Cancelled";
        $refnum = getrefnum();
        $date = date("Y-m-d");
        # debit bank, credit supplier account
        writetrans($bank['accnum'], $accnt['accinv'], $date, $refnum, $accnt['amount'], $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']);
        db_connect();
        # Delete cashbook ID
        $sql = "DELETE FROM cashbook WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        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'] . " Cancelled";
        $refnum = getrefnum();
        $date = date("Y-m-d");
        # debit bank, credit supplier account
        writetrans($bank['accnum'], $accnt['accinv'], $date, $refnum, $accnt['amount'], $descript);
    } elseif (strlen($accnt['accids']) > 0) {
        /* -- Start Hooks -- */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
        /* -- End Hooks -- */
        multican($accnt, $bank, $vatacc);
    } 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 = "DELETE FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        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'] . " Cancelled";
        $refnum = getrefnum();
        $date = date("Y-m-d");
        if ($accnt['trantype'] == "deposit") {
            # DT(account involved), CT(bank)
            writetrans($accnt['accinv'], $bank['accnum'], $date, $refnum, $amount, $descript);
            if ($vat != 0) {
                # DT(Vat), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $date, $refnum, $vat, $descript);
            }
            $cc_trantype = cc_TranTypeAcc($accnt['accinv'], $bank['accnum']);
        } else {
            # DT(bank), CT(account invoilved)
            writetrans($bank['accnum'], $accnt['accinv'], $date, $refnum, $amount, $descript);
            if ($vat != 0) {
                # DT(Vat), CT(Bank)
                writetrans($bank['accnum'], $vatacc, $date, $refnum, $vat, $descript);
            }
            $cc_trantype = cc_TranTypeAcc($bank['accnum'], $accnt['accinv']);
        }
    }
    if (isset($cc_trantype) && $cc_trantype != false) {
        $cc = "<script> CostCenter('{$cc_trantype}', 'Cancelled Bank Transaction', '{$date}', '{$descript}', '" . ($accnt['amount'] - $accnt['vat']) . "', '../'); </script>";
    } else {
        $cc = "";
    }
    # Status report
    $bank = "\n\t\t\t\t{$cc}\n\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Cash Book</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t<td>Cash Book Entry was successfully canceled .</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    # Main table (layout with menu)
    $OUTPUT = "\n\t\t\t\t<center>\n\t\t\t\t<table width='90%'>\n\t\t\t\t\t<tr valign='top'>\n\t\t\t\t\t\t<td width='60%'>{$bank}</td>\n\t\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th>Quick Navigation</th>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr class='datacell'>\n\t\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\t</tr>\n\t\t\t\t\t\t\t\t<tr class='datacell'>\n\t\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\t</tr>\n\t\t\t\t\t\t\t\t<tr class='datacell'>\n\t\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\t</tr>\n\t\t\t\t\t\t\t\t<tr class='datacell'>\n\t\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\t</tr>\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    //processes
    db_connect();
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusname, "string", 1, 50, "Invalid Customer name.");
    $v->isOk($addr1, "string", 1, 255, "Invalid customer address(Line 1).");
    $v->isOk($addr2, "string", 0, 255, "Invalid customer address(Line 2).");
    $v->isOk($addr3, "string", 0, 255, "Invalid customer address(Line 3).");
    $v->isOk($paddr1, "string", 0, 255, "Invalid customer postal address(Line 1).");
    $v->isOk($paddr2, "string", 0, 255, "Invalid customer postal address(Line 2).");
    $v->isOk($paddr3, "string", 0, 255, "Invalid customer postal address(Line 3).");
    $v->isOk($tel, "num", 1, 14, "Invalid telephone number.");
    $v->isOk($fax, "num", 0, 14, "Invalid fax number.");
    $v->isOk($email, "email", 0, 255, "Invalid E-mail address.");
    $v->isOk($orddate, "date", 1, 14, "Invalid order Date.");
    $v->isOk($invdate, "date", 1, 14, "Invalid invoice Date.");
    $v->isOk($stockacc, "num", 1, 255, "Invalid stock account.");
    $v->isOk($accpaid, "num", 1, 255, "Invalid account paid to.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # caclulate sub totals
    $SUBTOT = 0;
    //total of subtotals
    $COSTOT = 0;
    // Cost of stock sold
    foreach ($qty as $key => $value) {
        $SUB[$key] = sprintf("%01.2f", $qty[$key] * $unitcost[$key]);
        $COST[$key] = sprintf("%01.2f", $qty[$key] * $cost[$key]);
        $COSTOT += $COST[$key];
        $SUBTOT += $SUB[$key];
    }
    #calculate vat and grand total
    $vat = sprintf("%01.2f", TAX_VAT / 100);
    $VAT = sprintf("%01.2f", $vat * $SUBTOT);
    $GRDTOT = sprintf("%01.2f", $SUBTOT + $VAT);
    # Join each item into a string and put them into an array
    foreach ($qty as $key => $value) {
        $items[$key] = "{$descript[$key]} [|] {$qty[$key]} [|] {$unitcost[$key]} [|] {$SUB[$key]}";
    }
    # Implode items into one order
    $orddes = implode("\n", $items);
    # write customer to DB
    db_connect();
    $sql = "INSERT INTO customers(cusname, addr1, addr2, addr3, paddr1, paddr2, paddr3, tel, fax, email) ";
    $sql .= "VALUES('{$cusname}', '{$addr1}', '{$addr2}', '{$addr3}',  '{$paddr1}', '{$paddr2}', '{$paddr3}', '{$tel}', '{$fax}', '{$email}')";
    $rslt = db_exec($sql) or errDie("Unable to insert customer to Cubit.", SELF);
    # write invoice to DB
    db_connect();
    $sql = "INSERT INTO invoices(cusname, addr1, addr2, addr3, tel, fax, email, orddate, invdate, orddes, grdtot, salesrep, accpaid) ";
    $sql .= "VALUES('{$cusname}', '{$addr1}', '{$addr2}', '{$addr3}', '{$tel}', '{$fax}', '{$email}', '{$orddate}', '{$invdate}', '{$orddes}', '{$GRDTOT}', '" . USER_NAME . "', '{$accpaid}')";
    $rslt = db_exec($sql) or errDie("Unable to insert invoice to Cubit.", SELF);
    # get next ordnum
    $ordnum = pglib_lastid("invoices", "ordnum");
    # get cost of sales account
    $cosacc = gethook("accnum", "salesacc", "name", "Cost Of Sales");
    # get income account
    $incomeacc = gethook("accnum", "salesacc", "name", "Income");
    $refnum = getrefnum($invdate);
    # credit income debit acc paid
    writetrans($accpaid, $incomeacc, $invdate, $refnum, $GRDTOT, "Sales Income received.");
    # credit income debit acc paid
    # writetrans( $accpaid, $incomeacc, $GRDTOT, "income received.");
    # credit stock acc and cos acc
    writetrans($cosacc, $stockacc, $invdate, $refnum, $COSTOT, "Cost of Sales.");
    # credit stock acc and cos acc
    # writetrans( $cosacc, $stockacc, $COSTOT, "income received.");
    // invoice design
    $printInv = "<center><table border=0 cellpadding=5 cellspacing=0 width='91%'>\r\n        <tr><td width='35%' align=center>\r\n\t        <img src='" . COMP_LOGO . "' width=230 height=47 alt='" . COMP_NAME . "'>\r\n        </td><td align=right>\r\n\t        " . COMP_ADDRESS . "\r\n\t        <br>Tel : " . COMP_TEL . "\r\n\t        <br>Fax : " . COMP_FAX . "\r\n        </td><tr>\r\n        <tr><td width='35%' valign=top>\r\n\t        <table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='100%' border=1>\r\n\t        <tr><th class=h4>CUSTOMER ADDRESS</th></tr>\r\n\t        <tr><td align=center>\r\n        \t\t<table border=0 cellpadding=10 cellspacing=0>\r\n\t\t        <tr><td>\r\n\t\t\t        <b>{$cusname}</b>\r\n\t\t\t        <p>{$addr1}<br>{$addr2}<br>{$addr3}\r\n                                <p>{$tel}<br>{$fax}<br>{$email}<br>\r\n\t\t        </td></tr>\r\n\t\t        </table>\r\n\t        </td></tr>\r\n\t        </table>\r\n        </td><td>\r\n        \t<!-- commeted out\r\n                <table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='100%' border=1>\r\n        \t<tr><th class=h4>DELIVERY ADDRESS</th></tr>\r\n        \t<tr><td align=center>\r\n\t\t        <table border=0 cellpadding=10 cellspacing=0>\r\n\t\t        <tr><td>\r\n        \t\t\t<b>-Customer name-</b>\r\n\t\t                <p>-Customer's Delivery Address-\r\n\t\t        </td></tr>\r\n\t\t</table>\r\n\t        </td></tr>\r\n\t        </table>\r\n                /commente out -->\r\n\r\n        </td></tr>\r\n        <tr><td colspan=2>\r\n        \t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='100%' border=1>\r\n        \t<tr><th>INVOICE No.</th><th>SALESPERSON</th><th>ORDER DATE</th><th>INVOICE DATE</th></tr>\r\n        \t<tr><td align=center>{$ordnum}</td><td align=center>" . USER_NAME . "</td><td align=center>{$orddate}</td><td align=center>{$invdate}</td></tr>\r\n        \t</table>\r\n        </td></tr>\r\n        </table>\r\n        <br>\r\n        <table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='90%' border=1>\r\n        <tr><th>CODE</th><th>DESCRIPTION</th><th>QTY</th><th>UNIT COST</th><th width=20%>SUBTOTAL</th></tr>";
    foreach ($qty as $key => $value) {
        $printInv .= "<tr><td>0000{$key}</td><td>" . stripslashes($descript[$key]) . "</td><td>{$qty[$key]}</td><td>{$unitcost[$key]}</td><td align=right>" . CUR . " {$SUB[$key]}</td></tr>";
    }
    $printInv .= "<tr><td colspan=4 align=right><b>SUBtotal</b></td><td align=right>{$SUBTOT}</td></tr>\r\n        <tr><td colspan=4 align=right><b>VAT @ " . TAX_VAT . "%</b></td><td align=right>{$VAT}</td></tr>\r\n        <tr><td colspan=4 align=right><b>GRAND total</b></td><td align=right><b>{$GRDTOT}</b></td></tr>\r\n        </table></center>\r\n        <blockquote> <table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=1>\r\n        <tr><th>VAT No.</th><td align=center>" . COMP_VATNO . "</td></tr>\r\n        </table>";
    $OUTPUT = $printInv;
    #  Print the invoice and exit
    require "tmpl-print.php";
}
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 details($_GET)
{
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid = '{$invid}'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found[1]</i>";
    }
    $inv = pg_fetch_array($invRslt);
    // Cash deposit
    if ($inv["deposit_type"] == "CSH" && $inv["deposit_amt"] > 0) {
        $get_ar = array();
        foreach ($_GET as $key => $value) {
            if ($key != "key") {
                $get_ar[] = "{$key}={$value}";
            }
        }
        $get_vars = implode("&", $get_ar);
        $deposit_receipt = "<script>\r\n\t\t\t\t\t\t\t\tprinter(\"" . SELF . "?key=deposit{$get_vars}\")\r\n\t\t\t\t\t\t\t</script>";
    } else {
        $deposit_receipt = "";
    }
    if ($inv['rounding'] > 0) {
        db_conn('core');
        $Sl = "SELECT * FROM salesacc WHERE name='rounding'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set the rounding account, under sales settings.";
        }
        $ad = pg_fetch_array($Ri);
        $rac = $ad['accnum'];
    }
    if ($inv['cusnum'] != "0") {
        #then get the actual customer
        db_connect();
        $get_cus = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' LIMIT 1";
        $run_cus = db_exec($get_cus) or errDie("Unable to get customer information");
        if (pg_numrows($run_cus) < 1) {
            #do nothing
        } else {
            $carr = pg_fetch_array($run_cus);
            $inv['cusname'] = "{$carr['cusname']}";
            $inv['surname'] = "{$carr['surname']}";
        }
    }
    $td = $inv['odate'];
    db_conn('cubit');
    $sql = "SELECT asset_id FROM hire.hire_invitems WHERE invid = '{$inv['invid']}'";
    $crslt = db_exec($sql);
    if ($inv['terms'] == 1) {
        db_conn('core');
        $Sl = "SELECT * FROM salacc WHERE name='cc'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please set a link for the POS credit card control account";
        }
        $cd = pg_fetch_array($Ri);
        $cc = $cd['accnum'];
    }
    $change = sprint(sprint($inv['pcash'] + $inv['pcheque'] + $inv['pcc'] + $inv['pcredit']) - sprint($inv['total'] - $inv['rounding']));
    $inv['pcash'] = sprint($inv['pcash'] - $change);
    if ($inv['pcash'] < 0) {
        $inv['pcash'] = 0;
    }
    if (sprint($inv['pcash'] + $inv['pcheque'] + $inv['pcc'] + $inv['pcredit']) != sprint($inv['total'] - $inv['rounding'])) {
        return "<li class=err>The total of all the payments is not equal to the invoice total.<br>\r\n\t\tPlease edit the invoice and try again(You can only overpay with cash)</li>";
    }
    db_connect();
    pglib_transaction("BEGIN");
    $invnum = getHirenum($invid, 1);
    $sql = "UPDATE hire.reprint_invoices SET invnum='{$invnum}' WHERE invid='{$invid}'";
    db_exec($sql) or errDie("Unable to assign hire invoice number.");
    $Sl = "INSERT INTO ncsrec (oldnum,newnum, div) VALUES ('{$invid}','{$invnum}', '" . USER_DIV . "')";
    $Rs = db_exec($Sl) or errDie("Unable to insert into db");
    //unlock(2);
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class=err>Not Found[2]</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM hire.hire_invitems  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $taxex = 0;
    $commision = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] == 0) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM assets WHERE id = '{$stkd['asset_id']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            db_connect();
            //this was set to the stock vatcode ??? must be the pur_item code ...
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "<li class='err'>Please select the vatcode for all your stock.</li>";
            }
            $vd = pg_fetch_array($Ri);
            $sp = "&nbsp;&nbsp;&nbsp;&nbsp;";
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "&nbsp;&nbsp;";
            }
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            # Insert stock record
            $sdate = date("Y-m-d");
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            # put in product
            $products .= "<tr valign=top>\r\n\t\t\t\t<td>{$stk['stkcod']}</td>\r\n\t\t\t\t<td>{$ex} {$sp} {$stk['stkdes']}</td>\r\n\t\t\t\t<td>{$stkd['qty']}</td>\r\n\t\t\t\t<td>" . sprint($stk["selamt"]) . "</td>\r\n\t\t\t\t<td>" . CUR . sprint($stkd["amt"]) . "</td>\r\n\t\t\t</tr>";
            # Get amount exluding vat if including and not exempted
            $VATP = TAX_VAT;
            $amtexvat = sprint($stkd['amt']);
            if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes') {
                $amtexvat = sprint($stkd['amt'] * 100 / (100 + $VATP));
            }
            $commision = $commision + coms($inv['salespn'], $stkd['amt'], $stk['com']);
        } else {
            db_conn('core');
            $Sl = "SELECT * FROM accounts WHERE accid='{$stkd['account']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get account data.");
            $ad = pg_fetch_array($Ri);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            $sp = "";
            # Check Tax Excempt
            if ($vd['zero'] == "Yes") {
                $taxex += $stkd['amt'];
                $ex = "#";
            } else {
                $ex = "";
            }
            # all must be excempted
            if ($inv['chrgvat'] == 'nov') {
                $ex = "#";
            }
            //$commision=$commision+coms($inv['salespn'], $stkd['amt'], $stk['com']);
            # Put in product
            $products .= "<tr valign=top>\r\n\t\t\t\t<td></td>\r\n\t\t\t\t<td>{$ex} {$sp} {$stkd['description']}</td>\r\n\t\t\t\t<td>{$stkd['qty']}</td>\r\n\t\t\t\t<td>" . sprint($stkd["unitcost"]) . "</td>\r\n\t\t\t\t<td>{$stkd['disc']}</td>\r\n\t\t\t\t<td>" . CUR . sprint($stkd["amt"]) . "</td>\r\n\t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOTAL = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $av = $VAT;
    $at = $TOTAL - $VAT;
    $nt = sprint($inv['pcredit']);
    $sd = date("Y-m-d");
    $ro = $inv['rounding'];
    $ro += 0;
    com_invoice($inv['salespn'], $TOTAL - $VAT, $commision, $invnum);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "novat");
    /* - End Hooks - */
    $nsp = 0;
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    db_conn('cubit');
    if ($inv['cusnum'] > 0 && $nt > 0) {
        # Record the payment on the statement
        $sql = "INSERT INTO stmnt(cusnum, invid, docref, amount, date, type, div) VALUES('{$inv['cusnum']}', '{$invnum}', '0', '{$nt}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Record the payment on the statement
        $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('{$inv['cusnum']}', '{$invnum}', '0', '{$nt}', '{$nt}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "')";
        $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 + '{$nt}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        custledger($inv['cusnum'], $dept['incacc'], $inv['odate'], $invnum, "Invoice No. {$invnum}", $nt, "d");
        recordDT($nt, $inv['cusnum'], $inv['odate']);
        db_conn('cubit');
        $Sl = "INSERT INTO payrec(date,by,inv,amount,method,prd,note) VALUES ('{$sd}','" . USER_NAME . "','{$invnum}','{$nt}','Credit','" . PRD_DB . "','0')";
        $Ri = db_exec($Sl) or errDie("Unable to insert data.");
    }
    db_conn('cubit');
    if ($inv['terms'] == 1) {
        $Sl = "INSERT INTO crec(userid,username,amount,pdate,inv) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}')";
        $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    } else {
        $Sl = "INSERT INTO posrec(userid,username,amount,pdate,inv) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}')";
        $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    }
    $Sl = "INSERT INTO pr(userid,username,amount,pdate,inv,cust,t) VALUES ('" . USER_ID . "','" . USER_NAME . "','{$TOTAL}','{$td}','{$invnum}','{$inv['cusname']}','{$inv['terms']}')";
    $Ry = db_exec($Sl) or errDie("Unable to insert pos record.");
    $refnum = getrefnum();
    $fcash = $inv['pcash'];
    $fccp = $inv['pcc'];
    $fcheque = $inv['pcheque'];
    $fcredit = $inv['pcredit'];
    /* --- Updates ---- */
    db_connect();
    $Sql = "UPDATE hire.hire_invoices SET pchange='{$change}',printed = 'y', done ='y',invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
    # save invoice discount
    $sql = "INSERT INTO inv_discs(cusnum, invid, traddisc, itemdisc, inv_date, delchrg, div,total) VALUES('0','{$invnum}','{$inv['delivery']}','{$disc}', '{$inv['odate']}', '{$inv['delivery']}', '" . USER_DIV . "',({$SUBTOT}+{$inv['delivery']}))";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    # get selected stock in this invoice
    $sql = "SELECT * FROM hire.hire_invitems  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $tcosamt = 0;
    if (strlen($inv['comm']) > 0) {
        $Com = "<table><tr><td>" . nl2br($inv['comm']) . "</td></tr></table>";
    } else {
        $Com = "";
    }
    $cc = "<script> sCostCenter('dt', 'Sales', '{$date}', 'POS Invoice No.{$invnum}', '" . ($TOTAL - $VAT) . "', 'Cost Of Sales for Invoice No.{$invnum}', '{$tcosamt}', ''); </script>";
    if ($inv['chrgvat'] == "inc") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "exc") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    /* - End Transactoins - */
    /* -- Final Layout -- */
    $details = "<center>\r\n\t{$deposit_receipt} {$cc}\r\n\t<h2>Tax Invoice</h2>\r\n\t<table cellpadding='0' cellspacing='1' border=0 width=750>\r\n\t<tr><td valign=top width=40%>\r\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0>\r\n\t\t\t<tr><td>{$inv['surname']}</td></tr>\r\n\t\t</table>\r\n\t</td><td valign=top width=35%>\r\n\t\t" . COMP_NAME . "<br>\r\n\t\t" . COMP_ADDRESS . "<br>\r\n\t\t" . COMP_TEL . "<br>\r\n\t\t" . COMP_FAX . "<br>\r\n\t\tReg No. " . COMP_REGNO . "<br>\r\n\t</td><td valign=bottom align=right width=25%>\r\n\t\t<table cellpadding='2' cellspacing='0' border=1 bordercolor='#000000'>\r\n\t\t\t<tr><td><b>Hire No.</b></td><td valign=center>H" . getHirenum($inv["invid"], 1) . "</td></tr>\r\n\t\t\t<tr><td><b>Order No.</b></td><td valign=center>{$inv['ordno']}</td></tr>\r\n\t\t\t<tr><td><b>Terms</b></td><td valign=center>Cash</td></tr>\r\n\t\t\t<tr><td><b>Invoice Date</b></td><td valign=center>{$inv['odate']}</td></tr>\r\n\t\t\t<tr><td><b>VAT</b></td><td valign=center>{$inv['chrgvat']}</td></tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td><br></td></tr>\r\n\t<tr><td colspan=3>\r\n\t<table cellpadding='5' cellspacing='0' border=1 width=100% bordercolor='#000000'>\r\n\t\t<tr><th>ITEM NUMBER</th><th width=45%>DESCRIPTION</th><th>QTY</th><th>UNIT PRICE</th><th>AMOUNT</th><tr>\r\n\t\t{$products}\r\n\t</table>\r\n\t</td></tr>\r\n\t<tr><td>\r\n\t\t{$inv['custom_txt']}\r\n\t\t{$Com}\r\n\t</td><td align=right colspan=2>\r\n\t\t<table cellpadding='5' cellspacing='0' border=1 width=50% bordercolor='#000000'>\r\n\t\t\t<tr><td><b>SUBTOTAL</b></td><td align=right>" . CUR . " {$SUBTOT}</td></tr>\r\n\t\t\t<tr><td><b>Trade Discount</b></td><td align=right>" . CUR . " {$inv['discount']}</td></tr>\r\n\t\t\t<tr><td><b>Delivery Charge</b></td><td align=right>" . CUR . " {$inv['delivery']}</td></tr>\r\n\t\t\t<tr><td><b>VAT @ {$VATP}%</b></td><td align=right>" . CUR . " {$VAT}</td></tr>\r\n\t\t\t<tr><th><b>GRAND TOTAL<b></th><td align=right>" . CUR . " {$TOTAL}</td></tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td><br></td></tr>\r\n\t<tr><td>\r\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=1>\r\n\t\t\t<tr><td colspan=2>VAT Exempt indicator = #</td></tr>\r\n\t\t\t<tr><th>VAT No.</th><td align=center>" . COMP_VATNO . "</td></tr>\r\n        </table>\r\n\t</td><td><br></td></tr>\r\n\t</table></center>";
    /* Start moving invoices */
    db_connect();
    # Move invoices that are fully paid
    $sql = "SELECT * FROM hire.hire_invoices WHERE invid='{$invid}'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    $time2 = time();
    while ($invb = pg_fetch_array($invbRslt)) {
        $invb['invnum'] += 0;
        # Insert invoice to period DB
        $sql = "INSERT INTO hire.hire_invoices(invid,invnum, deptid, cusnum, deptname, cusacc, cusname, surname, cusaddr, cusvatno, cordno, ordno, chrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, balance, comm, printed, done, div, username,rounding,delvat,vatnum,pcash,pcheque,pcc,pcredit)";
        $sql .= " VALUES('{$invb['invid']}','{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', '{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', 'y', 'y', '" . USER_DIV . "','" . USER_NAME . "','{$invb['rounding']}','{$invb['delvat']}','{$invb['vatnum']}','{$invb['pcash']}','{$invb['pcheque']}','{$invb['pcc']}','{$invb['pcredit']}')";
        //$rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.",SELF);
        $sql = "SELECT * FROM hire.monthly_invoices WHERE invid='{$invb['invid']}'";
        $hi_rslt = db_exec($sql) or errDie("Unable to retrieve hire invoice.");
        if (pg_num_rows($hi_rslt)) {
            $sql = "UPDATE hire.monthly_invoices SET invnum='{$invb['invnum']}',\r\n\t\t\t\t\t\tdeptid='{$invb['deptid']}', cusnum='{$invb['cusnum']}',\r\n\t\t\t\t\t\tdeptname='{$invb['deptname']}', cusacc='{$invb['cusacc']}',\r\n\t\t\t\t\t\tcusname='{$invb['cusname']}', surname='{$invb['surname']}',\r\n\t\t\t\t\t\tcusaddr='{$invb['cusaddr']}', cusvatno='{$invb['cusvatno']}',\r\n\t\t\t\t\t\tcordno='{$invb['cordno']}', ordno='{$invb['ordno']}',\r\n\t\t\t\t\t\tchrgvat='{$invb['chrgvat']}', terms='{$invb['terms']}',\r\n\t\t\t\t\t\ttraddisc='{$invb['traddisc']}', salespn='{$invb['salespn']}',\r\n\t\t\t\t\t\todate='{$invb['odate']}', delchrg='{$invb['delchrg']}',\r\n\t\t\t\t\t\tsubtot='{$invb['subtot']}', vat='{$invb['vat']}',\r\n\t\t\t\t\t\ttotal='{$invb['total']}', balance='{$invb['balance']}',\r\n\t\t\t\t\t\tcomm='{$invb['comm']}', printed='{$invb['printed']}',\r\n\t\t\t\t\t\tdone='{$invb['done']}', div='{$invb['div']}',\r\n\t\t\t\t\t\tusername='******'username']}', rounding='{$invb['rounding']}',\r\n\t\t\t\t\t\tdelvat='{$invb['delvat']}', vatnum='{$invb['vatnum']}',\r\n\t\t\t\t\t\tpcash='{$invb['pcash']}', pcheque='{$invb['pcheque']}',\r\n\t\t\t\t\t\tpcc='{$invb['pcc']}', pcredit='{$invb['pcredit']}'\r\n\t\t\t\t\tWHERE invid='{$invb['invid']}'";
            db_exec($sql) or errDie("Unable to store monthly invoice.");
            $mi_invid = $invb["invid"];
        } else {
            $sql = "INSERT INTO hire.monthly_invoices(invid, invnum, deptid, cusnum, deptname, cusacc, cusname, surname, cusaddr, cusvatno, cordno, ordno, chrgvat, terms, traddisc, salespn, odate, delchrg, subtot, vat, total, balance, comm, printed, done, div, username,rounding,delvat,vatnum,pcash,pcheque,pcc,pcredit, invoiced_month)";
            $sql .= " VALUES('{$invb['invid']}', '{$invb['invnum']}', '{$invb['deptid']}', '{$invb['cusnum']}', '{$invb['deptname']}', '{$invb['cusacc']}', '{$invb['cusname']}', '{$invb['surname']}', '{$invb['cusaddr']}', '{$invb['cusvatno']}', '{$invb['cordno']}', '{$invb['ordno']}', '{$invb['chrgvat']}', '{$invb['terms']}', '{$invb['traddisc']}', '{$invb['salespn']}', '{$invb['odate']}', '{$invb['delchrg']}', '{$invb['subtot']}', '{$invb['vat']}' , '{$invb['total']}', '{$invb['balance']}', '{$invb['comm']}', 'y', 'y', '" . USER_DIV . "','" . USER_NAME . "','{$invb['rounding']}','{$invb['delvat']}','{$invb['vatnum']}','{$invb['pcash']}','{$invb['pcheque']}','{$invb['pcc']}','{$invb['pcredit']}', '" . date("m") . "')";
            db_exec($sql) or errDie("Unable to store monthly invoice.");
            db_conn("hire");
            $mi_invid = pglib_lastid("monthly_invoices", "invid");
        }
        $sql = "SELECT * FROM hire.hire_invitems WHERE invid='{$invb['invid']}'";
        $invi_rslt = db_exec($sql) or errDie("Unable to retrieve note items.");
        // 		while ($invi = pg_fetch_array($invi_rslt)) {
        // 			if (isset($monthly) && $monthly) {
        // 				$sql = "DELETE FROM hire.monthly_invitems WHERE invid='$mi_invid'";
        // 				db_exec($sql) or errDie("Unable to remove items.");
        //
        // 				$sql = "INSERT INTO hire.monthly_invitems (invid, asset_id, qty,
        // 							unitcost, amt, disc, discp, serno, div, vatcode, account,
        // 							description, basis, from_date, to_date, hours, weeks,
        // 							collection)
        // 						VALUES ('$mi_invid', '$invi[asset_id]',
        // 							'$invi[qty]', '$invi[unitcost]', '$invi[amt]',
        // 							'$invi[disc]', '$invi[discp]',	'$invi[serno]',
        // 							'".USER_DIV."',	'$invi[vatcode]', '$invi[account]',
        // 							'$invi[description]', '$invi[basis]', '$invi[from_date]',
        // 							'$invi[to_date]', '$invi[hours]', '$invi[weeks]',
        // 							'$invi[collection]')";
        // 				db_exec($sql) or errDie("Unable to create montly item.");
        // 			}
        // 		}
        db_connect();
        $sql = "INSERT INTO movinv(invtype, invnum, prd, docref, div) VALUES('pos', '{$invb['invnum']}', '{$invb['prd']}', '', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert invoice to the period database.", SELF);
        # get selected stock in this invoice
        db_connect();
        $sql = "SELECT * FROM hire.hire_invitems WHERE invid = '{$invb['invid']}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        while ($stkd = pg_fetch_array($stkdRslt)) {
            # insert invoice items
            $stkd['vatcode'] += 0;
            $stkd['account'] += 0;
            $sql = "INSERT INTO hire.hire_invitems(invid, whid, asset_id, qty,\r\n\t\t\t\t\t\tunitcost, amt, disc, discp, serno, div, vatcode, account,\r\n\t\t\t\t\t\tdescription)\r\n\t\t\t\t\tVALUES ('{$invb['invid']}', '{$stkd['whid']}',\r\n\t\t\t\t\t\t'{$stkd['asset_id']}', '{$stkd['qty']}', '{$stkd['unitcost']}',\r\n\t\t\t\t\t\t'{$stkd['amt']}', '{$stkd['disc']}', '{$stkd['discp']}',\r\n\t\t\t\t\t\t'{$stkd['serno']}', '" . USER_DIV . "', '{$stkd['vatcode']}',\r\n\t\t\t\t\t\t'{$stkd['account']}', '{$stkd['description']}')";
            $sql = "INSERT INTO hire.monthly_items (invid, whid, asset_id, qty,\r\n\t\t\t\t\t\tunitcost, amt, disc, discp, serno, div, vatcode, account,\r\n\t\t\t\t\t\tdescription)\r\n\t\t\t\t\tVALUES ('{$invb['invid']}', '{$stkd['whid']}', '{$stkd['asset_id']}',\r\n\t\t\t\t\t\t'{$stkd['qty']}', '{$stkd['unitcost']}', '{$stkd['amt']}',\r\n\t\t\t\t\t\t'{$stkd['disc']}', '{$stkd['discp']}',\t'{$stkd['serno']}',\r\n\t\t\t\t\t\t'" . USER_DIV . "',\t'{$stkd['vatcode']}', '{$stkd['account']}',\r\n\t\t\t\t\t\t '{$stkd['desciption']}')";
            $rslt = db_exec($sql) or errDie("Unable to insert invoice items to Cubit.", SELF);
        }
    }
    // Update assets
    $sql = "SELECT * FROM hire.hire_invitems WHERE invid='{$inv['invid']}'";
    $item_rslt = db_exec($sql) or errDie("Unable to update items.");
    while ($item_data = pg_fetch_array($item_rslt)) {
        if (!isSerialized($item_data["asset_id"])) {
            $sql = "SELECT serial2 FROM cubit.assets\r\n\t\t\t\t\t\tWHERE id='{$item_data['asset_id']}'";
            $qty_rslt = db_exec($sql) or errDie("Unable to retrieve qty.");
            $qty = pg_fetch_result($qty_rslt, 0);
            $qty = $qty - $item_data["qty"];
            $sql = "UPDATE cubit.assets SET serial2='{$qty}'\r\n\t\t\t\t\t\tWHERE id='{$item_data['asset_id']}'";
            db_exec($sql) or errDie("Unable to update assets.");
            $sql = "SELECT id, units FROM hire.bookings\r\n\t\t\t\t\t\tWHERE cust_id='{$inv['cusnum']}' AND\r\n\t\t\t\t\t\t\tasset_id='{$item_data['asset_id']}'";
            $bk_rslt = db_exec($sql) or errDie("Unable to retrieve booking.");
            $bk_data = pg_fetch_array($bk_rslt);
            // Update booking information.
            if (!empty($bk_data["id"])) {
                if ($bk_data["units"] - $item_data["qty"] <= 0) {
                    $sql = "DELETE FROM hire.bookings WHERE id='{$bk_data['id']}'";
                } else {
                    $new_qty = $bk_data["units"] - $item_data["qty"];
                    $sql = "UPDATE hire.bookings SET units=(units-'{$new_qty}')\r\n\t\t\t\t\t\t\t\tWHERE id='{$bk_data['id']}'";
                }
                db_exec($sql) or errDie("Unable to update bookings.");
            }
            $item_qty = $item_data["qty"];
        } else {
            $sql = "DELETE FROM hire.bookings WHERE cust_id='{$inv['cusnum']}'\r\n\t\t\t\t\t\tAND asset_id='{$item_data['asset_id']}'";
            db_exec($sql) or errDie("Unable to remove booking.");
            $item_qty = 1;
        }
        $discount = $item_data["amt"] / 100 * $inv["traddisc"];
        $sql = "INSERT INTO hire.assets_hired (invid, asset_id, hired_time, qty,\r\n\t\t\t\t\t item_id, cust_id, invnum, basis, value, discount, weekends)\r\n\t\t\t\tVALUES ('{$invid}', '{$item_data['asset_id']}', CURRENT_TIMESTAMP,\r\n\t\t\t\t\t'{$item_qty}', '{$item_data['id']}', '{$inv['cusnum']}',\r\n\t\t\t\t\t'{$inv['invnum']}', '{$item_data['basis']}', '{$item_data['amt']}',\r\n\t\t\t\t\t'{$discount}', '{$item_data['weekends']}')";
        db_exec($sql) or errDie("Unable to hire out item.");
    }
    # Commit updates
    pglib_transaction("COMMIT");
    header("Location: hire-slip.php?invid={$inv['invid']}&prd={$inv['prd']}&cccc=yes");
    exit;
}
function write($_POST)
{
    # Set max execution time to 12 hours
    ini_set("max_execution_time", 43200);
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($invids as $key => $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid recuring invoice number.");
    }
    $VATP = TAX_VAT;
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return $err;
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $i = 0;
    foreach ($invids as $key => $invid) {
        db_connect();
        $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "' and done='n'";
        $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
        if (pg_numrows($invRslt) < 1) {
            return "<i class=err>Not Found</i>";
        }
        $inv = pg_fetch_array($invRslt);
        $ctyp = $inv['ctyp'];
        //$td=$inv['sdate'];
        $td = $inv['odate'];
        //$cus['surname']=$inv['cusname'];
        if ($ctyp == 's') {
            $cusnum = $inv['tval'];
            $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to view customer");
            $cus = pg_fetch_array($custRslt);
            $na = $cus['surname'];
        } elseif ($ctyp == 'c') {
            $deptid = $inv['tval'];
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
            $deptRslt = db_exec($sql) or errDie("Unable to view customers");
            $dept = pg_fetch_array($deptRslt);
            $na = $inv['cusname'];
        }
        db_connect();
        $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql) or errDie("Unable to get data.");
        unset($totstkamt);
        $refnum = getrefnum();
        /*refnum*/
        /* - Start Hooks - */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "NO VAT");
        $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
        /* - End Hooks - */
        db_conn("cubit");
        $real_invid = divlastid('inv', USER_DIV);
        db_conn("cubit");
        # Put in product
        $totstkamt = array();
        while ($stk = pg_fetch_array($stkdRslt)) {
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatex']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            if ($vd['zero'] == "Yes") {
                $stk['vatex'] = "y";
            }
            $t = $inv['chrgvat'];
            $stkacc = $stk['accid'];
            if (isset($totstkamt[$stkacc])) {
                if ($stk['vatex'] == "y") {
                    $totstkamt[$stkacc] += vats($stk['amt'], 'novat', $vd['vat_amount']);
                    $va = 0;
                    $inv['chrgvat'] = "";
                } else {
                    $totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                    $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                    if ($inv['chrgvat'] == "no") {
                        $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                    }
                }
            } else {
                if ($stk['vatex'] == "y") {
                    $totstkamt[$stkacc] = vats($stk['amt'], 'novat', $vd['vat_amount']);
                    $inv['chrgvat'] = "";
                    $va = 0;
                } else {
                    $totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                    $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                    if ($inv['chrgvat'] == "no") {
                        $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                    }
                }
            }
            vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock Sales, invoice No.{$real_invid}", vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']) + $va, $va);
            //print vats($stk['amt'],$inv['chrgvat'], $vd['vat_amount']);
            $inv['chrgvat'] = $t;
            //$sql = "UPDATE nons_inv_items SET accid = '$stk[account]' WHERE id = '$stk[id]'";
            //$sRslt = db_exec($sql);
        }
        /* --- Start Some calculations --- */
        # Subtotal
        $SUBTOT = sprint($inv['subtot']);
        $VAT = sprint($inv['vat']);
        $TOTAL = sprint($inv['total']);
        /* --- End Some calculations --- */
        /* - Start Hooks - */
        //$vatacc = gethook("accnum", "salesacc", "name", "VAT");
        /* - End Hooks - */
        # todays date
        $date = date("d-m-Y");
        $sdate = date("Y-m-d");
        db_conn("cubit");
        if (isset($bankid)) {
            $bankid += 0;
            db_conn("cubit");
            $sql = "SELECT * FROM bankacct WHERE bankid = '{$inv['accid']}'";
            $deptRslt = db_exec($sql) or errDie("Unable to view customers");
            if (pg_numrows($deptRslt) < 1) {
                $error = "<li class=err> Bank not Found.";
                $confirm .= "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
                return $confirm;
            } else {
                $deptd = pg_fetch_array($deptRslt);
            }
            db_conn('core');
            $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
            $rd = db_exec($Sl) or errDie("Unable to get data.");
            $data = pg_fetch_array($rd);
            $BA = $data['accnum'];
        }
        $tot_post = 0;
        # bank  % cust
        if ($ctyp == 's') {
            # Get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                $dept['deptname'] = "<li class=err>Department not Found.";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $tpp = 0;
            //$sql = "SELECT * FROM nons_inv_items  WHERE invid = '$invid' AND div = '".USER_DIV."'";
            //$stkdRslt = db_exec($sql);
            // 			# Put in product
            // 			while($stk = pg_fetch_array($stkdRslt)){
            // 				$wamt=$stk['amt'];
            //
            // 				$tot_post+=$wamt;
            // 				writetrans($dept['debtacc'], $stk['account'], $td, $refnum, $wamt, "Non-Stock Sales on invoice No.$real_invid customer $cus[surname].");
            // 			}
            # record transaction  from data
            foreach ($totstkamt as $stkacc => $wamt) {
                # Debit Customer and Credit stock
                $tot_post += $wamt;
                writetrans($dept['debtacc'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            # Debit bank and credit the account involved
            if ($VAT != 0) {
                $tot_post += $VAT;
                writetrans($dept['debtacc'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            $sdate = date("Y-m-d");
        } else {
            if (!isset($accountc)) {
                $accountc = 0;
            }
            if (!isset($dept['pca'])) {
                $accountc += 0;
                $dept['pca'] = $accountc;
                $dept['debtacc'] = $accountc;
            }
            if (isset($bankid)) {
                $dept['pca'] = $BA;
            }
            if ($ctyp == "ac") {
                $dept['pca'] = $inv['tval'];
            }
            $tpp = 0;
            # record transaction  from data
            foreach ($totstkamt as $stkacc => $wamt) {
                if (!isset($cust['surname'])) {
                    $cust['surname'] = $inv['cusname'];
                    $cust['addr1'] = $inv['cusaddr'];
                }
                # Debit Customer and Credit stock
                $tot_post += $wamt;
                writetrans($dept['pca'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            if (isset($bankid)) {
                db_connect();
                $bankid += 0;
                $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div) VALUES ('{$bankid}', 'deposit', '{$td}', '{$inv['cusname']}', 'Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}', '0', '{$TOTAL}', '{$VAT}', '{$inv['chrgvat']}', 'no', '{$stkacc}', '" . USER_DIV . "')";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                $sql = "UPDATE nons_invoices SET jobid='{$bankid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            }
            # Debit bank and credit the account involved
            if ($VAT != 0) {
                $tot_post += $VAT;
                writetrans($dept['pca'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            $sdate = date("Y-m-d");
        }
        $tot_post = sprint($tot_post);
        db_connect();
        if ($ctyp == 's') {
            $sql = "UPDATE nons_invoices SET balance = total, cusid = '{$cusnum}', ctyp = '{$ctyp}', cusaddr = '{$cus['addr1']}', cusvatno = '{$cus['vatnum']}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
            $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            # Record the payment on the statement
            $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}','{$inv['odate']}', 'Non-Stock Invoice', '" . USER_DIV . "', '{$inv['odate']}')";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            # Record the payment on the statement
            $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}', '{$TOTAL}','{$inv['sdate']}', 'Non-Stock Invoice', '" . USER_DIV . "')";
            $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 + '{$TOTAL}'::numeric(13,2)) WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            # Make ledge record
            custledger($cusnum, $stkacc, $td, $real_invid, "Non Stock Invoice No. {$real_invid}", $TOTAL, "d");
            custDT($TOTAL, $cusnum, $td, $invid, "nons");
            //print $tot_post;exit;
            $tot_dif = sprint($tot_post - $TOTAL);
            if ($tot_dif > 0) {
                writetrans($varacc, $dept['debtacc'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            } elseif ($tot_dif < 0) {
                $tot_dif = $tot_dif * -1;
                writetrans($dept['debtacc'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            }
        } else {
            $date = date("Y-m-d");
            $sql = "UPDATE nons_invoices SET balance=total, accid = '{$dept['pca']}', ctyp = '{$ctyp}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
            $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            $tot_dif = sprint($tot_post - $TOTAL);
            if ($tot_dif > 0) {
                writetrans($varacc, $dept['pca'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            } elseif ($tot_dif < 0) {
                $tot_dif = $tot_dif * -1;
                writetrans($dept['pca'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            }
            if ($ctyp == "c") {
                $cusnum = "0";
            } elseif ($ctyp == "ac") {
                $cusnum = "0";
                $na = "";
            }
        }
        db_connect();
        $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\tVALUES('{$inv['sdate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$VAT}', '{$TOTAL}', 'non', '" . USER_DIV . "')";
        $recRslt = db_exec($sql);
        db_conn('cubit');
        $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t\t('{$cusnum}','{$na}','Non-stock Invoice {$real_invid}','{$inv['sdate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
        $Ri = db_exec($Sl);
        $ecost = sprint($TOTAL - $VAT);
        db_conn('cubit');
        $inv['jobid'] += 0;
        $Sl = "SELECT * FROM ninvc WHERE inv='{$inv['jobid']}'";
        $Ri = db_exec($Sl);
        if (CC_USE == "use") {
            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)\n\t\t\t\t\tVALUES('{$cc['ccid']}', 'dt', 'Invoice', '{$inv['sdate']}', 'Invoice No.{$real_invid}', '{$amount}', '" . USER_NAME . "', '" . USER_DIV . "')";
                    $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
                }
            }
        }
        $i++;
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Retrieve template settings
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices' AND div='" . USER_DIV . "'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        pdf($_POST);
    } else {
        templatePdf($_POST);
    }
    // Final Laytout
    $write = "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>{$i} Invoices Proccesed</th></tr>\n\t\t<tr class='bg-even'><td>Invoices have been successfully printed.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t<tr><th>Quick Links</th></tr>\n\t<tr class='bg-odd'><td><a href='invoice-view.php'>View Invoices</a></td></tr>\n\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function write($_POST)
{
    # Processes
    db_connect();
    # Get vars
    extract($_POST);
    if (isset($back)) {
        return add($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($date, "date", 1, 10, "Invalid Date Entry.");
    $v->isOk($name, "string", 1, 255, "Invalid Person/Business paid to/received from.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($reference, "string", 0, 255, "Invalid Reference.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amount, "float", 1, 10, "Invalid amount.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid vat option.");
    $v->isOk($accinv, "string", 1, 255, "Invalid account number (account involved).");
    # 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;
    }
    # Date format
    # Refnum
    $refnum = getrefnum($date);
    // AND zero='Yes'
    # Start rattling vat
    //	$vatp = TAX_VAT;
    $totamt = $amount;
    if ($chrgvat == "exc") {
        $totamt += $vat;
    } elseif ($chrgvat == "inc") {
        $amount -= $vat;
    } else {
        $vat = 0;
    }
    /* -- Start Hooks -- */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
    # Get hook account number
    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.";
    }
    $banklnk = pg_fetch_array($rslt);
    /* -- End Hooks -- */
    $cheqnum = 0 + $cheqnum;
    db_connect();
    $sql = "UPDATE batch_cashbook SET bankid='{$bankid}',date='{$date}',name='{$name}',\n\t\t\t\tdescript='{$descript}',cheqnum='{$cheqnum}',amount='{$totamt}',vat='{$vat}',\n\t\t\t\tchrgvat='{$chrgvat}',accinv='{$accinv}',reference='{$reference}'\n\t\t\tWHERE cashid='{$id}'";
    db_exec($sql);
    $write = "\n\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Bank Receipt</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t<td>Bank Receipt edited.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    # main table (layout with menu)
    $OUTPUT = "\n\t\t\t\t<center>\n\t\t\t\t<table width = 90%>\n\t\t\t\t\t<tr valign='top'>\n\t\t\t\t\t\t<td width='50%'>{$write}</td>\n\t\t\t\t\t\t<td align='center'>" . mkQuickLinks(ql("bank-pay-add.php", "Add Bank Payment"), ql("bank-recpt-add.php", "Add Bank Receipt"), ql("cashbook-view.php", "View Cash Book"), ql("batch-cashbook-view.php", "View Batch Cashbook")) . "\n\t\t\t\t\t\t</td></tr>\n\t\t\t\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (!isset($proc_trans) or !is_array($proc_trans)) {
        return slctacc($_POST, "<li class='err'>Please Select Transaction(s) To Process</li>");
    }
    db_connect();
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($proc_trans as $procid => $value) {
        $get_trans = "SELECT * FROM cust_trans_batch WHERE id = '{$procid}' LIMIT 1";
        $run_trans = db_exec($get_trans) or errDie("Unable to get transaction information.");
        if (pg_numrows($run_trans) < 1) {
            return slctacc($_POST, "<li class='err'>Transaction Not Found: (ID:{$procid})</li>");
        }
        $parr = pg_fetch_array($run_trans);
        $v->isOk($parr['cusnum'], "num", 1, 50, "Invalid Customer number.");
        $v->isOk($parr['contra_account'], "num", 1, 50, "Invalid Contra Account.");
        $v->isOk($parr['ref_num'], "num", 1, 10, "Invalid Reference number.");
        $v->isOk($parr['amount'], "float", 1, 20, "Invalid Amount.");
        $v->isOk($parr['description'], "string", 0, 255, "Invalid Details.");
        // 		$v->isOk ($author, "string", 1, 30, "Invalid Authorising person name.");
        $datea = explode("-", $parr['proc_date']);
        if (count($datea) == 3) {
            if (!checkdate($datea[1], $datea[2], $datea[0])) {
                $v->isOk($parr['proc_date'], "num", 1, 1, "Invalid date. (1)");
            }
        } else {
            $v->isOk($parr['proc_date'], "num", 1, 1, "Invalid date. (2)");
        }
        $v->isOk($parr['chrg_vat'], "string", 1, 10, "Invalid Charge VAT Option.");
        // 	$v->isOk ($vatinc, "string", 1, 10, "Invalid VAT Inclusive Exclusive Option.");
        $v->isOk($parr['vatcode'], "num", 1, 5, "Invalid Vat Code Option.");
    }
    # 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;
    }
    foreach ($proc_trans as $procid => $value) {
        db_connect();
        $get_trans = "SELECT * FROM cust_trans_batch WHERE id = '{$procid}' LIMIT 1";
        $run_trans = db_exec($get_trans) or errDie("Unable to get transaction information.");
        if (pg_numrows($run_trans) < 1) {
            return slctacc($_POST, "<li class='err'>Transaction Not Found: (ID:{$procid})</li>");
        }
        $parr = pg_fetch_array($run_trans);
        $cusnum = $parr['cusnum'];
        $vatinc = $parr['chrg_vat'];
        if (isset($vatinc) and $vatinc != "0") {
            $chrgvat = "yes";
        } else {
            $chrgvat = "no";
        }
        // 		$chrgvat = $parr['chrg_vat'];
        $vatcode = $parr['vatcode'];
        $amount = $parr['amount'];
        $type = 1;
        $entry = $parr['entry_type'];
        $date = $parr['proc_date'];
        $datea = explode("-", $parr['proc_date']);
        $accid = $parr['contra_account'];
        $refnum = $parr['ref_num'];
        $details = $parr['description'];
        if (isset($chrgvat) and $chrgvat == "yes") {
            db_connect();
            #get selected vatcode
            $get_vatcode = "SELECT * FROM vatcodes WHERE id = '{$vatcode}' LIMIT 1";
            $run_vatcode = db_exec($get_vatcode) or errDie("Unable to get vat code information.");
            if (pg_numrows($run_vatcode) < 1) {
                #vatcode not found ....
                return "<li class='err'>Unable to get vat code information.</li>";
            }
            $vd = pg_fetch_array($run_vatcode);
            if ($vatinc == "inc") {
                #vat inc ...  recalc value
                $vatamt = sprint($amount * ($vd['vat_amount'] / (100 + $vd['vat_amount'])));
                $amount = sprint($amount - $vatamt);
            } else {
                #vat excl
                $amount = sprint($amount);
                $vatamt = sprint($amount / 100 * $vd['vat_amount']);
            }
        } else {
            #vat not set
            $amount = sprint($amount);
            $vatamt = sprint(0);
        }
        // 		$date = "$datea[2]-$datea[1]-$datea[0]";
        # Accounts details
        $accRs = get("core", "*", "accounts", "accid", $accid);
        $acc = pg_fetch_array($accRs);
        # Select customer
        db_connect();
        $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
        if (pg_numrows($custRslt) < 1) {
            return slctacc($_POST, "<li class='err'>Invalid customer ID, or customer has been blocked.</li>");
        } else {
            $cust = pg_fetch_array($custRslt);
        }
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$cust['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            return slctacc($_POST, "<i class='err'>Department Not Found</i>");
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        #get vat acc ...
        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
        # Begin updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        # Probe tran type
        if ($entry == "CT") {
            # Write transaction  (debit contra account, credit debtors control)
            writetrans($accid, $dept['debtacc'], $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
            $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t      <td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t      <td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t      </tr>";
            $samount = $amount - $amount * 2;
            $svatamt = $vatamt - $vatamt * 2;
            recordCT($samount, $cust['cusnum'], $date);
            $type = 'c';
            if (isset($chrgvat) and $chrgvat == "yes") {
                writetrans($vatacc, $dept['debtacc'], $date, $refnum, $vatamt, "VAT for Transaction: {$refnum} for Customer : {$cust['cusname']} {$cust['surname']}");
                vatr($vd['id'], $date, "OUTPUT", $vd['code'], $refnum, "VAT for Transaction: {$refnum} for Customer : {$cust['cusname']} {$cust['surname']}", $samount + $svatamt, $svatamt);
            }
        } else {
            # Write transaction  (debit debtors control, credit contra account)
            writetrans($dept['debtacc'], $accid, $date, $refnum, $amount, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
            $tran = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t</tr>";
            $samount = $amount;
            $svatamt = $vatamt;
            recordDT($samount, $cust['cusnum'], $date);
            $type = 'd';
            if (isset($chrgvat) and $chrgvat == "yes") {
                writetrans($dept['debtacc'], $vatacc, $date, $refnum, $vatamt, "VAT for Transaction: {$refnum} for Customer : {$cust['cusname']} {$cust['surname']}");
                vatr($vd['id'], $date, "OUTPUT", $vd['code'], $refnum, "VAT for Transaction: {$refnum} for Customer : {$cust['cusname']} {$cust['surname']}", $amount + $vatamt, $vatamt);
            }
        }
        db_connect();
        $sdate = date("Y-m-d");
        # record the payment on the statement
        $sql = "\n\t\t\tINSERT INTO stmnt (\n\t\t\t\tcusnum, invid, amount, date, type, st, div, allocation_date\n\t\t\t) VALUES (\n\t\t\t\t'{$cust['cusnum']}', '0', '" . sprint($samount + $svatamt) . "', '{$date}', '{$details}', 'n', '" . USER_DIV . "', '{$date}'\n\t\t\t)";
        $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
        $sql = "\n\t\t\tINSERT INTO open_stmnt (\n\t\t\t\tcusnum, invid, amount, balance, date, type, st, div\n\t\t\t) VALUES (\n\t\t\t\t'{$cust['cusnum']}', '0', '" . sprint($samount + $svatamt) . "', '" . sprint($samount + $svatamt) . "', '{$date}', '{$details}', 'n', '" . USER_DIV . "'\n\t\t\t)";
        $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 + '{$samount}') WHERE cusnum = '{$cust['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
        # Make ledge record
        //	custledger($cust['cusnum'], $accid, $date, $refnum, $details, $amount, $type);
        custledger($cust['cusnum'], $accid, $date, $refnum, $details, sprint($amount + $vatamt), $type);
        db_connect();
        $rem_batch = "DELETE FROM cust_trans_batch WHERE id = '{$procid}'";
        $run_batch = db_exec($rem_batch) or errDie("Unable to remove customer batch transaction information.");
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    }
    return slctacc($_POST, "<li class='yay'>Transaction(s) Have Been Processed.</li><br>");
}
function write($_POST)
{
    #get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference number.");
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $ddate = $d_year . "-" . $d_month . "-" . $d_day;
    if (!checkdate($d_month, $d_day, $d_year)) {
        $v->isOk($ddate, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($recvd)) {
        foreach ($recvd as $sk => $keys) {
            $v->isOk($qtys[$keys], "float", 1, 15, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitcost[$keys], "float", 0, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($cunitcost[$keys], "float", 0, 20, "Invalid Foreign currency Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($duty[$keys], "float", 0, 20, "Invalid Duty Charges for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($dutyp[$keys], "float", 0, 20, "Invalid Duty Charges Percentage for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qtys[$keys] < 1) {
                $v->isOk($qtys[$keys], "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
            if ($qtys[$keys] > $qts[$keys]) {
                $v->isOk($qtys[$keys], "num", 0, 0, "Error : Item Quantity returned is more than the bought quantity : <b>" . ($keys + 1) . "</b>");
            }
            $v->isOk($stkids[$keys], "num", 1, 10, "Invalid Stock number, please enter all details.");
            # Nasty Zeros
            $unitcost[$keys] += 0;
            $cunitcost[$keys] += 0;
            $duty[$keys] += 0;
            $dutyp[$keys] += 0;
        }
        if (isset($sers)) {
            foreach ($sers as $stkid => $sernos) {
                if (!ext_isUnique(ext_remBlnk($sernos))) {
                    $v->isOk("error", "num", 1, 1, "Error : Serial numbers must be unique per Stock Item.");
                } else {
                    foreach ($recvd as $sk => $keys) {
                        if (isset($sernos[$keys]) && $v->isOk($sernos[$keys], "string", 1, 20, "Error : Invalid Serial number.")) {
                            if (ext_findSer($sernos[$keys]) != false) {
                                $v->isOk("#", "string", 1, 20, "Error : Serial number already exists.");
                            }
                        }
                    }
                }
            }
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : Items Not Selected.");
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $_POST['done'] = "";
        return details($_POST, $err);
    }
    //print $td; exit;
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $TD = $pur["pdate"];
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($TD) >= strtotime($blocked_date_from) and strtotime($TD) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    # check if Order has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : Order number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get customer information");
    $sup = pg_fetch_array($supRslt);
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<i class='err'>Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # Insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_conn(PRD_DB);
    # get last ref number
    $refnum = getrefnum();
    db_connect();
    # amount of stock in
    $totstkamt = array();
    $resub = 0;
    foreach ($recvd as $sk => $keys) {
        if ($qtys[$keys] < 1) {
            continue;
        }
        /* -- Calculations -- */
        # Calculate cost amount bought
        $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        $amt[$keys] += $duty[$keys] * $pur['xrate'];
        # Calculate percentage from subtotal
        $perc[$keys] = $amt[$keys] / ($pur['subtot'] * $pur['xrate']) * 100;
        # Get percentage from shipping charges
        $shipchrg[$keys] = $perc[$keys] / 100 * ($pur['shipchrg'] * $pur['xrate']);
        # add shipping charges to amt
        $amt[$keys] = round($amt[$keys] + $shipchrg[$keys], 2);
        $resub += $amt[$keys];
        /* -- End Calculations --*/
        # Get selamt from selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        if ($stk['units'] < 0) {
            $min_stock = abs($stk['units']);
            if ($qtys[$keys] < $min_stock) {
                $min_stock = $qtys[$keys];
            }
        } else {
            $min_stock = 0;
        }
        # Update Order items
        $sql = "UPDATE purint_items SET rqty = (rqty + '{$qtys[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        # update stock(ordered + qty, units + qty, csamt + (csamt + amt))
        $sql = "UPDATE stock SET ordered = (ordered - '{$qtys[$keys]}'), units = (units + '{$qtys[$keys]}' +'{$min_stock}'), csamt = (csamt + '{$amt[$keys]}') WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        if (isset($sers[$stkids[$keys]][$keys])) {
            ext_InSer($sers[$stkids[$keys]][$keys], $stkids[$keys], $sup['supname'], $pur['purnum'], "pur", $TD);
            $serial = $sers[$stkids[$keys]][$keys];
            db_connect();
            $sql = "INSERT INTO pserec(purid, purnum, stkid, serno, div)\n\t\t\t\tVALUES('{$purid}', '{$pur['purnum']}', '{$stkids[$keys]}', '{$serial}', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to update stock serials in Cubit.", SELF);
        }
        # get selected stock
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        $sdate = date("Y-m-d");
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $TD, $qtys[$keys], $amt[$keys], "Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}");
        db_connect();
        $cspric = sprint($amt[$keys] / $qtys[$keys]);
        $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\tVALUES('{$TD}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'purchase', '{$qtys[$keys]}', '{$amt[$keys]}', '{$cspric}', 'Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}', '" . USER_DIV . "')";
        $recRslt = db_exec($sql);
        # keep records for transactions
        if (isset($totstkamt[$stk['whid']])) {
            $totstkamt[$stk['whid']] += $amt[$keys];
        } else {
            $totstkamt[$stk['whid']] = $amt[$keys];
        }
        # Just wanted to fix the xxx.xxxxxxe-x value
        # $csprice = round(($stk['csamt']/$stk['units']), 2);
        if ($stk['units'] > 0) {
            $csprice = round($stk['csamt'] / $stk['units'], 2);
        } else {
            $csprice = round($stk['csprice'], 2);
        }
        # update stock(csprice = (csamt/units))
        $sql = "UPDATE stock SET csprice = '{$csprice}', lcsprice = '{$cspric}' WHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        # check if there are any outstanding items
        $sql = "SELECT * FROM purint_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        # if none the set to received
        if (pg_numrows($stkdRslt) < 1) {
            # update surch_int(received = 'y')
            $sql = "UPDATE purch_int SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF);
        }
    }
    if ($min_stock > 0) {
        $cost = sprint($unitcost[$keys] * $min_stock);
        $td = "{$d_year}-{$d_month}-{$d_day}";
        db_conn("exten");
        $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        $stockacc = $wh['stkacc'];
        $cosacc = $wh['cosacc'];
        db_connect();
        $Sl = "UPDATE stock SET csamt = (csamt - '{$cost}'),units=(units-'{$min_stock}') WHERE stkid='{$stkids[$keys]}'";
        $Ri = db_exec($Sl);
        writetrans($cosacc, $stockacc, $TD, $refnum, $cost, "Cost Of Sales for stock sold before international purchase {$pur['purnum']}");
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, 0, $cost, "Cost Of Sales for stock sold before international purchase {$pur['purnum']}");
        db_connect();
        $Sl = "INSERT INTO pcost(purnum,cost,qty,rqty,stkid) VALUES ('{$pur['purnum']}','{$unitcost[$keys]}','{$min_stock}','0','{$stk['stkid']}')";
        $Ri = db_exec($Sl);
    }
    if (strlen($refno) > 0) {
        if (strlen($pur['refno']) > 0) {
            $refno = "{$pur['refno']}-{$refno}";
        } else {
            $refno = $refno;
        }
    } else {
        $refno = $pur['refno'];
    }
    # Update Order on the DB
    $fresub = sprint($resub / $pur['xrate']);
    $sql = "UPDATE purch_int SET rsubtot = (rsubtot + '{$fresub}'), rlsubtot = (rlsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', ddate = '{$ddate}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    /* --- Transactions --- */
    db_conn(PRD_DB);
    $refnum = getrefnum();
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    /* - End Hooks - */
    # record transaction  from data
    foreach ($totstkamt as $whid => $wamt) {
        # Get whouse info
        db_conn("exten");
        $sql = "SELECT stkacc,conacc FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # Debit Stock and Credit Suppliers control
        writetrans($wh['stkacc'], $wh['conacc'], $TD, $refnum, $wamt, "International Stock Order No. {$pur['purnum']} Received from Supplier {$sup['supname']}.");
    }
    # commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* Start moving if Order received and invoiced */
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y" && $pur['invcd'] == 'y') {
        # Copy Order
        db_conn($pur['prd']);
        $sql = "INSERT INTO purch_int(purid, deptid, supid, supaddr, terms, pdate, ddate, xrate, fcid, curr, tax, shipchrg, fshipchrg, duty, subtot, total, balance, fbalance, remarks, refno, received, done, div, purnum)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['xrate']}', '{$pur['fcid']}', '{$pur['curr']}', '{$pur['tax']}', '{$pur['shipchrg']}', '{$pur['fshipchrg']}', '{$pur['duty']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['fbalance']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
        /*-- Cost varience -- */
        $nsubtot = sprint($pur['total'] - $pur['tax']);
        $nsubtot = sprint($nsubtot * $pur['xrate']);
        if ($pur['rlsubtot'] > $nsubtot) {
            $diff = sprint($pur['rlsubtot'] - $nsubtot);
            # Debit Stock Control and Credit Creditors control
            writetrans($wh['conacc'], $cvacc, $TD, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        } elseif ($nsubtot > $pur['rlsubtot']) {
            $diff = sprint($nsubtot - $pur['rlsubtot']);
            # Debit Stock Control and Credit Creditors control
            writetrans($cvacc, $wh['conacc'], $TD, $refnum, $diff, "Cost Variance for Stock Received on Purchase No. {$pur['purnum']} from Supplier : {$sup['supname']}.");
        }
        /*-- End Cost varience -- */
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert Order items
            db_conn($pur['prd']);
            $sql = "INSERT INTO purint_items(purid, whid, stkid, qty, unitcost, cunitcost, duty, dutyp, amt, ddate, recved, div) VALUES('{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['cunitcost']}', '{$stktc['duty']}', '{$stktc['dutyp']}', '{$stktc['amt']}', '{$stktc['ddate']}', 'y', '" . USER_DIV . "')";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        db_connect();
        # Remove the Order from running DB
        $sql = "DELETE FROM purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Record where Order is
        $sql = "INSERT INTO movpurch(purtype, purnum, prd, div) VALUES('int', '{$pur['purnum']}', '{$pur['prd']}', '" . USER_DIV . "')";
        $movRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
        # Remove those Order items from running DB
        $sql = "DELETE FROM purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    }
    /* End moving Order received */
    // Final Layout
    $write = "\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>International Order received</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Order receipt from Supplier <b>{$sup['supname']}</b> has been recorded.</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='purch-int-view.php'>View International Orders</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
    return $write;
}
function write($_POST)
{
    #get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $ddate = $dyear . "-" . $dmon . "-" . $dday;
    if (!checkdate($dmon, $dday, $dyear)) {
        $v->isOk($ddate, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qtys[$keys], "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            $v->isOk($unitamts[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            $v->isOk($stkacc[$keys], "num", 1, 10, "Invalid Item Account number : <b>" . ($keys + 1) . "</b>");
        }
    } else {
        $v->isOk("#", "num", 0, 0, "Error : no products selected.");
    }
    $prd += 0;
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get Order info
    db_conn($prd);
    $sql = "SELECT * FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # Get selected supplier info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to get supplier");
    if (pg_numrows($supRslt) < 1) {
        $error = "<li class='err'> Supplier not Found.</li>";
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    } else {
        $sup = pg_fetch_array($supRslt);
        $pur['supplier'] = $sup['supname'];
        $pur['supaddr'] = $sup['supaddr'];
        # Get department info
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$sup['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            return "<i class='err'>Department Not Found</i>";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        $supacc = $dept['credacc'];
    }
    # Insert Order to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    db_connect();
    # Update all supplies xchange rate first
    xrate_update($pur['fcid'], $pur['xrate'], "suppurch", "id");
    sup_xrate_update($pur['fcid'], $pur['xrate']);
    db_connect();
    $retax = 0;
    if (isset($qtys)) {
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            db_conn($prd);
            $sql = "SELECT * FROM nons_purint_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # the unitcost + delivery charges * qty
            $famt[$keys] = sprint($unitamts[$keys] * $qtys[$keys]);
            # calculate tax
            $ftaxes[$keys] = svat($famt[$keys], $pur['subtot'], $pur['tax']);
            $amt[$keys] = sprint($unitamts[$keys] * $pur['xrate'] * $qtys[$keys]);
            # calculate tax
            $retax += sprint($ftaxes[$keys] * $pur['xrate']);
            # Update Order items
            $sql = "UPDATE nons_purint_items SET rqty = (rqty + '{$qtys[$keys]}'), accid = '{$stkacc[$keys]}' WHERE id = '{$ids[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            # keep records for transactions
            if (isset($totstkamt[$stkacc[$keys]])) {
                $totstkamt[$stkacc[$keys]] += $amt[$keys];
            } else {
                $totstkamt[$stkacc[$keys]] = $amt[$keys];
            }
        }
    }
    /* Transactions */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $refnum = getrefnum();
    $sdate = $pur["pdate"];
    //$ddate;
    /* - End Hooks - */
    # record transaction  from data
    foreach ($totstkamt as $stkacc => $wamt) {
        # Debit Stock and Credit Suppliers control
        writetrans($supacc, $stkacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. {$pur['purnum']} Returned to Supplier {$sup['supname']}.");
    }
    db_connect();
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['cusid']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        return "Please select the vatcode for all your stock.";
    }
    $vd = pg_fetch_array($Ri);
    if ($retax > 0) {
        writetrans($supacc, $vatacc, date("d-m-Y"), $refnum, $retax, "Returned, Non-Stock Purchase Vat paid on Non-Stock Order No. {$pur['purnum']}.");
    }
    $retot = sprint(array_sum($amt) + $retax);
    vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Returned, Non-Stock Purchase Vat paid on Non-Stock Order No. {$pur['purnum']}.", $retot, $retax);
    $fretot = sprint(array_sum($famt) + array_sum($ftaxes));
    suppledger($sup['supid'], $stkacc, $sdate, $pur['purid'], "Returned, Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'd');
    db_connect();
    # update the supplier (make balance more)
    $sql = "UPDATE suppliers SET balance = (balance - '{$retot}'), fbalance = (fbalance - '{$fretot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$sup['supid']}','{$sdate}', '{$dept['credacc']}', '-{$fretot}','Returned, Non Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}','" . USER_DIV . "')";
    $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
    db_connect();
    # make transaction record for age analysis
    $sql = "INSERT INTO suppurch(supid, purid, pdate, fcid, balance, fbalance, div) VALUES('{$sup['supid']}', '{$pur['purnum']}', '{$sdate}', '{$pur['fcid']}', '-{$retot}', '-{$fretot}', '" . USER_DIV . "')";
    $purcRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.", SELF);
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    db_conn($prd);
    # check if there are any outstanding items
    $sql = "SELECT * FROM nons_purint_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # if none the set to received
    if (pg_numrows($stkdRslt) < 1) {
        # update surch_int(received = 'y')
        $sql = "UPDATE nons_purch_int SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        //$rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.",SELF);
    }
    # Update Order on the DB
    $sql = "UPDATE nons_purch_int SET refno = '{$refno}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.",SELF);
    /* End Transactions */
    /* Start moving if Order received */
    db_conn($prd);
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $sql = "SELECT * FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $rdate = date("Y-m-d");
    # copy Order
    db_conn($prd);
    $sql = "INSERT INTO rnons_purch_int(purid, deptid, supid, supplier, supaddr, terms, pdate, ddate, shipchrg, xrate, fcid, curr, currency, shipping, subtot, total, balance, tax, remarks, refno, received, done, div, purnum, rdate)";
    $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['xrate']}', '{$pur['fcid']}', '{$pur['curr']}', '{$pur['currency']}', '{$pur['shipping']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['tax']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}', '{$rdate}')";
    $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Order to Cubit.", SELF);
    db_connect();
    db_conn($prd);
    # get selected stock
    $sql = "SELECT * FROM nons_purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stktcRslt = db_exec($sql);
    while ($stktc = pg_fetch_array($stktcRslt)) {
        # Insert Order items
        db_conn($prd);
        $sql = "INSERT INTO rnons_purint_items(purid, cod, des, qty, unitcost, cunitcost, duty, dutyp, amt, accid, div) VALUES('{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['cunitcost']}', '{$stktc['duty']}', '{$stktc['dutyp']}', '{$stktc['amt']}', '{$stktc['accid']}', '" . USER_DIV . "')";
        $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
    }
    db_connect();
    # Remove the Order from running DB
    $sql = "DELETE FROM nons_purch_int WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.",SELF);
    # Remove those Order items from running DB
    $sql = "DELETE FROM nons_purint_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    //$delRslt = db_exec($sql) or errDie("Unable to update int Orders information in Cubit.",SELF);
    # Commit updating
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving Order received */
    $cc = "<script> CostCenter('dt', 'Returned, International Non-Stock Purchase', '{$pur['pdate']}', 'Returned, Non Stock Purchase No.{$pur['purnum']}', '" . sprint($retot - $retax) . "', ''); </script>";
    // Final Layout
    $write = "{$cc}\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>International Non-Stock Order received</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>International Non-Stock Order receipt has been recorded.</td>\n\t\t</tr>\n\t</table>\n\t<p>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='nons-purch-int-view.php'>View International Orders</a></td>\n\t\t</tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
function write($_POST)
{
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($pay as $key => $value) {
        $v->isOk($pay[$key], "num", 1, 50, "Invalid purchase No.");
        $v->isOk($paidamt[$key], "float", 1, 20, "Invalid amount to be paid. [{$key}]");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get creditors account
    $creditacc = gethook("accnum", "pchsacc", "name", "Creditors");
    $tot = 0;
    # Creditors
    $pays = "";
    foreach ($pay as $key => $value) {
        core_connect();
        # get purchase info
        $sql = "SELECT * FROM purchases WHERE purchid = '{$pay[$key]}'";
        $purchRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve purchase details from database.", SELF);
        if (pg_numrows($purchRslt) < 1) {
            $OUTPUT = "<li clss=err>Invalid purchase ID.";
            return $OUTPUT;
        }
        $purch = pg_fetch_array($purchRslt);
        # get credit purchase info
        $sql = "SELECT amount FROM credit_purch WHERE purchid = '{$pay[$key]}'";
        $ctpRslt = db_exec($sql);
        $ctp = pg_fetch_array($ctpRslt);
        # get account name for account paid
        $accRslt = get("core", "accname", "accounts", "accid", $purch['paidacc']);
        $acc = pg_fetch_array($accRslt);
        $paidacc = $acc['accname'];
        # get account name for account used
        $accRslt = get("core", "accname", "accounts", "accid", $purch['usedacc']);
        $acc = pg_fetch_array($accRslt);
        $usedacc = $acc['accname'];
        $pays .= "<tr class='bg-odd'>\n                                <input type=hidden name=pay[] value='{$pay[$key]}'>\n                                <td>{$purch['retailer']}</td>\n                                <td>{$purch['itemname']}</td>\n                                <td>{$purch['descript']}</td>\n                                <td>{$purch['quantity']}</td>\n                                <td>" . CUR . " {$ctp['amount']}</td>\n                                <td>" . CUR . " {$paidamt[$key]}</td>\n                                <td>{$usedacc}</td>\n                                <td>{$paidacc}</td>\n                        </tr>";
        # reduce the money that has been paid
        $sql = "UPDATE credit_purch SET amount = (amount - cast(float8 '{$paidamt[$key]}' as numeric)) WHERE purchid = '{$pay[$key]}'";
        $payRslt = db_exec($sql) or errDie("Unable to update credit purchases table.", SELF);
        $refnum = getrefnum(date('d-m-Y'));
        writetrans($creditacc, $purch['usedacc'], date('d-m-Y'), $refnum, $paidamt[$key], 'Pay Purchase Credit.');
        $tot += $paidamt[$key];
    }
    $write = "<center>\n        <h3>Multiple Credits Payments Processed</h3>\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n                <tr><th>Retailer</th><th>Item Name</th><th>Description</th><th>Quantity</th><th>Outstanding amount</th><th>Amount Paid</th><th>Account used</th><th>Account paid</th></tr>\n                {$pays}\n                <tr><td><br></td></tr>\n                <tr class='bg-even'><td colspan=5><b>Total Amount Paid</b></td><td colspan=2><b>" . CUR . " " . sprintf("%01.2f", round($tot, 2)) . "</b></td></tr>\n        </table>\n        <br><br><br>\n        <table border=0 cellpadding='2' cellspacing='1' width=15%>\n                <tr><th>Quick Links</th></tr>\n                <tr bgcolor='#88BBFF'><td><a href='creditors-view.php'>View Creditors</a></td></tr>\n                <script>document.write(getQuicklinkSpecial());</script>\n        </table>";
    return $write;
}
function details($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    // 	# display errors, if any
    // 	if ($v->isError ()) {
    // 		$err = "";
    // 		$errors = $v->getErrors();
    // 		foreach ($errors as $e) {
    // 			$err .= "<li class=err>".$e["msg"];
    // 		}
    // 		$confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
    // 		return $confirm;
    // 	}
    # Get invoice info
    $sql = "SELECT * FROM cubit.nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    // are we working with an international invoice?
    if ($inv["currency"] != "") {
        $currency = $inv["currency"];
    } else {
        $currency = CUR;
    }
    /* --- Start some checks --- */
    # check if stock was selected(yes = put done button)
    /* --- End some checks --- */
    /* --- Start Products Display --- */
    # Products layout
    $products = array();
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM cubit.nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $page = 0;
    while ($stk = pg_fetch_array($stkdRslt)) {
        if ($i >= 25) {
            $page++;
            $i = 0;
        }
        //		$sql = "SELECT *,
        //					extract('epoch' FROM hired_time) AS e_from,
        //					extract('epoch' FROM return_time) AS e_to
        //				FROM hire.assets_hired
        //				WHERE item_id='$stk[item_id]'";
        //		$hires_rslt = db_exec($sql) or errDie("Unable to retrieve hires.");
        //		$hires_data = pg_fetch_array($hires_rslt);
        // Check Tax Excempt
        db_conn("cubit");
        $sql = "SELECT zero FROM vatcodes WHERE id='{$stk['vatex']}'";
        $zRslt = db_exec($sql) or errDie("Unable to retrieve vat code from Cubit.");
        $vatex = pg_fetch_result($zRslt, 0);
        if ($vatex == "Yes") {
            $ex = "#";
        } else {
            $ex = "";
        }
        $products[$page][] = "\r\n\t\t<tr valign='top'>\r\n\t\t\t<td style='border-right: 2px solid #000'>{$ex} {$stk['description']}&nbsp;</td>\r\n\t\t\t<td style='border-right: 2px solid #000'>{$stk['qty']}&nbsp;</td>\r\n\t\t\t<td style='border-right: 2px solid #000'>{$stk['unitcost']}&nbsp;</td>\r\n\t\t\t<td align='right'>{$currency} " . sprint($stk["amt"]) . "&nbsp;</td>\r\n\t\t</tr>";
        $i++;
    }
    $blank_lines = 25;
    foreach ($products as $key => $val) {
        $bl = $blank_lines - count($products[$key]);
        for ($i = 0; $i <= $bl; $i++) {
            $products[$key][] = "<tr>\r\n \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n \t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n \t\t\t\t<td>&nbsp;</td>\r\n \t\t\t</tr>";
        }
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*refnum*/
    /* --- Updates ---- */
    db_connect();
    # get selected stock in this invoice
    $sql = "SELECT * FROM cubit.nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='SALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sp = "<tr><td><b>Sales Person:</b> {$inv['salespn']}</td></tr>";
    } else {
        $sp = "";
    }
    if ($inv['chrgvat'] == "yes") {
        $inv['chrgvat'] = "Inclusive";
    } elseif ($inv['chrgvat'] == "no") {
        $inv['chrgvat'] = "Exclusive";
    } else {
        $inv['chrgvat'] = "No vat";
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Retrieve the company information
    db_conn("cubit");
    $sql = "SELECT * FROM compinfo";
    $comp_rslt = db_exec($sql) or errDie("Unable to retrieve company information from Cubit.");
    $comp_data = pg_fetch_array($comp_rslt);
    // Retrieve customer information
    db_conn("cubit");
    $sql = "SELECT * FROM customers WHERE cusnum='{$inv['cusid']}'";
    $cust_rslt = db_exec($sql) or errDie("Unable to retrieve customer information from Cubit.");
    $cust_data = pg_fetch_array($cust_rslt);
    #make sure we have a valid bank id for customer
    if (!isset($inv['bankid']) or strlen($inv['bankid']) < 1) {
        $inv['bankid'] = '2';
    }
    // Retrieve the banking information
    db_conn("cubit");
    $sql = "SELECT * FROM bankacct WHERE bankid='{$inv['bankid']}' AND div='" . USER_DIV . "'";
    $bank_rslt = db_exec($sql) or errDie("Unable to retrieve bank information from Cubit.");
    $bank_data = pg_fetch_array($bank_rslt);
    if ($inv['ctyp'] != "s") {
        $cust_data['addr1'] = $inv['cusaddr'];
        $cust_data['surname'] = $inv['cusname'];
        $cust_data['paddr1'] = "";
        $cust_data['del_addr1'] = "";
    }
    $table_borders = "\r\n\t\tborder-top: 2px solid #000000;\r\n\t\tborder-left: 2px solid #000000;\r\n\t\tborder-right: 2px solid #000000;\r\n\t\tborder-bottom: none;\r\n\t";
    // 	$nolr_borders = "
    // 		border-top: 2px solid #000;
    // 		border-left: none;
    // 		border-right: none;
    // 		border-bottom: none;
    // 	";
    $details = "";
    for ($i = 0; $i <= $page; $i++) {
        // new page?
        if ($i > 1) {
            $details .= "<br style='page-break-after:always;'>";
        }
        $products_out = "";
        foreach ($products[$i] as $string) {
            $products_out .= $string;
        }
        $details .= "<center>\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table border='0' cellpadding='2' cellspacing='2' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='left' rowspan='2'><img src='compinfo/getimg.php' width='230' height='47'></td>\r\n\t\t\t\t\t<td align='left' rowspan='2'><font size='5'><b>" . COMP_NAME . "</b></font></td>\r\n\t\t\t\t\t<td align='right'><font size='5'><b>Tax Invoice</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<!-- Rowspan -->\r\n\t\t\t\t\t<!-- Rowspan -->\r\n\t\t\t\t\t<td align='right'><font size='4'><b>Reprint</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr1']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr1']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr2']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr2']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr3']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['paddr3']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['addr4']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$comp_data['postcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>REG:</b> {$comp_data['regnum']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>{$bank_data['bankname']}</b>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>VAT REG:</b> {$comp_data['vatnum']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch</b> {$bank_data['branchname']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Tel:</b> {$comp_data['tel']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Branch Code:</b> {$bank_data['branchcode']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Fax:</b> {$comp_data['fax']}&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Acc Num:</b> {$bank_data['accnum']}&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td><td valign='top'>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date</b></td>\r\n\t\t\t\t\t<td><b>Page Number</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>{$inv['odate']}</td>\r\n\t\t\t\t\t<td>" . ($i + 1) . "</td>\r\n\t\t\t\t</tr>\r\n\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000'>&nbsp</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr><td>&nbsp</td></tr>\r\n\t\t\t\t\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'><b>Invoice No:</b> {$inv['invnum']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td colspan='2'>&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$sp}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td align='center'><font size='4'><b>Tax Invoice To:</b></font></td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>{$cust_data['surname']}</b>&nbsp;</td>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Postal Address</b></td>\r\n\t\t\t\t\t<td width='33%'><b>Delivery Address</td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["addr1"]) . "&nbsp;</td>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>" . nl2br($cust_data["paddr1"]) . "&nbsp;</td>\r\n\t\t\t\t\t<td>" . nl2br($cust_data["del_addr1"]) . "&nbsp;</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td width='33%' style='border-right: 2px solid #000'><b>Customer VAT No:</b> {$inv['cusvatno']}</td>\r\n\t\t\t\t\t<td width='33%'><b>Customer Order No:</b> {$inv['cordno']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Description</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Qty</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000; border-right: 2px solid #000'><b>Unit Cost</b></td>\r\n\t\t\t\t\t<td style='border-bottom: 2px solid #000;' align='right'><b>Amount</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t{$products_out}\r\n\t\t\t</table>\r\n\t\t\t</td></tr>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='{$table_borders}'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td><i>VAT Exempt Indicator: #</i></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td>{$inv['remarks']}</td>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\r\n\t\t<table cellpadding='0' cellspacing='0' width='85%' style='border: 2px solid #000000'>\r\n\t\t\t<tr><td>\r\n\t\t\t<table cellpadding='2' cellspacing='0' border='0' width='100%'>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>\r\n\t\t\t\t\t\t<b>Terms:</b> {$inv['terms']} days</b>\r\n\t\t\t\t\t</td>\r\n\r\n\t\t\t\t\t<td><b>Delivery Charge:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['delivery']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\t\t\t\t\t<td><b>Trade Discount:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['discount']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Received in good order by:</b>_____________________</td>\r\n\r\n\t\t\t\t\t<td><b>Subtotal:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['subtot']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'>&nbsp;</td>\r\n\r\n\t\t\t\t\t<td><b>VAT {$vat14}:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['vat']}</b></td>\r\n\t\t\t\t<tr>\r\n\t\t\t\t<tr>\r\n\t\t\t\t\t<td style='border-right: 2px solid #000'><b>Date:</b>_____________________</td>\r\n\r\n\t\t\t\t\t<td><b>Total Incl VAT:</b></td>\r\n\t\t\t\t\t<td><b>" . CUR . "{$inv['total']}</b></td>\r\n\t\t\t\t</tr>\r\n\t\t\t\t</tr>\r\n\t\t\t</table>\r\n\t\t</table>\r\n\t\t";
    }
    // Retrieve template settings
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    $OUTPUT = $details;
    require "tmpl-print.php";
}
function pay($_POST)
{
    //processes
    db_connect();
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purchid, "num", 1, 20, "Invalid Purchase ID.");
    $v->isOk($paidamt, "float", 1, 20, "Invalid amount to be paid.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    // Connect to database
    core_Connect();
    # get purchase info
    $sql = "SELECT * FROM purchases WHERE purchid = '{$purchid}'";
    $purchRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve purchase details from database.", SELF);
    $numrows = pg_numrows($purchRslt);
    if ($numrows < 1) {
        $OUTPUT = "<li clss=err>Invalid purchase ID.";
        require "template.php";
    }
    $purch = pg_fetch_array($purchRslt);
    # reduce the money that has been paid
    $sql = "UPDATE credit_purch SET amount = (amount - cast(float8 '{$paidamt}' as numeric)) WHERE purchid = '{$purchid}'";
    $payRslt = db_exec($sql) or errDie("Unable to update credit purchases table.", SELF);
    # get creditors account
    $creditacc = gethook("accnum", "pchsacc", "name", "Creditors");
    $refnum = getrefnum(date('d-m-Y'));
    writetrans($creditacc, $purch['usedacc'], date('d-m-Y'), $refnum, $paidamt, 'Pay Purchase Credit.');
    # status report
    $pay = "\r\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='100%'>\r\n        <tr><th>Credit Paid</th></tr>\r\n        <tr class=datacell><td>Credit for,<b> {$purch['itemname']}</b> bought From <b>{$purch['retailer']}</b>, was successfully paid.</td></tr>\r\n        </table>";
    # main table (layout with menu)
    $OUTPUT = "<center>\r\n        <table width = 90%>\r\n        <tr valign=top><td width=60%>{$pay}</td>\r\n        <td align=center>\r\n        <table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=80%>\r\n        <tr><th>Quick Navigation</th></tr>\r\n        <tr class=datacell><td align=center><a href='purchase-view.php'>View Other Purchases</td></tr>\r\n        <tr class=datacell><td align=center><a href='purchase-new.php'>Add New Purchase</td></tr>\r\n        </table>\r\n        </td></tr></table>";
    return $OUTPUT;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid purchase number.");
    if (!isset($supid) && !isset($deptid)) {
        $v->isOk($supacc, "num", 1, 10, "Invalid Supplier Account number.");
    }
    $v->isOk($remarks, "string", 0, 255, "Invalid Remarks.");
    $v->isOk($refno, "string", 0, 255, "Invalid Delivery Reference No.");
    $v->isOk($shipchrg, "float", 0, 20, "Invalid Delivery Charges.");
    $pdate = $p_year . "-" . $p_month . "-" . $p_day;
    if (!checkdate($p_month, $p_day, $p_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid Date.");
    }
    # used to generate errors
    $error = "asa@";
    # check quantities
    if (isset($qtys)) {
        foreach ($qtys as $keys => $qty) {
            $v->isOk($qty, "num", 1, 10, "Invalid Quantity for product number : <b>" . ($keys + 1) . "</b>");
            if ($qty > $qts[$keys]) {
                $v->isOk($qty, "num", 0, 0, "Error : Quantity for product number : <b>" . ($keys + 1) . "</b> is more that Qty Purchased");
            }
            $v->isOk($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qty < 1) {
                $v->isOk($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>" . ($keys + 1) . "</b>");
            }
        }
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return details($_POST, $err);
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($pur['pdate']) >= strtotime($blocked_date_from) and strtotime($pur['pdate']) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    $pur['pdate'] = $p_year . "-" . $p_month . "-" . $p_day;
    # Get selected supplier info
    db_connect();
    if (isset($supid)) {
        $sql = "SELECT * FROM suppliers WHERE supid = '{$supid}' AND div = '" . USER_DIV . "'";
        $supRslt = db_exec($sql) or errDie("Unable to get supplier");
        if (pg_numrows($supRslt) < 1) {
            $error = "<li class='err'> Supplier not Found.</li>";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $sup = pg_fetch_array($supRslt);
            $pur['supplier'] = $sup['supname'];
            $pur['supaddr'] = $sup['supaddr'];
            # Get department info
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$sup['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                return "<i class='err'>Department Not Found</i>";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $supacc = $dept['credacc'];
        }
    } elseif (isset($deptid)) {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            $error = "<li class='err'> Department not Found.";
            $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $confirm;
        } else {
            $dept = pg_fetch_array($deptRslt);
            $supacc = $dept['pca'];
        }
    }
    # check if purchase has been received
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    # Insert purchase to DB
    db_connect();
    # begin updating
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $refnum = getrefnum();
    /*refnum*/
    db_connect();
    if (isset($qtys)) {
        # amount of stock in
        $totstkamt = array();
        $resub = 0;
        # Get subtotal
        foreach ($qtys as $keys => $value) {
            # Skip zeros
            if ($qtys[$keys] < 1) {
                continue;
            }
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
        }
        $SUBTOTAL = array_sum($amt);
        $revat = 0;
        foreach ($qtys as $keys => $value) {
            # Get selected stock line
            $sql = "SELECT * FROM nons_pur_items WHERE cod = '{$cod[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            $stkd = pg_fetch_array($stkdRslt);
            # Calculate cost amount bought
            $amt[$keys] = $qtys[$keys] * $unitcost[$keys];
            /* delivery charge */
            # Calculate percentage from subtotal
            $perc[$keys] = $amt[$keys] / $SUBTOTAL * 100;
            # Get percentage from shipping charges
            $shipc[$keys] = $perc[$keys] / 100 * $shipchrg;
            # add delivery charges
            $amt[$keys] += $shipc[$keys];
            /* end delivery charge */
            # the subtotal + delivery charges
            $resub += $amt[$keys];
            # calculate vat
            $svat[$keys] = svat($amt[$keys], $stkd['amt'], $stkd['svat']);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "Vat for Non-Stock Purchase No. {$pur['purnum']}", -$amt[$keys], -$svat[$keys]);
            # received vat
            $revat += $svat[$keys];
            # make amount vat free
            if ($pur['vatinc'] == "yes") {
                $amt[$keys] = $amt[$keys] - $svat[$keys];
            }
            # Update Order items
            $sql = "UPDATE nons_pur_items SET rqty = (rqty + '{$qtys[$keys]}') WHERE cod = '{$cod[$keys]}' AND purid='{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
            /* ?: refer to :Code Insert:
            			# keep records for transactions
            			if(isset($totstkamt[$stkacc[$keys]])){
            				$totstkamt[$stkacc[$keys]] += $amt[$keys];
            			}else{
            				$totstkamt[$stkacc[$keys]] = $amt[$keys];
            			}
            			*/
            # check if there are any outstanding items
            $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND (qty - rqty) > '0' AND div = '" . USER_DIV . "'";
            $stkdRslt = db_exec($sql);
            # if none the set to received
            if (pg_numrows($stkdRslt) < 1) {
                # update surch_int(received = 'y')
                $sql = "UPDATE nons_purchases SET received = 'y', supplier = '{$pur['supplier']}', supaddr = '{$pur['supaddr']}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update international Orders in Cubit.", SELF);
            }
        }
    }
    # Update purchase on the DB
    if ($pur['part'] == 'y') {
        # Update purchase on the DB
        $sql = "UPDATE nons_purchases SET shipchrg = (shipchrg + '{$shipchrg}'), refno = '{$refno}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    } else {
        # Update purchase on the DB
        $sql = "UPDATE nons_purchases SET shipchrg = '{$shipchrg}', refno = '{$refno}', remarks = '{$remarks}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update purchase in Cubit.", SELF);
    }
    /* Transactions */
    /* - Start Hooks - */
    /* - End Hooks - */
    $detadd = "";
    if (isset($supid)) {
        $detadd = " from Supplier {$sup['supname']}";
    }
    $sdate = $pur['pdate'];
    /* ?:refer to :Code Insert:
    		# record transaction  from data
    		foreach($totstkamt as $stkacc => $wamt){
    			# Debit Stock and Credit Suppliers control
    			writetrans($stkacc, $supacc, date("d-m-Y"), $refnum, $wamt, "Non-Stock Purchase No. $pur[purnum] Received $detadd.");
    			pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. $pur[purnum] Received $detadd.", $wamt, "Cash Purchase");
    		}*/
    # Calc Vat amount on (subtot + delchrg)
    $vatamt = $revat;
    # Add vat if not included
    if ($pur['vatinc'] == 'no') {
        $retot = $resub + $vatamt;
    } elseif ($pur['vatinc'] == "novat") {
        $retot = $resub;
        $vatamt = 0;
    } else {
        $retot = $resub;
    }
    # get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    $tot_post = 0;
    if ($vatamt != 0) {
        $tot_post += $vatamt;
        # Debit bank and credit the account involved
        writetrans($vatacc, $supacc, $pdate, $refnum, $vatamt, "Non-Stock Purchase Vat paid on Non-Stock Purchase No. {$pur['purnum']} {$detadd}.");
        pettyrec($supacc, $sdate, "ct", "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.", $vatamt, "Cash Purchase Vat");
        # Record the payment on the statement
        db_connect();
        $sdate = $pur['pdate'];
    }
    if (isset($supid)) {
        $DAte = $pur['pdate'];
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$retot}') WHERE supid = '{$sup['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, amount, descript,ref,ex,div) VALUES('{$sup['supid']}','{$DAte}', '{$dept['credacc']}', '{$retot}','Non-Stock Purchase No. {$pur['purnum']} Received', '{$refnum}', '{$pur['purnum']}','" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        suppledger($sup['supid'], $wh['stkacc'], $DAte, $pur['purid'], "Non-Stock Purchase No. {$pur['purnum']} received.", $retot, 'c');
        db_connect();
        # update the supplier age analysis (make balance less)
        /* Make transaction record for age analysis */
        $sql = "INSERT INTO suppurch(supid, purid, pdate, balance, div) VALUES('{$sup['supid']}', '{$pur['purnum']}', '{$DAte}', '{$retot}', '" . USER_DIV . "')";
        $purcRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    /* End Transactions */
    # commit updating
    // pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
    /* Update items found in ther linked purchase */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    db_conn($pur['spurprd']);
    $stab = $pur['spurtype'] == "int" ? "purch_int" : "purchases";
    $itab = $pur['spurtype'] == "int" ? "purint_items" : "pur_items";
    # Get purchase info
    $sql = "SELECT * FROM {$stab} WHERE purnum = '{$pur['spurnum']}' AND div = '" . USER_DIV . "'";
    $spurRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($spurRslt) < 1) {
        return "<li> - purchase Not Found</li>";
    }
    $spur = pg_fetch_array($spurRslt);
    $purs = explode(",", $pur['purs']);
    $TSUB = 0;
    foreach ($purs as $purID) {
        $purID += 0;
        db_connect();
        $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $p = pg_fetch_array($srchRslt);
            $TSUB += $p['subtot'];
            $Sl = "SELECT sum(unitcost) -sum(svat) as non FROM pur_items WHERE purid='{$p['purid']}' AND stkid=0";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $pi = pg_fetch_array($Ri);
            $pi = $pi['non'];
        }
        $sql = "SELECT * FROM movpurch WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $res = pg_fetch_array($srchRslt);
            db_conn($res['prd']);
            $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
            $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
            if (pg_numrows($srchRslt) > 0) {
                $p = pg_fetch_array($srchRslt);
                $TSUB += $p['subtot'];
                $Sl = "SELECT sum(unitcost)-sum(svat) as non FROM pur_items WHERE purid='{$p['purid']}' AND stkid=0";
                $Ri = db_exec($Sl) or errDie("Unable to get data.");
                $pi = pg_fetch_array($Ri);
                $pi = $pi['non'];
            } else {
                db_conn($res['prd']);
                $sql = "SELECT * FROM purch_int WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
                $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
                if (pg_numrows($srchRslt) > 0) {
                    $p = pg_fetch_array($srchRslt);
                    $TSUB += $p['subtot'];
                    // 					$Sl="SELECT sum(unitcost)-sum(svat) as non FROM purint_items WHERE purid='$p[purid]' AND stkid=0";
                    //
                    // 					$Ri=db_exec($Sl) or errDie("Unable to get data.");
                    // 					$pi=pg_fetch_array($Ri);
                    // 					$pi=$pi['non'];
                    $pi = 0;
                }
            }
        }
        if (!isset($pi)) {
            $pi = 0;
        }
        $TSUB -= $pi;
    }
    $purs = explode(",", $pur['purs']);
    foreach ($purs as $purID) {
        $itab = "pur_items";
        $purID += 0;
        //print $purID;
        db_connect();
        $sql = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $pur['spurprd'] = "cubit";
        }
        $sql = "SELECT * FROM movpurch WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
        $srchRslt = db_exec($sql) or errDie("Unable to retrieve purchases from database.");
        if (pg_numrows($srchRslt) > 0) {
            $res = pg_fetch_array($srchRslt);
            db_conn($res['prd']);
            $pur['spurprd'] = $res['prd'];
        }
        db_conn($pur['spurprd']);
        $test = $pur['spurprd'];
        $test += 0;
        if ($test != 0) {
            $s = "SELECT * FROM purchases WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
            $q = db_exec($s) or errDie("Unable to retrieve purchases from database.");
            if (pg_num_rows($q) > 0) {
                $p = pg_fetch_array($q);
                $purID = $p['purid'];
            } else {
                $s = "SELECT * FROM purch_int WHERE purnum = '{$purID}' AND div = '" . USER_DIV . "'";
                $q = db_exec($s) or errDie("Unable to retrieve purchases from database.");
                if (pg_num_rows($q) > 0) {
                    $p = pg_fetch_array($q);
                    $purID = $p['purid'];
                    $itab = "purint_items";
                }
            }
        }
        # Get selected stock
        $sql = "SELECT * FROM {$itab} WHERE purid = '{$purID}' AND div = '" . USER_DIV . "' AND stkid!=0";
        $sstkdRslt = db_exec($sql);
        while ($sstk = pg_fetch_array($sstkdRslt)) {
            if ($pur['spurtype'] == "int") {
                $csamt = sprint($sstk['amt'] / $TSUB * ($retot - $vatamt));
            } else {
                if ($spur['vatinc'] == "yes") {
                    $csamt = sprint(($sstk['amt'] - $sstk['svat']) / $TSUB * ($retot - $vatamt));
                } else {
                    $csamt = sprint($sstk['amt'] / $TSUB * ($retot - $vatamt));
                }
            }
            db_connect();
            # get selected stock
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            /* Code insert */
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT * FROM warehouses WHERE whid = '{$stkt['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $tot_post += $csamt;
            writetrans($wh['stkacc'], $supacc, $pdate, $refnum, $csamt, "Non-Stock Purchase No. {$pur['purnum']} Received {$detadd}.");
            /* End code insert */
            db_connect();
            if ($stkt['units'] != 0) {
                $sql = "UPDATE stock SET csamt = (csamt + '{$csamt}'), csprice = (csamt/units) WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            } else {
                $sql = "UPDATE stock SET csamt = (csamt + '{$csamt}') WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
            }
            $sdate = $pur['pdate'];
            stockrec($stkt['stkid'], $stkt['stkcod'], $stkt['stkdes'], 'dt', $sdate, 0, $csamt, "Cost Increased with Non Stock Purchase No. {$pur['purnum']}");
            # get selected stock
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $stktRslt = db_exec($sql);
            $stkt = pg_fetch_array($stktRslt);
            # $csprice = round(($stk['csamt']/$stk['units']), 2);
            if ($stkt['units'] > 0) {
                $csprice = round($stkt['csamt'] / $stkt['units'], 2);
            } else {
                $csprice = round($stkt['csprice'], 2);
            }
            # update stock(csprice = (csamt/units))
            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$sstk['stkid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        }
    }
    //exit;
    /*
    		db_conn($pur['spurprd']);
    		# Get selected stock
    		$sql = "SELECT * FROM $itab WHERE purid = '$spur[purid]' AND div = '".USER_DIV."' AND stkid!=0";
    		$sstkdRslt = db_exec($sql);
    		while($sstk = pg_fetch_array($sstkdRslt)){
    			if($pur['spurtype'] == "int"){
    				$csamt = sprint(($sstk['amt']/$TSUB) * ($retot - $vatamt));
    			}else{
    				if($spur['vatinc'] == "yes"){
    					$csamt = sprint((($sstk['amt'] - $sstk['svat'])/$TSUB) * ($retot - $vatamt));
    				}else{
    					$csamt = sprint((($sstk['amt'])/$TSUB) * ($retot - $vatamt));
    				}
    			}
    
    			db_connect();
    			# get selected stock
    			$sql = "SELECT * FROM stock WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$stktRslt = db_exec($sql);
    			$stkt = pg_fetch_array($stktRslt);
    
    			/* Code insert
    				# get warehouse name
    				db_conn("exten");
    				$sql = "SELECT * FROM warehouses WHERE whid = '$stkt[whid]' AND div = '".USER_DIV."'";
    				$whRslt = db_exec($sql);
    				$wh = pg_fetch_array($whRslt);
    
    				$tot_post+=$csamt;
    
    				writetrans($wh['stkacc'], $supacc, date("d-m-Y"), $refnum, $csamt, "Non-Stock Purchase No. $pur[purnum] Received $detadd.");
    			/* End code insert
    
    			db_connect();
    			if($stkt['units'] <> 0){
    				$sql = "UPDATE stock SET csamt = (csamt + '$csamt'), csprice = (csamt/units) WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    				$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    			}else{
    				$sql = "UPDATE stock SET csamt = (csamt + '$csamt') WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    				$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    			}
    			$sdate = $pur['pdate'];
    			stockrec($stkt['stkid'], $stkt['stkcod'], $stkt['stkdes'], 'dt', $sdate, 0, $csamt, "Cost Increased with Non Stock Purchase No. $pur[purnum]");
    
    			# get selected stock
    			db_connect();
    			$sql = "SELECT * FROM stock WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$stktRslt = db_exec($sql);
    			$stkt = pg_fetch_array($stktRslt);
    
    			# $csprice = round(($stk['csamt']/$stk['units']), 2);
    			if($stkt['units'] > 0){
    				$csprice = round(($stkt['csamt']/$stkt['units']), 2);
    			}else{
    				$csprice = round($stkt['csprice'], 2);
    			}
    
    			# update stock(csprice = (csamt/units))
    			$sql = "UPDATE stock SET csprice = '$csprice' WHERE stkid = '$sstk[stkid]' AND div = '".USER_DIV."'";
    			$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
    		}
    */
    $diff = sprint($retot - $tot_post);
    if ($diff > 0) {
        writetrans($cvacc, $supacc, $sdate, $refnum, $diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']}");
    } elseif ($diff < 0) {
        writetrans($supacc, $cvacc, $sdate, $refnum, -$diff, "Cost Variance for Non stock Purchase No. {$pur['purnum']}");
    }
    /* End Update items found in ther linked purchase */
    /* Start moving if purchase received */
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return "<li>- purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    if ($pur['received'] == "y") {
        if (isset($supid)) {
            $ctyp = "sup";
            $typeid = $supid;
        } elseif (isset($deptid)) {
            $ctyp = "led";
            $typeid = $deptid;
        } else {
            $ctyp = "ot";
            $typeid = 0;
        }
        # copy purchase
        db_conn($pur['prd']);
        $pur['spurprd'] += 0;
        $pur['spurnum'] += 0;
        $sql = "INSERT INTO nons_purchases(purid, deptid, supplier, supaddr, terms, pdate, ddate, shipchrg, subtot, total, balance, vatinc, vat, remarks, refno, received, done, div, purnum,ctyp,typeid,spurprd,spurnum)";
        $sql .= " VALUES('{$purid}', '{$pur['deptid']}', '{$pur['supplier']}',  '{$pur['supaddr']}', '{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', '{$pur['purnum']}','{$ctyp}','{$typeid}','{$pur['spurprd']}','{$pur['spurnum']}')";
        $rslt = db_exec($sql) or errDie("Unable to insert Non-Stock Purchase to Cubit.", SELF);
        db_connect();
        # Get selected stock
        $sql = "SELECT * FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktcRslt = db_exec($sql);
        while ($stktc = pg_fetch_array($stktcRslt)) {
            # Insert purchase items
            db_conn($pur['prd']);
            $sql = "INSERT INTO nons_pur_items(purid, cod, des, qty, unitcost, amt, ddate, div,svat) VALUES('{$purid}', '{$stktc['cod']}', '{$stktc['des']}', '{$stktc['qty']}', '{$stktc['unitcost']}', '{$stktc['amt']}', '{$stktc['ddate']}', '" . USER_DIV . "','{$stktc['svat']}')";
            $rslt = db_exec($sql) or errDie("Unable to insert purchase items to Cubit.", SELF);
        }
        db_connect();
        # Remove the purchase from running DB
        $sql = "DELETE FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
        # Remove those purchase items from running DB
        $sql = "DELETE FROM nons_pur_items WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $delRslt = db_exec($sql) or errDie("Unable to update int purchases information in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving purchase received */
    $cc = "<script> CostCenter('ct', 'Non-Stock Purchase', '{$pdate}', 'Non Stock Purchase No.{$pur['purnum']}', '" . ($retot - $vatamt) . "', ''); </script>";
    // Final Layout
    $write = "\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Non-Stock Purchase received</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Non-Stock Purchase receipt has been recorded.</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<p>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><a href='nons-purchase-view.php'>View purchases</a></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t</table>";
    return $write;
}
function details($_GET)
{
    # get vars
    foreach ($_GET as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    db_connect();
    # Get invoice info
    $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class=err>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    /* --- Start some checks --- */
    # check if stock was selected(yes = put done button)
    /* --- End some checks --- */
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    # Put in product
    while ($stk = pg_fetch_array($stkdRslt)) {
        $products .= "<tr valign=top><td>{$stk['description']}</td><td>{$stk['qty']}</td><td>{$stk['unitcost']}</td><td>" . CUR . " {$stk['amt']}</td></tr>";
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint("%0.2f", $inv['subtot']);
    $VAT = sprint("%0.2f", $inv['vat']);
    $TOTAL = sprint("%0.2f", $inv['total']);
    /* --- End Some calculations --- */
    /* - Start Hooks - */
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    /* - End Hooks - */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    $refnum = getrefnum();
    /*refnum*/
    /* --- Updates ---- */
    db_connect();
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $real_invid = divlastid('inv', USER_DIV);
    $sql = "UPDATE nons_invoices SET done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # get selected stock in this invoice
    $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    /* -- Format the remarks boxlet -- */
    $inv["remarks"] = "<table border=1><tr><td>Remarks:<br>{$inv['remarks']}</td></tr></table>";
    /* -- Final Layout -- */
    $details = "<center><h2>Tax Invoice</h2>\r\n\t<table cellpadding='0' cellspacing='4' border=0 width=750>\r\n\t<tr><td valign=top width=30%>\r\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0>\r\n\t\t\t<tr><td>{$inv['cusname']}</td></tr>\r\n\t\t\t<tr><td>" . nl2br($inv['cusaddr']) . "</td></tr>\r\n\t\t\t<tr><td>(Vat No. {$inv['cusvatno']})</td></tr>\r\n\t\t</table>\r\n\t</td><td valign=top width=30%>\r\n\t\t" . COMP_NAME . "<br>\r\n\t\t" . COMP_ADDRESS . "<br>\r\n\t\t" . COMP_TEL . "<br>\r\n\t\t" . COMP_FAX . "<br>\r\n\t</td><td width=20%>\r\n\t\t<img src='compinfo/getimg.php' width=230 height=47>\r\n\t</td><td valign=bottom align=right width=20%>\r\n\t\t<table cellpadding='2' cellspacing='0' border=1 bordercolor='#000000'>\r\n\t\t\t<tr><td><b>Invoice No.</b></td><td valign=center>{$inv['invnum']}</td></tr>\r\n\t\t\t<tr><td><b>Invoice Date</b></td><td valign=center>{$inv['sdate']}</td></tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td><br></td></tr>\r\n\t<tr><td colspan=4>\r\n\t<table cellpadding='5' cellspacing='0' border=1 width=100% bordercolor='#000000'>\r\n\t\t<tr>\r\n\t\t\t<th width='5%'>#</th>\r\n\t\t\t<th width='65%'>DESCRIPTION</th>\r\n\t\t\t<th width='10%'>QTY</th>\r\n\t\t\t<th width='10%'>UNIT PRICE</th>\r\n\t\t\t<th width='10%'>AMOUNT</th>\r\n\t\t<tr>\r\n\t\t{$products}\r\n\t</table>\r\n\t</td></tr>\r\n\t<tr><td>\r\n\t{$inv['remarks']}\r\n\t</td><td align=right colspan=3>\r\n\t\t<table cellpadding='5' cellspacing='0' border=1 width=50% bordercolor='#000000'>\r\n\t\t\t<tr><td><b>SUBTOTAL</b></td><td align=right>" . CUR . " {$SUBTOT}</td></tr>\r\n\t\t\t<tr><td><b>VAT @ \$" . TAX_VAT . "%</b></td><td align=right>" . CUR . " {$VAT}</td></tr>\r\n\t\t\t<tr><th><b>GRAND TOTAL<b></th><td align=right>" . CUR . " {$TOTAL}</td></tr>\r\n\t\t</table>\r\n\t</td></tr>\r\n\t<tr><td><br></td></tr>\r\n\t<tr><td>\r\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=1>\r\n        \t<tr><th>VAT No.</th><td align=center>" . COMP_VATNO . "</td></tr>\r\n        </table>\r\n\t</td><td><br></td></tr>\r\n\t</table></center>";
    $OUTPUT = $details;
    require "tmpl-print.php";
}