Пример #1
0
function write($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($bank as $key => $value) {
        $v->isOk($batchid[$key], "num", 1, 10, "Invalid Batch ID.[{$key}]");
        $v->isOk($ctaccid[$key], "num", 1, 50, "Invalid Account to be Credited.[{$key}]");
        $v->isOk($dtaccid[$key], "num", 1, 50, "Invalid Account to be Debited.[{$key}]");
        $v->isOk($refnum[$key], "num", 1, 10, "Invalid Reference number.[{$key}]");
        $v->isOk($amount[$key], "float", 1, 20, "Invalid Amount.[{$key}]");
        $v->isOk($descript[$key], "string", 0, 255, "Invalid Details.[{$key}]");
        $datea = explode("-", $date[$key]);
        if (count($datea) == 3) {
            if (!checkdate($datea[1], $datea[2], $datea[0])) {
                $v->isOk($date[$key], "num", 1, 1, "Invalid date.");
            }
        } else {
            $v->isOk($date[$key], "num", 1, 1, "Invalid date.");
        }
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    foreach ($bank as $key => $value) {
        // Accounts details
        $dtaccRs = get("core", "accname, topacc, accnum", "accounts", "accid", $dtaccid[$key]);
        $dtacc[$key] = pg_fetch_array($dtaccRs);
        $ctaccRs = get("core", "accname, topacc, accnum", "accounts", "accid", $ctaccid[$key]);
        $ctacc[$key] = pg_fetch_array($ctaccRs);
    }
    // Start layout
    $write = "\n\t\t\t\t<center>\n\t\t\t\t<h3>Journal transactions have been recorded</h3>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t<th>Ref num</th>\n\t\t\t\t\t\t<th>Debit</th>\n\t\t\t\t\t\t<th>Credit</th>\n\t\t\t\t\t\t<th>Amount</th>\n\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t<th>VAT Amount</th>\n\t\t\t\t\t\t<th>Total Transaction Amount</th>\n\t\t\t\t\t</tr>";
    $cc = "";
    foreach ($bank as $key => $value) {
        $write .= "\n\t\t\t\t\t\t<tr bgcolor=" . bgcolorg() . ">\n\t\t\t\t\t\t\t<td>{$date[$key]}</td>\n\t\t\t\t\t\t\t<td>{$refnum[$key]}</td>\n\t\t\t\t\t\t\t<td valign='center'>" . $dtacc[$key]['topacc'] . "/" . $dtacc[$key]['accnum'] . " " . $dtacc[$key]['accname'] . "</td>\n\t\t\t\t\t\t\t<td valign='center'>" . $ctacc[$key]['topacc'] . "/" . $ctacc[$key]['accnum'] . " " . $ctacc[$key]['accname'] . "</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$amount[$key]}</td>\n\t\t\t\t\t\t\t<td>{$descript[$key]}</td>";
        if (isset($chrgvat[$value])) {
            $datea = explode("-", $date[$key]);
            $cdate = "{$datea['2']}-{$datea['1']}-{$datea['0']}";
            $vataccRs = get("core", "*", "accounts", "accid", $vataccid[$value]);
            $vatacc = pg_fetch_array($vataccRs);
            $vataccRs = get("core", "*", "accounts", "accid", $vatdedacc[$value]);
            $vdedacc = pg_fetch_array($vataccRs);
            //$VATP = TAX_VAT;
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$key]}'";
            $Ri = db_exec($Sl);
            $vd = pg_fetch_array($Ri);
            $VATP = $vd['vat_amount'];
            # if vat must be charged
            if ($vatinc[$value] == "no") {
                $vatamt[$value] = sprint($VATP / 100 * $amount[$key]);
                $amt[$key] = sprint($amount[$key]);
                $totamt = sprint($amount[$key] + $vatamt[$value]);
            } else {
                $vatamt[$value] = sprint($amount[$key] / ($VATP + 100) * $VATP);
                $amt[$key] = sprint($amount[$key] - $vatamt[$value]);
                $totamt = sprint($amount[$key]);
            }
            # Check VAt Deductable account
            if ($vatdedacc[$value] == $dtaccid[$key]) {
                db_connect();
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$key]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return "Please select the vatcode";
                }
                $vd = pg_fetch_array($Ri);
                vatr($vd['id'], $date[$key], "INPUT", $vd['code'], $refnum[$key], "{$descript[$key]} VAT", -$totamt, -$vatamt[$value]);
                writetrans($vataccid[$value], $ctaccid[$key], $date[$key], $refnum[$key], $vatamt[$value], $descript[$key] . "  VAT");
                writetrans($dtaccid[$key], $ctaccid[$key], $date[$key], $refnum[$key], $amt[$key], $descript[$key]);
            } elseif ($vatdedacc[$value] == $ctaccid[$key]) {
                db_connect();
                $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcodes[$key]}'";
                $Ri = db_exec($Sl);
                if (pg_num_rows($Ri) < 1) {
                    return "Please select the vatcode";
                }
                $vd = pg_fetch_array($Ri);
                vatr($vd['id'], $date[$key], "OUTPUT", $vd['code'], $refnum[$key], "{$descript[$key]} VAT", $totamt, $vatamt[$value]);
                writetrans($dtaccid[$key], $vataccid[$value], $date[$key], $refnum[$key], $vatamt[$value], $descript[$key] . "  VAT");
                writetrans($dtaccid[$key], $ctaccid[$key], $date[$key], $refnum[$key], $amt[$key], $descript[$key]);
            }
            $write .= "\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$vatamt[$value]}</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$totamt}</td>";
        } else {
            $totamt[$key] = sprint($amount[$key]);
            # Write normal transaction
            writetrans($dtaccid[$key], $ctaccid[$key], $date[$key], $refnum[$key], $totamt[$key], $descript[$key]);
            $write .= "<td>0</td><td>" . CUR . " {$totamt[$key]}</td>";
        }
        $write .= "</tr>";
        db_connect();
        $sql = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '" . USER_DIV . "' LIMIT 1";
        $banks = db_exec($sql);
        if (pg_numrows($banks) < 1) {
            return "<li class='err'> There are no accounts held at the selected Bank.\n\t\t\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
        }
        $barr = pg_fetch_array($banks);
        $bankid = $barr['bankid'];
        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);
        $cc_trantype = cc_TranTypeAcc($dtaccid[$key], $ctaccid[$key]);
        if ($cc_trantype != false) {
            $cc .= "\n\t\t\t\t\t<script>\n\t\t\t\t\t\tCostCenter('{$cc_trantype}', 'Batch Journal', '{$date[$key]}', '{$descript[$key]}', '{$amount[$key]}', '../');\n\t\t\t\t\t</script>";
        } else {
            $cc .= "";
        }
        db_conn('core');
        #process complete ... remove entry
        $rem_sql = "DELETE FROM batch WHERE batchid = '{$batchid[$key]}'";
        $run_sql = db_exec($rem_sql) or errDie("Unable to remove batch entry.");
    }
    $write .= "\n\t\t\t\t\t\t</table>\n\t\t\t\t\t\t{$cc}\n\t\t\t\t\t\t<br>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='25%'>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='trans-batch.php'>Add Journal Transactions to batch</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='batch-view.php'>View batch Entries</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t</table>";
    return $write;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (isset($back)) {
        return edit($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($stkid, "num", 1, 50, "Invalid stock id.");
    $v->isOk($whid, "num", 1, 50, "Invalid stock id.");
    $v->isOk($unitnum, "num", 1, 50, "Invalid number of units.");
    $v->isOk($cost, "float", 1, 50, "Invalid cost amount per unit.");
    $v->isOk($cacc, "num", 1, 50, "Invalid contra account.");
    $v->isOk($tipo, "string", 1, 50, "Invalid type.");
    $v->isOk($det, "string", 0, 255, "Invalid Details.");
    $v->isOk($date, "string", 4, 14, "Invalid date.");
    # check if duplicate serial number selected, remove blanks
    if (isset($sernos)) {
        if (!ext_isUnique(ext_remBlnk($sernos))) {
            $v->isOk("##", "num", 0, 0, "Error : Serial Numbers must be unique per line item.");
        }
    }
    # 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;
    }
    # Select Stock
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.</li>";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    if ($stk['units'] < 0) {
        $min_stock = abs($stk['units']);
        if ($unitnum < $min_stock) {
            $min_stock = $unitnum;
        }
    } else {
        $min_stock = 0;
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    $refnum = getrefnum();
    # calculate actual cost amount
    $temp = $cost;
    $cost = sprint($cost * $unitnum);
    if ($tipo == 'Increase') {
        # Update Stock
        db_connect();
        $sql = "UPDATE stock\n\t\t\t\tSET units = (units + '{$unitnum}'),\n\t\t\t\t\tlcsprice = '{$temp}',\n\t\t\t\t\tcsamt = (csamt + {$cost}),\n\t\t\t\t\tcsprice = (\n\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\tCASE WHEN (units != -{$unitnum}) THEN (csamt+{$cost})/(units+{$unitnum})\n\t\t\t\t\t\t\tELSE 0\n\t\t\t\t\t\t\tEND\n\t\t\t\t\t\tFROM cubit.stock\n\t\t\t\t\t\tWHERE stkid='{$stkid}' AND div='" . USER_DIV . "'\n\t\t\t\t\t)\n\t\t\t\tWHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        //		$rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.",SELF);
        $sdate = $date;
        recordtrans('stock', '1', '1', $sdate, $unitnum, $cost, $temp, '', $stkid);
        db_connect();
        if ($unitnum == 0) {
            $csprice = 0;
        } else {
            $csprice = sprint($cost / $unitnum);
        }
        recordtrans('stock', '1', '0', $sdate, $unitnum, $cost, $csprice, $det, $stk['stkid']);
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        //stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $sdate, $unitnum, $cost, $det);
        $sql = "INSERT INTO stockrec (edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\tVALUES('{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'inc', '{$unitnum}', '{$cost}', '{$csprice}', '{$det}', '" . USER_DIV . "')";
        //		$recRslt = db_exec($sql);
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
        if (pg_numrows($stkRslt) < 1) {
            return "<li> Invalid Stock ID.";
        } else {
            $stk = pg_fetch_array($stkRslt);
        }
        # balance transaction
        # Debit STock account and Credit Contra Account
        recordtrans('journal', $wh['stkacc'], $cacc, $date, $refnum, $cost, '0', $det);
        //writetrans($wh['stkacc'], $cacc, $date, $refnum, $cost, $det);
        $cc_trantype = cc_TranTypeAcc($wh['stkacc'], $cacc);
    } else {
        if ($tipo == 'Decrease') {
            # Update Stock
            db_connect();
            $sql = "UPDATE stock SET csamt = (csamt - {$cost}), units = (units - '{$unitnum}') WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
            //		$rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.",SELF);
            //$sdate = date("Y-m-d");
            $sdate = $date;
            recordtrans('stock', '0', '0', $sdate, $unitnum, $cost, '0', $det, $stkid);
            recordtrans('stock', '0', '1', $sdate, $unitnum, $cost, $csprice, $det, $stk['stkid']);
            # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
            //stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $sdate, $unitnum, $cost, $det);
            db_connect();
            if ($unitnum == 0) {
                $csprice = 0;
            } else {
                $csprice = sprint($cost / $unitnum);
            }
            $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\tVALUES('{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'dec', '-{$unitnum}', '{$cost}', '{$csprice}', '{$det}', '" . USER_DIV . "')";
            //$recRslt = db_exec($sql);
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
            if (pg_numrows($stkRslt) < 1) {
                return "<li> Invalid Stock ID.</li>";
            } else {
                $stk = pg_fetch_array($stkRslt);
            }
            # Units
            if ($stk['units'] != 0) {
                $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
                //			$rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.",SELF);
            } else {
                $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
                //			$rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.",SELF);
            }
            if (isset($sernos)) {
                foreach ($sernos as $skey => $serno) {
                    ext_OutSer($serno, $stkid, $det, $refnum, "tran");
                }
            }
            recordtrans('journal', $cacc, $wh['stkacc'], $date, $refnum, $cost, '0', $det);
            #  Debit Contra Account and Credit Stock account
            //writetrans($cacc, $wh['stkacc'], $date, $refnum, $cost, $det);
            $cc_trantype = cc_TranTypeAcc($cacc, $wh['stkacc']);
        }
    }
    if ($cc_trantype != false) {
        $cc = "<script> CostCenter('{$cc_trantype}', 'Stock Transaction', '{$date}', '{$det}', '{$cost}', ''); </script>";
    } else {
        $cc = "";
    }
    $write = "\n\t\t\t{$cc}\n\t\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Stock Balance Transaction</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>Stock Balance Transaction for stock, {$stk['stkdes']} ({$stk['stkcod']}) has been successfully recorded.</td>\n\t\t\t\t</tr>\n\t\t\t</table>" . mkQuickLinks(ql("stock-add.php", "Add Stock"), ql("stock-view.php", "View Stock"));
    return $write;
}
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)
{
    extract($_POST);
    $vatcode += 0;
    if (isset($back)) {
        unset($_POST["back"]);
        if ($chrgvat == "yes") {
            return slctVatacc($_POST);
        } elseif (isset($details)) {
            return details($_POST);
        } else {
            return details2($_POST);
        }
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($ctaccid, "num", 1, 50, "Invalid Account to be Credited.");
    $v->isOk($dtaccid, "num", 1, 50, "Invalid Account to be Debited.");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    $v->isOk($amount, "float", 1, 20, "Invalid Amount.");
    $v->isOk($details, "string", 0, 255, "Invalid Details.");
    $v->isOk($author, "string", 1, 30, "Invalid Authorising person name.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid charge vat option.");
    if ($chrgvat == 'yes') {
        $v->isOk($vataccid, "num", 1, 50, "Invalid VAT Account number.");
        $v->isOk($vatdedacc, "num", 1, 50, "Invalid VAT Deductable Account number.");
        $v->isOk($vatamt, "float", 1, 11, "Invalid VAT Amount.");
        $v->isOk($vatinc, "string", 1, 3, "Invalid VAT inclusive selection.");
    }
    if ($v->isError()) {
        $err = $v->genErrors();
        return confirm($_POST, $err);
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # Accounts details
    $dtaccRs = get("core", "*", "accounts", "accid", $dtaccid);
    $dtacc = pg_fetch_array($dtaccRs);
    $ctaccRs = get("core", "*", "accounts", "accid", $ctaccid);
    $ctacc = pg_fetch_array($ctaccRs);
    if ($chrgvat == 'yes') {
        if ($vatinc == 'yes') {
            # Calculate amount
            $amt = sprint($amount - $vatamt);
            $totamt = sprint($amount);
        } else {
            # Calculate amount
            $amt = sprint($amount);
            $totamt = sprint($amount + $vatamt);
        }
        $datea = explode("-", $date);
        //		$cdate="$datea[2]-$datea[1]-$datea[0]";
        $cdate = $date;
        # Check VAt Deductable account
        if ($vatdedacc == $dtaccid) {
            db_connect();
            $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode";
            }
            $vd = pg_fetch_array($Ri);
            ## PROCESS THIS VAT
            //vatr($vd['id'],$cdate,"INPUT",$vd['code'],$refnum,"$details VAT",-$totamt,-$vatamt);
            recordtrans('journal', '0', '0', $cdate, $refnum, -$totamt, -$vatamt, "{$details} VAT" . "|{$vd['id']}|INPUT|{$vd['code']}", '0');
            ## PROCESS THIS WRITETRANS
            recordtrans('journal', $vataccid, $ctaccid, $date, $refnum, $vatamt, '0', $details . "  VAT");
            //writetrans($vataccid, $ctaccid, $date, $refnum, $vatamt, $details."  VAT");
            ## PROCESS THIS WRITETRANS
            recordtrans('journal', $dtaccid, $ctaccid, $date, $refnum, $amt, '0', $details);
            //writetrans($dtaccid, $ctaccid, $date, $refnum, $amt, $details);
        } elseif ($vatdedacc == $ctaccid) {
            db_connect();
            $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode";
            }
            $vd = pg_fetch_array($Ri);
            ## PROCESS THIS VAT
            //vatr($vd['id'],$cdate,"OUTPUT",$vd['code'],$refnum,"$details.  VAT",$totamt,$vatamt);
            recordtrans('journal', '0', '0', $cdate, $refnum, $totamt, $vatamt, "{$details} VAT" . "|{$vd['id']}|OUTPUT|{$vd['code']}");
            ## PROCESS THIS WRITETRANS
            recordtrans('journal', $dtaccid, $vataccid, $date, $refnum, $vatamt, '0', $details . "  VAT");
            //writetrans($dtaccid, $vataccid, $date, $refnum, $vatamt, $details."  VAT");
            ## PROCESS THIS WRITETRANS
            recordtrans('journal', $dtaccid, $ctaccid, $date, $refnum, $amt, $details);
            //writetrans($dtaccid, $ctaccid, $date, $refnum, $amt, $details);
        }
    } else {
        $totamt = sprint($amount);
        # Write normal transaction
        recordtrans('journal', $dtaccid, $ctaccid, $date, $refnum, $totamt, '0', $details);
        //writetrans($dtaccid,$ctaccid, $date, $refnum, $totamt, $details);
    }
    if ($chrgvat == 'yes') {
        $vataccRs = get("core", "*", "accounts", "accid", $vataccid);
        $vatacc = pg_fetch_array($vataccRs);
        $vataccnum = "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT Amount</td>\n\t\t\t\t\t\t\t<td>{$vatamt}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Total Transaction Amount</td>\n\t\t\t\t\t\t\t<td><b>{$totamt}</b></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>VAT Account</td>\n\t\t\t\t\t\t\t<td>{$vatacc['topacc']}/{$vatacc['accnum']} - {$vatacc['accname']}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t";
        $amt = $totamt - $vatamt;
    } else {
        $vataccnum = "";
        $amt = $amount;
    }
    if (cc_TranTypeAcc($dtaccid, $ctaccid) != false) {
        $cc_trantype = cc_TranTypeAcc($dtaccid, $ctaccid);
        $cc = "<script> CostCenter('{$cc_trantype}', 'Journal Entry', '{$date}', '{$details}', '{$amt}', '../'); </script>";
    } else {
        $cc = "";
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Start layout
    $write = "\n\t\t\t\t<center>\n\t\t\t\t{$cc}\n\t\t\t\t<script>\n\t\t\t\t\tparent.window.reload;\n\t\t\t\t</script>\n\t\t\t\t<h3>Journal transaction has been recorded</h3>\n\t\t\t\t<table " . TMPL_tblDflts . " width='500'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td width='50%'><h3>Debit</h3></td>\n\t\t\t\t\t\t<td width='50%'><h3>Credit</h3></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>{$dtacc['topacc']}/{$dtacc['accnum']} - {$dtacc['accname']}</td>\n\t\t\t\t\t\t<td>{$ctacc['topacc']}/{$ctacc['accnum']} - {$ctacc['accname']}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t" . TBL_BR . "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Amount</td>\n\t\t\t\t\t\t<td><b>{$amount}</b></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t{$vataccnum}\n\t\t\t\t</table>" . mkQuickLinks(ql("../reporting/index-reports.php", "Financials"), ql("../core/trans-new.php", "Journal Transactions"));
    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($reference, "string", 0, 255, "Invalid Reference.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amount, "float", 1, 40, "Invalid amount.");
    $v->isOk($vat, "float", 1, 10, "Invalid vat amount.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid vat option.");
    $v->isOk($accinv, "string", 1, 255, "Invalid account number (account involved).");
    $vatcode += 0;
    # 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;
    }
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    #refnum
    $refnum = getrefnum();
    # Start rattling vat
    //	$vatp = TAX_VAT;
    $totamt = $amount;
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}' AND zero='Yes'";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    if (pg_num_rows($Ri) > 0) {
        $chrgvat = "no";
    }
    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);
    $vatp = $vd['vat_amount'];
    if ($chrgvat == "exc") {
        $totamt += $vat;
    } elseif ($chrgvat == "inc") {
        //$vat=sprint((sprint($amount*100/(100+$vatp)))*$vatp/100);
        $amount = sprint($totamt - $vat);
        //$vat = sprint(($amount/(100 + $vatp)) * $vatp);
    } else {
        $vat = "No VAT";
    }
    /*if($chrgvat == "exc"){
    		$vat = sprint(($vatp/100) * $amount);
    		$totamt += $vat;
    	} elseif($chrgvat == "inc"){
    		$vat=sprint((sprint($amount*100/(100+$vatp)))*$vatp/100);
    		$amount=sprint($amount*100/(100+$vatp));
    		//$vat = sprint(($amount/(100 + $vatp)) * $vatp);
    	}else{
    		$vat = "No VAT";
    	}
    
    // 	if($chrgvat == "exc"){
    // 		$vat = sprint(($vatp/100) * $amount);
    // 		$totamt += $vat;
    // 	} elseif($chrgvat == "inc"){
    // 		//$vat = sprint((sprint($amount/(100 + $vatp))) * $vatp);
    // 		$vat = sprint((sprint($amount/114*100)*$vatp/100));
    // 		$amount = sprint($amount/114*100);
    // 	}else{
    // 		$vat = 0;
    // 	}
    
    	/* -- 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 -- */
    $cheqnum = 0 + $cheqnum;
    $vat += 0;
    $vatcode += 0;
    if (isset($batch)) {
        db_conn('cubit');
        $Sl = "UPDATE batch_cashbook SET bankid='{$bankid}', date='{$date}', name='{$name}', descript='{$descript}', reference = '{$reference}', cheqnum='{$cheqnum}', amount='{$totamt}', vat='{$vat}', chrgvat='{$chrgvat}', accinv='{$accinv}', vatcode='{$vatcode}' WHERE cashid = '{$id}'";
        $Ri = db_exec($Sl) or errDie("Unable to update cashbook");
        # Status report
        $write = "\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Bank Payment</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t\t<td>Bank Payment edited.</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>";
    } else {
        # Record the payment record
        db_connect();
        $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div, reference, vatcode) VALUES ('{$bankid}', 'withdrawal', '{$date}', '{$name}', '{$descript}', '{$cheqnum}', '{$totamt}', '{$vat}', '{$chrgvat}', 'no', '{$accinv}', '" . USER_DIV . "', '{$reference}', '{$vatcode}')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        vatr($vd['id'], $date, "INPUT", $vd['code'], $refnum, $descript, -($amount + $vat), -$vat);
        # DT(account involved), CT(bank)
        writetrans($accinv, $banklnk['accnum'], $date, $refnum, $amount, $descript);
        if ($vat != 0) {
            # DT(VAT), CT(Bank)
            writetrans($vatacc, $banklnk['accnum'], $date, $refnum, $vat, $descript);
        }
        if (cc_TranTypeAcc($accinv, $banklnk['accnum']) != false) {
            $cc_trantype = cc_TranTypeAcc($accinv, $banklnk['accnum']);
            $cc = "<script> CostCenter('{$cc_trantype}', 'Bank Transaction', '{$date}', '{$descript}', '{$amount}', '../'); </script>";
        } else {
            $cc = "";
        }
        $dif = sprint($amount + $vat - $totamt);
        if ($dif > 0) {
            writetrans($banklnk['accnum'], $varacc, $date, $refnum, $dif, "Variance on bank payment Ref: {$refnum}");
        } elseif ($dif < 0) {
            $dif = $dif * -1;
            writetrans($varacc, $banklnk['accnum'], $date, $refnum, $dif, "Variance on bank payment Ref: {$refnum}");
        }
        # Status report
        $write = "\n\t\t\t\t\t{$cc}\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Bank Payment</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t\t\t<td>Bank Payment added to cash book.</td>\n\t\t\t\t\t\t</tr>\n\t\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>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    # get vars
    extract($_POST);
    $vatcode += 0;
    $vat += 0;
    # 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;
    }
    # Connect to database
    db_Connect();
    $sql = "SELECT * FROM pettycashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
    $cashRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.", SELF);
    $cash = pg_fetch_array($cashRslt);
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($cash['date']) >= strtotime($blocked_date_from) and strtotime($cash['date']) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    $refnum = getrefnum($cash['date']);
    # Check available funds
    $cashacc = gethook("accnum", "bankacc", "name", "Petty Cash");
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}' AND zero='Yes'";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    if (pg_num_rows($Ri) > 0) {
        $cash['chrgvat'] = "exc";
    }
    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);
    $VATP = $vd['vat_amount'];
    # If subtract vat
    if ($cash['chrgvat'] == "inc") {
        # get vat account
        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
        //		$VATP = TAX_VAT;
        //$VAT = sprint(($VATP/($VATP + 100)) * $cash['amount']);
        $VAT = $vat;
        $samount = $cash['amount'] - $VAT;
        //date("Y-m-d")
        # Write transaction
        writetrans($cash['accid'], $cashacc, $cash['date'], $refnum, $samount, $cash['det']);
        # Write VAT transaction
        writetrans($vatacc, $cashacc, $cash['date'], $refnum, $VAT, "VAT, " . $cash['det']);
        vatr($vd['id'], $cash['date'], "INPUT", $vd['code'], $refnum, "VAT, " . $cash['det'], -($samount + $VAT), -$VAT);
        # record vat statement
        /*
        db_connect();
        $sql = "INSERT INTO svatrec(edate, ref, amount, descript, div) VALUES('".date("Y-m-d")."', '$refnum', '-$VAT', 'VAT paid on Petty Cash requisition.', '".USER_DIV."')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.",SELF);
        */
    } elseif ($cash['chrgvat'] == "exc") {
        # get vat account
        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
        //		$VATP = TAX_VAT;
        //		$VAT = sprint(($VATP/100) * $cash['amount']);
        $VAT = $vat;
        $samount = $cash['amount'];
        $cash['amount'] += $VAT;
        # Write transaction
        $VAT = $vat;
        writetrans($cash['accid'], $cashacc, $cash['date'], $refnum, $samount, $cash['det']);
        # Write VAT transaction
        writetrans($vatacc, $cashacc, $cash['date'], $refnum, $VAT, "VAT, " . $cash['det']);
        vatr($vd['id'], $cash['date'], "INPUT", $vd['code'], $refnum, "VAT, " . $cash['det'], -($samount + $VAT), -$VAT);
        # record vat statement
        /*
        db_connect();
        $sql = "INSERT INTO svatrec(edate, ref, amount, descript, div) VALUES('".date("Y-m-d")."', '$refnum', '-$VAT', 'VAT paid on Petty Cash requisition.', '".USER_DIV."')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.",SELF);
        */
    } else {
        $samount = $cash['amount'];
        # Write transaction
        writetrans($cash['accid'], $cashacc, $cash['date'], $refnum, $samount, $cash['det']);
    }
    # Update
    db_connect();
    //	$date = date("Y-m-d");
    $date = $cash['date'];
    $sql = "\n\t\tINSERT INTO pettyrec (\n\t\t\tdate, type, det, amount, name, div\n\t\t) VALUES (\n\t\t\t'{$date}', 'Req', '{$cash['det']}', '-{$cash['amount']}', 'Cash Paid to : {$cash['name']}', '" . USER_DIV . "'\n\t\t)";
    $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    # Update
    $sql = "UPDATE pettycashbook SET approved = 'y',vatcode='{$vatcode}', vat_paid = '{$vat}',reced = 'no' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
    $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
    if (cc_TranTypeAcc($cash['accid'], $cashacc) != false) {
        $cc_trantype = cc_TranTypeAcc($cash['accid'], $cashacc);
        $cc = "<script> CostCenter('{$cc_trantype}', 'Petty Cash Requisition', '{$date}', '{$cash['det']}', '{$samount}', '../'); </script>";
    } else {
        $cc = "";
    }
    # status report
    $write = "\n\t\t{$cc}\n\t\t<table " . TMPL_tblDflts . " width='30%'>\n\t\t\t<tr>\n\t\t\t\t<th>Petty Cash Requisition Approved</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>Petty Cash Requisition has been approved .</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . " width='15%'>\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='petty-req-add.php'>Add Petty Cash Requisition</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='pettycashbook-view.php'>View Petty Cash Requisitions</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='../main.php'>Main Menu</a></td>\n\t\t\t</tr>\n\t\t</table>";
    return $write;
}
function bank($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cashid, "num", 1, 20, "Invalid Reference number.");
    $v->isOk("{$date_day}{$date_month}{$date_year}", "num", 6, 8, "Invalid date selected.");
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->addError("", "Invalid date selected. No such date possible.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    $seldate = "{$date_year}-{$date_month}-{$date_day}";
    $salconacc = gethook("accnum", "salacc", "name", "salaries control");
    # Get cash book record
    Db_Connect();
    $sql = "SELECT * FROM cashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database11.", SELF);
    if (pg_numrows($accntRslt) < 1) {
        $OUTPUT = "<li clss='err'>The entry with reference number, <b>{$cashid}</b> was not found in Cubit.</li>";
        return $OUTPUT;
    }
    $accnt = pg_fetch_array($accntRslt);
    # get hook account number
    core_connect();
    $sql = "SELECT * FROM bankacc WHERE accid = '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to retrieve bank account link from Cubit", SELF);
    # check if link exists
    if (pg_numrows($rslt) < 1) {
        return "<li class='err'> ERROR : The bank account that you selected doesn't appear to have an account linked to it.</li>";
    }
    $bank = pg_fetch_array($rslt);
    # Date
    $sdate = date("Y-m-d");
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # If tis customer payment
    if (($accnt['cusnum'] > 0 || $accnt["multicusnum"] != "") && strlen($accnt['rinvids']) > 0) {
        db_connect();
        # Get invoice Ids and Amounts
        $invids = explode("|", $accnt['rinvids']);
        $amounts = explode("|", $accnt['amounts']);
        $invprds = explode("|", $accnt['invprds']);
        $rages = explode("|", $accnt['rages']);
        if ($accnt["multicusnum"] != "") {
            $cusnums = explode(",", $accnt["multicusnum"]);
            $cusamts = explode(",", $accnt["multicusamt"]);
        } else {
            $cusnums = array($accnt["cusnum"]);
            $cusamts = array($accnt["amount"]);
        }
        $oa = 0;
        # Return the amount that was surppose to be paid to invoices
        foreach ($invids as $key => $invid) {
            if ($invids[$key] <= 0) {
                continue;
            }
            db_connect();
            if (ext_ex("invoices", "invid", $invids[$key]) && $invprds[$key] != 0) {
                db_connect();
                $sql = "\n\t\t\t\t\tUPDATE invoices \n\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                if (open()) {
                    $sql = "SELECT invnum FROM invoices WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $idata = pg_fetch_array($payRslt);
                    $sql = "\n\t\t\t\t\t\tUPDATE open_stmnt \n\t\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\t\tWHERE invid = '{$idata['invnum']}' AND div = '" . USER_DIV . "'";
                    $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    $oa = $oa - $amounts[$key];
                }
            } else {
                if (ext_ex("nons_invoices", "invid", $invids[$key]) && $invprds[$key] == 0) {
                    db_connect();
                    $sql = "\n\t\t\t\t\tUPDATE nons_invoices \n\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                    db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                    /*$Sll="SELECT sdate FROM nons_invoices WHERE invid = '$invids[$key]' AND div = '".USER_DIV."'";
                    		$Rii=db_exec($Sll) or errDie("Unable to get invoice data.");
                    		$dii=pg_fetch_array($Rii);*/
                    $cnsql = "SELECT cusid FROM cubit.nons_invoices WHERE invid='{$invids[$key]}'";
                    $cnrslt = db_exec($cnsql) or errDie("Error reading customer info from nonstock invoice.");
                    $invcusid = pg_fetch_result($cnrslt, 0, 0);
                    custDTA($amounts[$key], $invcusid, $rages[$key], $seldate);
                } else {
                    if ($invprds[$key] != 0 && ext_ex("pinvoices", "invid", $invids[$key], $invprds[$key])) {
                        $sql = "\n\t\t\t\t\tUPDATE \"{$invprds[$key]}\".pinvoices \n\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                        db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                        $sql = "SELECT cusnum, balance FROM \"{$invprds[$key]}\".pinvoices WHERE invid='{$invids[$key]}'";
                        $rslt = db_exec($sql) or errDie("Error reading customer info from nonstock invoice.");
                        $invcusid = pg_fetch_result($rslt, 0, 0);
                        custDTA($amounts[$key], $invcusid, $rages[$key], $seldate);
                    } else {
                        if ($invprds[$key] > 0) {
                            if (open()) {
                                db_conn($invprds[$key]);
                                $sql = "SELECT invnum FROM  invoices WHERE invid = '{$invids[$key]}' AND div = '" . USER_DIV . "'";
                                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                                $idata = pg_fetch_array($payRslt);
                                db_conn('cubit');
                                $sql = "\n\t\t\t\t\t\tUPDATE open_stmnt \n\t\t\t\t\t\tSET balance = (balance + '{$amounts[$key]}'::numeric(13,2)) \n\t\t\t\t\t\tWHERE invid = '{$idata['invnum']}' AND div = '" . USER_DIV . "'";
                                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                                $oa = $oa - $amounts[$key];
                            }
                            db_conn($invprds[$key]);
                            # check if invoice exitsts on prd
                            if (ext_ex("invoices", "invid", $invids[$key])) {
                                # if found, Move the invoice back
                                if (moveback($invids[$key], $invprds[$key], $amounts[$key])) {
                                }
                            }
                        }
                    }
                }
            }
        }
        foreach ($cusnums as $cuskey => $cusnum) {
            $accnt["cusnum"] = $cusnum;
            $cusamt = $cusamts[$cuskey];
            db_connect();
            # Update the customer (make balance more)
            $sql = "UPDATE customers SET balance = (balance + '{$cusamt}'::numeric(13,2)) \n\t\t\t\t\tWHERE cusnum = '{$accnt['cusnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit1.", SELF);
            # Record the transaction on the statement
            $sql = "\n\t\t\t\tINSERT INTO stmnt (\n\t\t\t\t\tcusnum, invid, amount, date, type, \n\t\t\t\t\tdiv, allocation_date\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$accnt['cusnum']}', '0', '{$cusamt}', '{$seldate}', 'Cheque/Payment for Invoices Returned.', \n\t\t\t\t\t'" . USER_DIV . "', '{$accnt['date']}'\n\t\t\t\t)";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            if (sprint($accnt['amount'] + $oa) > 0) {
                # Record the transaction on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, balance\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$accnt['cusnum']}', '0', '" . sprint($accnt['amount'] + $oa) . "', '{$seldate}', \n\t\t\t\t\t\t'Cheque/Payment for Invoices Returned.', '" . USER_DIV . "', '{$cusamt}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            }
        }
        # Delete cashbook ID
        $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
        $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        copyEntry($cashid);
        if ($accnt['lcashid'] > 0) {
            // Connect to database
            db_Connect();
            $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.2", SELF);
            $laccnt = pg_fetch_array($laccntRslt);
            $sql = "\n\t\t\t\tUPDATE bankacct \n\t\t\t\tSET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) \n\t\t\t\tWHERE bankid = '{$laccnt['bankid']}'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit2.", SELF);
            # Delete cashbook ID
            $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
        }
        # Make ledge record
        //		custledger($accnt['cusnum'], $bank['accnum'], $accnt['date'], "cancel", "Payment Returned.", $accnt['amount'], "d");
        foreach ($cusnums as $cuskey => $cusnum) {
            $cusamt = $cusamts[$cuskey];
            custledger($cusnum, $bank['accnum'], $seldate, "cancel", "Payment Returned.", $cusamt, "d");
        }
        $descript = $accnt['descript'] . " Returned, Unpaid";
        $refnum = getrefnum();
        $date = date("Y-m-d");
        # debit customer account, credit bank account (customer takes money back)
        //		writetrans($accnt['accinv'], $bank['accnum'], $accnt['date'], $refnum, $accnt['amount'], $descript);
        writetrans($accnt['accinv'], $bank['accnum'], $seldate, $refnum, $accnt['amount'], $descript);
        $vatacc = gethook("accnum", "salesacc", "name", "VAT");
        if ($accnt['vat'] != 0) {
            # DT(VAT), CT(Bank)
            writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
        }
    } else {
        if (($accnt['cusnum'] > 0 || $accnt["multicusnum"] != "") && $accnt['trantype'] != "withdrawal") {
            $refnum = getrefnum();
            $date = date("Y-m-d");
            //		recordDT($accnt['amount'], $accnt['cusnum']);
            recordCT($accnt['amount'], $accnt['cusnum']);
            if ($accnt["multicusnum"] != "") {
                $cusnums = explode(",", $accnt["multicusnum"]);
                $cusamts = explode(",", $accnt["multicusamt"]);
            } else {
                $cusnums = array($accnt["cusnum"]);
                $cusamts = array($accnt["amount"]);
            }
            db_connect();
            foreach ($cusnums as $cuskey => $cusnum) {
                $accnt["cusnum"] = $cusnum;
                $cusamt = $cusamts[$cuskey];
                # receipt from customer returned
                $sql = "\n\t\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t\t(cusnum, invid, amount, date, type, st, div, allocation_date) \n\t\t\t\t\tVALUES \n\t\t\t\t\t\t('{$accnt['cusnum']}', '0', '{$cusamt}', '{$seldate}', 'Cheque/Payment returned', 'n', '" . USER_DIV . "', '{$accnt['date']}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                $sql = "INSERT INTO open_stmnt(cusnum, invid, amount, date, type, st, div,balance) VALUES('{$accnt['cusnum']}', '0', '{$cusamt}', '{$seldate}', '{$accnt['descript']}, Cheque/Payment returned', 'n', '" . USER_DIV . "','{$cusamt}')";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
                # update the customer (make balance more)
                $sql = "UPDATE customers SET balance = (balance + '{$cusamt}') WHERE cusnum = '{$accnt['cusnum']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
            }
            copyEntry($cashid);
            foreach ($cusnums as $cuskey => $cusnum) {
                $cusamt = $cusamts[$cuskey];
                # Make ledge record
                //		custledger($accnt['cusnum'], $bank['accnum'], $accnt['date'], $refnum, "Cheque/Payment returned.", $accnt['amount'], "c");
                custledger($cusnum, $bank['accnum'], $seldate, $refnum, "Cheque/Payment returned.", $cusamt, "d");
            }
            db_conn('cubit');
            $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            //		writetrans ($accnt['accinv'],$bank['accnum'], $accnt['date'], $refnum, $accnt['amount'], "Cheque/Payment returned.$accnt[descript]");
            writetrans($accnt['accinv'], $bank['accnum'], $seldate, $refnum, $accnt['amount'], "Cheque/Payment returned.{$accnt['descript']}");
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            if ($accnt['vat'] != 0) {
                # DT(VAT), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
            }
        } elseif ($accnt['cusnum'] > 0) {
            $refnum = getrefnum();
            $date = date("Y-m-d");
            recordCT($accnt['amount'], $accnt['cusnum']);
            db_connect();
            # receipt from customer returned
            $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, amount, date, type, st, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$accnt['cusnum']}', '0', '-{$accnt['amount']}', '{$seldate}', 'Cheque/Payment returned', 'n', '" . USER_DIV . "', '{$accnt['date']}')";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            $sql = "INSERT INTO open_stmnt(cusnum, invid, amount, date, type, st, div,balance) VALUES('{$accnt['cusnum']}', '0', '-{$accnt['amount']}', '{$seldate}', '{$accnt['descript']}, Cheque/Payment returned', 'n', '" . USER_DIV . "','-{$accnt['amount']}')";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            # update the customer (make balance more)
            $sql = "UPDATE customers SET balance = (balance - '{$accnt['amount']}') WHERE cusnum = '{$accnt['cusnum']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update customer in Cubit.", SELF);
            copyEntry($cashid);
            # Make ledge record
            custledger($accnt['cusnum'], $bank['accnum'], $accnt['date'], $refnum, "Cheque/Payment returned.", $accnt['amount'], "c");
            db_conn('cubit');
            $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            //		writetrans ($bank['accnum'],$accnt['accinv'], $date, $refnum, $accnt['amount'], "Cheque/Payment returned.$accnt[descript]");
            writetrans($bank['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $accnt['amount'], "Cheque/Payment returned.{$accnt['descript']}");
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            if ($accnt['vat'] != 0) {
                # DT(VAT), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
            }
        } elseif ($accnt['supid'] > 0) {
            db_connect();
            $ids = explode("|", $accnt['ids']);
            $purids = explode("|", $accnt['purids']);
            $pamounts = explode("|", $accnt['pamounts']);
            $pdates = explode("|", $accnt['pdates']);
            if (count($ids) > 0) {
                foreach ($ids as $key => $vale) {
                    if ($ids[$key] > 0) {
                        rerecord($ids[$key], $accnt['supid'], $purids[$key], $pamounts[$key], $pdates[$key]);
                    }
                }
            }
            # if the amount was overpaid
            if (array_sum($pamounts) < $accnt['amount']) {
                # get and record amount that was overpaid to balance the equation
                $rem = $accnt['amount'] - array_sum($pamounts);
                rerecord('0', $accnt['supid'], '0', $rem, $accnt['date']);
            }
            # Update the supplier (make balance more)
            $sql = "UPDATE suppliers SET balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE supid = '{$accnt['supid']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit3.", SELF);
            # Record the payment on the statement
            $sql = "INSERT INTO sup_stmnt(supid, edate, cacc, ref, descript, amount, div) VALUES('{$accnt['supid']}', '{$seldate}', '{$bank['accnum']}', '{$accnt['cheqnum']}', 'Cheque/Payment to Supplier Returned.', '{$accnt['amount']}', '" . USER_DIV . "')";
            $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            # Delete cashbook ID
            $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            copyEntry($cashid);
            if ($accnt['lcashid'] > 0) {
                // Connect to database
                db_Connect();
                $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database3.", SELF);
                $laccnt = pg_fetch_array($laccntRslt);
                $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.4", SELF);
                # Delete cashbook ID
                $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            }
            suppledger($accnt['supid'], $bank['accnum'], $accnt['date'], $accnt['cheqnum'], "Payment to Supplier Returned", $accnt['amount'], "c");
            db_connect();
            $descript = $accnt['descript'] . " Returned, Unpaid";
            $refnum = getrefnum();
            $date = date("Y-m-d");
            # debit bank, credit supplier account
            writetrans($bank['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $accnt['amount'], $descript);
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            if ($accnt['vat'] != 0) {
                # DT(VAT), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
            }
        } elseif ($accnt['suprec'] > 0) {
            db_connect();
            $Sl = "INSERT INTO sup_stmnt(supid, amount, edate, descript,ref,cacc, div) VALUES('{$accnt['suprec']}','-{$accnt['amount']}','{$accnt['date']}', 'Receipt Returned','{$accnt['cheqnum']}','0', '" . USER_DIV . "')";
            $Rs = db_exec($Sl) or errDie("Unable to insert statement record in Cubit.", SELF);
            # Update the supplier (make balance less)
            $sql = "UPDATE suppliers SET balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE supid = '{$accnt['suprec']}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.5", SELF);
            suppDT($accnt['amount'], $accnt['suprec']);
            suppledger($accnt['suprec'], $bank['accnum'], $accnt['date'], $accnt['cheqnum'], "Receipt from Supplier Returned", $accnt['amount'], "d");
            db_connect();
            # Delete cashbook ID
            $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            copyEntry($cashid);
            if ($accnt['lcashid'] > 0) {
                # Delete cashbook ID
                $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
            }
            $descript = $accnt['descript'] . " Returned, Unpaid";
            $refnum = getrefnum();
            $date = date("Y-m-d");
            # debit bank, credit supplier account
            writetrans($accnt['accinv'], $bank['accnum'], $accnt['date'], $refnum, $accnt['amount'], $descript);
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            if ($accnt['vat'] != 0) {
                # DT(VAT), CT(Bank)
                writetrans($vatacc, $bank['accnum'], $accnt['date'], $accnt['reference'], $vat, $accnt['descript']);
            }
        } else {
            if ($accnt["empnum"] != "0" && strlen($accnt["empnum"]) > 0 && $accnt['trantype'] == "withdrawal") {
                $refnum = getrefnum();
                $date = date("Y-m-d");
                $sql = "UPDATE cubit.employees SET balance = balance + '{$accnt['amount']}' \n\t\t\t\tWHERE empnum='{$accnt['empnum']}' AND div = '" . USER_DIV . "'";
                db_exec($sql) or errDie("Unable to get employee details.");
                $sql = "SELECT fnames,sname FROM cubit.employees WHERE empnum='{$accnt['empnum']}'";
                $rslt = db_exec($sql);
                $empinfo = pg_fetch_array($rslt);
                $empname = "{$empinfo['fnames']} {$empinfo['sname']}";
                copyEntry($cashid);
                empledger($accnt["empnum"], $bank['accnum'], $accnt["date"], $refnum, "Cheque/Payment Returned", $accnt['amount'], "c");
                db_conn('cubit');
                $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
                writetrans($bank['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $accnt['amount'], "Cheque/Payment returned for {$empname}");
            } elseif (strlen($accnt['accids']) > 0) {
                /* -- Start Hooks -- */
                $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                /* -- End Hooks -- */
                multican($accnt, $bank, $vatacc, $accnt['vatcode']);
            } else {
                $amount = $accnt['amount'];
                $vat = $accnt['vat'];
                $chrgvat = $accnt['chrgvat'];
                $amount -= $vat;
                /* -- Start Hooks -- */
                $vatacc = gethook("accnum", "salesacc", "name", "VAT");
                /* -- End Hooks -- */
                db_connect();
                # Delete cashbook ID
                $sql = "UPDATE cashbook SET opt = 'n' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
                $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
                copyEntry($cashid);
                if ($accnt['trantype'] == "deposit") {
                    $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$accnt['famount']}'::numeric(13,2)), balance = (balance - '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
                    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.5", SELF);
                } else {
                    $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$accnt['famount']}'::numeric(13,2)), balance = (balance + '{$accnt['amount']}'::numeric(13,2)) WHERE bankid = '{$accnt['bankid']}'";
                    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.6", SELF);
                }
                /* ---- the Others ---- */
                if ($accnt['lcashid'] > 0) {
                    //Connect to database
                    db_Connect();
                    $sql = "SELECT * FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                    $laccntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.4", SELF);
                    $laccnt = pg_fetch_array($laccntRslt);
                    if ($laccnt['trantype'] == "deposit") {
                        $sql = "UPDATE bankacct SET fbalance = (fbalance - '{$laccnt['famount']}'::numeric(13,2)), balance = (balance - '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.7", SELF);
                    } else {
                        $sql = "UPDATE bankacct SET fbalance = (fbalance + '{$laccnt['famount']}'::numeric(13,2)), balance = (balance + '{$laccnt['amount']}'::numeric(13,2)) WHERE bankid = '{$laccnt['bankid']}'";
                        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.8", SELF);
                    }
                    # Delete cashbook ID
                    $sql = "DELETE FROM cashbook WHERE cashid = '{$accnt['lcashid']}' AND div = '" . USER_DIV . "'";
                    $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
                    /* ---- End the Others ---- */
                }
                $descript = $accnt['descript'] . " Returned, Unpaid";
                $refnum = getrefnum();
                $date = date("Y-m-d");
                if ($accnt['trantype'] == "deposit") {
                    $vatacc = gethook("accnum", "salesacc", "name", "VAT", "a");
                    # DT(account involved), CT(bank)
                    //			writetrans($accnt['accinv'], $bank['accnum'], $accnt['date'], $refnum, $amount, $descript);
                    writetrans($accnt['accinv'], $bank['accnum'], $seldate, $refnum, $amount, $descript);
                    if ($vat != 0) {
                        # DT(Vat), CT(Bank)
                        db_conn('cubit');
                        $Sl = "SELECT * FROM vatcodes WHERE id='{$accnt['vatcode']}'";
                        $Ri = db_exec($Sl);
                        $vd = pg_fetch_array($Ri);
                        //				vatr($vd['id'],$date,"OUTPUT",$vd['code'],$refnum,$descript,-($amount+$vat),-$vat);
                        vatr($vd['id'], $seldate, "OUTPUT", $vd['code'], $refnum, $descript, -($amount + $vat), -$vat);
                        //				writetrans($vatacc, $bank['accnum'], $accnt['date'], $refnum, $vat, $descript);
                        writetrans($vatacc, $bank['accnum'], $seldate, $refnum, $vat, $descript);
                    }
                    $cc_trantype = cc_TranTypeAcc($accnt['accinv'], $bank['accnum']);
                } else {
                    # DT(bank), CT(account invoilved)
                    //			writetrans($bank['accnum'], $accnt['accinv'], $accnt['date'], $refnum, $amount, $descript);
                    writetrans($bank['accnum'], $accnt['accinv'], $seldate, $refnum, $amount, $descript);
                    if ($vat != 0) {
                        # DT(Vat), CT(Bank)
                        db_conn('cubit');
                        $Sl = "SELECT * FROM vatcodes WHERE id='{$accnt['vatcode']}'";
                        $Ri = db_exec($Sl);
                        $vd = pg_fetch_array($Ri);
                        //				vatr($vd['id'],$date,"INPUT",$vd['code'],$refnum,$descript,($amount+$vat),$vat);
                        vatr($vd['id'], $seldate, "INPUT", $vd['code'], $refnum, $descript, $amount + $vat, $vat);
                        //				writetrans($bank['accnum'], $vatacc, $accnt['date'], $refnum, $vat, $descript);
                        writetrans($bank['accnum'], $vatacc, $seldate, $refnum, $vat, $descript);
                    }
                    $cc_trantype = cc_TranTypeAcc($bank['accnum'], $accnt['accinv']);
                }
                /* stock purchase/sale */
                if (!empty($accnt["stkinfo"])) {
                    list($si_stkid, $si_unitnum, $si_cost, $si_vat) = explode("|", $accnt["stkinfo"]);
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                    $stk = pg_fetch_array($stkRslt);
                    if ($accnt['trantype'] == "deposit") {
                        db_connect();
                        $sql = "UPDATE stock SET csamt = (csamt + '{$si_cost}'), \n\t\t\t\t\t\t\tunits = (units + '{$si_unitnum}') \n\t\t\t\t\t\tWHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                        $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $seldate, $si_unitnum, $si_cost, "Returned receipt for: {$accnt['descript']}");
                        db_connect();
                        $cspric = sprint($si_cost / $si_unitnum);
                        $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\t\t\tVALUES('{$seldate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'inc', '{$si_unitnum}', '{$si_cost}', '{$cspric}', 'Returned receipt for: {$accnt['descript']}', '" . USER_DIV . "')";
                        $recRslt = db_exec($sql);
                        db_connect();
                        $sql = "SELECT * FROM stock WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                        $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                        $stk = pg_fetch_array($stkRslt);
                        if ($stk['units'] != 0) {
                            $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        } else {
                            $csprice = sprint($si_cost / $si_unitnum);
                            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        }
                    } else {
                        db_connect();
                        $sql = "UPDATE stock SET csamt = (csamt - {$si_cost}), \n\t\t\t\t\t\t\tunits = (units - '{$si_unitnum}') \n\t\t\t\t\t\tWHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                        $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $seldate, $si_unitnum, $si_cost, "Returned payment for: {$accnt['descript']}");
                        db_connect();
                        $cspric = sprint($si_cost / $si_unitnum);
                        $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\t\t\tVALUES('{$seldate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'dec', '-{$si_unitnum}', '{$si_cost}', '{$cspric}', 'Returned payment for: {$accnt['descript']}', '" . USER_DIV . "')";
                        $recRslt = db_exec($sql);
                        db_connect();
                        $sql = "SELECT * FROM stock WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                        $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                        $stk = pg_fetch_array($stkRslt);
                        if ($stk['units'] != 0) {
                            $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        } else {
                            $csprice = sprint($si_cost / $si_unitnum);
                            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$si_stkid}' AND div = '" . USER_DIV . "'";
                            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                        }
                    }
                }
            }
        }
    }
    if (isset($cc_trantype) && $cc_trantype != false) {
        $cc = "<script> CostCenter('{$cc_trantype}', 'Returned, Unpaid Bank Transaction', '{$seldate}', '{$descript}', '" . ($accnt['amount'] - $accnt['vat']) . "', '../'); </script>";
    } else {
        $cc = "";
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    # Status report
    $bank = "\n\t\t\t{$cc}\n\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Cash Book</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>Cash Book Entry was successfully canceled .</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    # Main table (layout with menu)
    $OUTPUT = "\n\t\t\t<center>\n\t\t\t<table width='90%'>\n\t\t\t\t<tr valign='top'>\n\t\t\t\t\t<td width='60%'>{$bank}</td>\n\t\t\t\t\t<td align='center'>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='cashbook-view.php'>View Cash Book</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='../reporting/not-banked.php'>View Outstanding Cash Book Entries</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='bank-pay-add.php'>Add Bank Payment</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td align='center'><a href='bank-recpt-add.php'>Add Bank Receipt</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    return $OUTPUT;
}
function write($_POST)
{
    # Get vars
    extract($_POST);
    if (isset($back)) {
        return edit($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($stkid, "num", 1, 50, "Invalid stock id.");
    $v->isOk($unitnum, "float", 1, 50, "Invalid number of units.");
    $v->isOk($cost, "float", 1, 50, "Invalid cost amount per unit.");
    $v->isOk($det, "string", 0, 255, "Invalid Details.");
    $v->isOk($date, "string", 4, 14, "Invalid date.");
    # 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;
    }
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.</li>";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    # Get warehouse name
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    $refnum = getrefnum();
    /*refnum*/
    # calculate actual cost amount
    $cost = sprint($cost * $unitnum);
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    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.</li>";
    }
    $banklnk = pg_fetch_array($rslt);
    $cacc = $banklnk['accnum'];
    ############## PROCESS VAT + AMOUNTS ################
    $totamt = $cost;
    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);
    $vatp = $vd['vat_amount'];
    if ($chrgvat == "exc") {
        $totamt += $vat;
    } elseif ($chrgvat == "inc") {
        $cost = sprint($totamt - $vat);
    } else {
        //		$vat = "No VAT";
    }
    ################# DONE ###################
    pglib_transaction("BEGIN");
    if ($ttype == 'payment') {
        # Update Stock
        db_connect();
        $sql = "UPDATE stock SET csamt = (csamt + '{$cost}'), units = (units + '{$unitnum}') WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
        $sdate = $date;
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $sdate, $unitnum, $cost, $det);
        db_connect();
        $cspric = sprint($cost / $unitnum);
        $sql = "\n\t\t\tINSERT INTO stockrec (\n\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div\n\t\t\t) VALUES (\n\t\t\t\t'{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'inc', '{$unitnum}', '{$cost}', '{$cspric}', '{$det}', '" . USER_DIV . "'\n\t\t\t)";
        $recRslt = db_exec($sql);
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
        if (pg_numrows($stkRslt) < 1) {
            return "<li> Invalid Stock ID.</li>";
        } else {
            $stk = pg_fetch_array($stkRslt);
        }
        # Units
        if ($stk['units'] != 0) {
            $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
        } else {
            $csprice = sprint($cost / $unitnum);
            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
        }
        /*		$totamt = $cost;
        
        		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);
        		$vatp = $vd['vat_amount'];
        		if($chrgvat == "exc"){
        		$totamt += $vat;
        		} elseif($chrgvat == "inc"){
        		$cost=sprint($totamt-$vat);
        		}else{
        		$vat = "No VAT";
        		}*/
        # Debit STock account and Credit Contra Account
        writetrans($wh['stkacc'], $cacc, $date, $refnum, $cost, $det);
        if ($vat != 0) {
            # DT(VAT), CT(Bank)
            writetrans($vatacc, $banklnk['accnum'], $date, $refnum, $vat, $det);
        }
        vatr($vd['id'], $date, "INPUT", $vd['code'], $refnum, $det, -($cost + $vat), -$vat);
        $cc_trantype = cc_TranTypeAcc($wh['stkacc'], $cacc);
        $temp = $cost + $vat;
        db_connect();
        $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, \n\t\t\t\tdiv, vatcode, stkinfo\n\t\t\t) VALUES (\n\t\t\t\t'{$bankid}', 'withdrawal', '{$date}', '{$det}', '{$det}', '0', '{$temp}', '{$vat}', '{$chrgvat}', 'no', '{$wh['stkacc']}', \n\t\t\t\t'" . USER_DIV . "', '{$vatcode}', '{$stk['stkid']}|{$unitnum}|{$cost}|{$vat}'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    } elseif ($ttype == 'receipt') {
        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "VAT");
        # Update Stock
        db_connect();
        $sql = "UPDATE stock SET csamt = (csamt - {$cost}), units = (units - '{$unitnum}') WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
        $sdate = $date;
        # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
        stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $sdate, $unitnum, $cost, $det);
        db_connect();
        $cspric = sprint($cost / $unitnum);
        $sql = "\n\t\t\tINSERT INTO stockrec (\n\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div\n\t\t\t) VALUES (\n\t\t\t\t'{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'dec', '-{$unitnum}', '{$cost}', '{$cspric}', '{$det}', '" . USER_DIV . "'\n\t\t\t)";
        $recRslt = db_exec($sql);
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
        if (pg_numrows($stkRslt) < 1) {
            return "<li> Invalid Stock ID. </li>";
        } else {
            $stk = pg_fetch_array($stkRslt);
        }
        if ($stk['units'] != 0) {
            $sql = "UPDATE stock SET csprice = (csamt/units) WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
        } else {
            $csprice = sprint($cost / $unitnum);
            $sql = "UPDATE stock SET csprice = '{$csprice}' WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
        }
        if (isset($sernos)) {
            foreach ($sernos as $skey => $serno) {
                // ext_invSer($serno, $stkid);
                ext_OutSer($serno, $stkid, $det, $refnum, "tran");
            }
        }
        #  Debit Contra Account and Credit Stock account
        writetrans($cacc, $wh['stkacc'], $date, $refnum, $cost, $det);
        if ($vat != 0) {
            # DT(VAT), CT(Bank)
            writetrans($banklnk['accnum'], $vatacc, $date, $refnum, $vat, $det);
        }
        vatr($vd['id'], $date, "OUTPUT", $vd['code'], $refnum, $det, -($cost + $vat), -$vat);
        $cc_trantype = cc_TranTypeAcc($cacc, $wh['stkacc']);
        $temp = $cost + $vat;
        db_connect();
        $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div, vatcode, \n\t\t\t\tstkinfo\n\t\t\t) VALUES (\n\t\t\t\t'{$bankid}', 'deposit', '{$date}', '{$det}', '{$det}', '0', '{$temp}', '0', 'no', 'no', '{$wh['stkacc']}', '" . USER_DIV . "','1',\n\t\t\t\t'{$stk['stkid']}|{$unitnum}|{$cost}|{$vat}'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    }
    pglib_transaction("COMMIT");
    // Layout
    $write = "\n\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t<tr>\n\t\t\t\t<th>Stock Bank Transaction</th>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td>Stock Bank Transaction for: {$stk['stkdes']} ({$stk['stkcod']}) has been successfully recorded.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<p>\n\t\t<table border='0' cellpadding='2' cellspacing='1'>\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='../stock-add.php'>Add Stock</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='../stock-view.php'>View Stock</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)
{
    # Get vars
    extract($_POST);
    if (isset($back)) {
        return details($_POST);
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 50, "Invalid Customer number.");
    $v->isOk($accid, "num", 1, 50, "Invalid Contra Account.");
    $v->isOk($refnum, "num", 1, 10, "Invalid Reference number.");
    $v->isOk($amount, "float", 1, 20, "Invalid Amount.");
    $v->isOk($details, "string", 0, 255, "Invalid Details.");
    $v->isOk($author, "string", 1, 30, "Invalid Authorising person name.");
    $v->isOk($vatinc, "string", 1, 6, "Invalid Transaction VAT Option.");
    $datea = explode("-", $date);
    if (count($datea) == 3) {
        if (!checkdate($datea[1], $datea[0], $datea[2])) {
            $v->isOk($date, "num", 1, 1, "Invalid date.");
        }
    } else {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $write = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $write .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $write .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $write;
    }
    if (isset($stock_prof) and is_array($stock_prof) and sprint(array_sum($stock_prof)) != $difference) {
        return details($_POST, "<li class='err'>Please ensure differences matches total difference.</li>");
    }
    //print "<pre>";
    //var_dump ($_POST);
    //print "</pre>";
    $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 "<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 "<i class='err'>Customer Department Not Found</i>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # Begin updates
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    # Probe tran type
    if ($entry == "CT") {
        $refnum = getrefnum();
        #update stock ...
        $stock_total = 0;
        if (isset($stock_items) and is_array($stock_items)) {
            $used_stock = TRUE;
            foreach ($stock_items as $stkid => $unitnum) {
                db_connect();
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                if (pg_numrows($stkRslt) < 1) {
                    return "<li> Invalid Stock ID.</li>";
                } else {
                    $stk = pg_fetch_array($stkRslt);
                }
                if ($stk['units'] < 0) {
                    $min_stock = abs($stk['units']);
                    if ($unitnum < $min_stock) {
                        $min_stock = $unitnum;
                    }
                } else {
                    $min_stock = 0;
                }
                # Get warehouse name
                db_conn("exten");
                $sql = "SELECT * FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                # calculate actual cost amount
                //				$temp = $cost;
                //				$cost = sprint($cost * $unitnum);
                #temp = unitprice
                $temp = sprint($stock_cost[$stkid]);
                #cost = total price
                $cost = sprint($stock_cost[$stkid] * $unitnum);
                $cost_amt = sprint($cost);
                $stock_total = $stock_total + $cost_amt;
                $stock_cost[$stkid] = $cost_amt / $unitnum;
                #temp = unitprice
                $temp = sprint($stock_cost[$stkid]);
                #cost = total price
                $cost = sprint($stock_cost[$stkid] * $unitnum);
                $tipo = "Increase";
                if ($tipo == 'Increase') {
                    /* do the journals for stock sold before purchase 
                    			this will only be done by a purchase */
                    if ($min_stock > 0) {
                        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'];
                    }
                    # Update Stock
                    db_connect();
                    $sql = "UPDATE stock\n\t\t\t\t\t\t\tSET units = (units + '{$unitnum}'),\n\t\t\t\t\t\t\t\tlcsprice = '{$temp}',\n\t\t\t\t\t\t\t\tcsamt = (csamt + {$cost}),\n\t\t\t\t\t\t\t\tcsprice = (\n\t\t\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\t\t\tCASE WHEN (units != -{$unitnum}) THEN (csamt+{$cost})/(units+{$unitnum})\n\t\t\t\t\t\t\t\t\t\tELSE 0\n\t\t\t\t\t\t\t\t\t\tEND\n\t\t\t\t\t\t\t\t\tFROM cubit.stock\n\t\t\t\t\t\t\t\t\tWHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tWHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
                    $rslt = db_exec($sql) or errDie("Unable to insert stock to Cubit.", SELF);
                    $sdate = $date;
                    # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
                    stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'dt', $sdate, $unitnum, $cost, $details);
                    db_connect();
                    if ($unitnum == 0) {
                        $csprice = 0;
                    } else {
                        $csprice = sprint($cost / $unitnum);
                    }
                    $sql = "INSERT INTO stockrec(edate, stkid, stkcod, stkdes, trantype, qty, csprice, csamt, details, div)\n\t\t\t\t\t\t\tVALUES('{$sdate}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'note', '{$unitnum}', '" . sprint($cost + $stock_prof[$stkid]) . "', '{$csprice}', '{$details}', '" . USER_DIV . "')";
                    $recRslt = db_exec($sql);
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
                    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
                    if (pg_numrows($stkRslt) < 1) {
                        return "<li> Invalid Stock ID.</li>";
                    } else {
                        $stk = pg_fetch_array($stkRslt);
                    }
                    # balance transaction
                    # Debit STock account and Credit Contra Account
                    #ct was $dept['debtacc']
                    writetrans($wh['stkacc'], $wh['cosacc'], $date, $refnum, $cost, "Cost Of Sales for: {$details} for Customer: {$cust['surname']}");
                    $cc_trantype = cc_TranTypeAcc($wh['stkacc'], $dept['debtacc']);
                }
            }
        } else {
            $used_stock = FALSE;
        }
        #we'll handle the discrincy seperately
        if ($stock_total != 0) {
            $amount_dif = sprint($amount - $stock_total);
            //			$amount = sprint ($stock_total);
        } else {
            $amount_dif = 0;
            //			$amount = sprint ($amount);
        }
        #do vat trans ...
        if (isset($vatinc) and $vatinc != "novat") {
            #process vat
            db_connect();
            $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}'";
            $Ri = db_exec($Sl);
            $vd = pg_fetch_array($Ri);
            $VATP = $vd['vat_amount'];
            #calculate amounts
            if ($vatinc == 'yes') {
                $vatamt = sprint($amount / ($VATP + 100) * $VATP);
                $amt = sprint($amount - $vatamt);
                $totamt = sprint($amount);
            } else {
                $vatamt = sprint($VATP / 100 * $amount);
                $amt = sprint($amount);
                $totamt = sprint($amount + $vatamt);
            }
            $datea = explode("-", $date);
            $cdate = $date;
            # Check VAt Deductable account
            if ($vatdedacc == 'dt') {
                vatr($vd['id'], $cdate, "INPUT", $vd['code'], $refnum, "{$details} VAT", -$totamt, -$vatamt);
                writetrans($vataccid, $dept['debtacc'], $date, $refnum, $vatamt, "VAT Return for: {$details}");
            } elseif ($vatdedacc == 'ct') {
                vatr($vd['id'], $cdate, "OUTPUT", $vd['code'], $refnum, "{$details}.  VAT", $totamt, $vatamt);
                writetrans($accid, $vataccid, $date, $refnum, $vatamt, "VAT Return for: {$details}");
            }
            if ($used_stock) {
                $accid = $dept['incacc'];
                $details = "Debtors Control for: {$details}";
            }
            writetrans($accid, $dept['debtacc'], $date, $refnum, $amt, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
        } else {
            $totamt = sprint($amount);
            $amt = sprint($amount);
            $getacc_arr = getAccn("2190", "000");
            $getgacc = $getacc_arr['accid'];
            if ($used_stock) {
                $accid = $dept['incacc'];
                $details = "Debtors Control for: {$details}";
            }
            # Write transaction  (debit contra account, credit debtors control)
            writetrans($accid, $dept['debtacc'], $date, $refnum, $totamt, $details . " - Customer {$cust['cusname']} {$cust['surname']}");
        }
        $tran = "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>{$acc['topacc']}/{$acc['accnum']} - {$acc['accname']}</td>\n\t\t\t\t\t\t<td>{$cust['accno']} - {$cust['cusname']} {$cust['surname']}</td>\n\t\t\t\t\t</tr>";
        $samount = $amount - $amount * 2;
        recordCT($samount, $cust['cusnum'], $date);
        $type = 'c';
    }
    db_connect();
    $stotamt = $totamt - $totamt * 2;
    $sdate = date("Y-m-d");
    # record the payment on the statement
    $sql = "\n\t\t\tINSERT INTO stmnt \n\t\t\t\t(cusnum, invid, amount, date, type, st, div, allocation_date) \n\t\t\tVALUES \n\t\t\t\t('{$cust['cusnum']}', '0', '{$stotamt}', '{$date}', '{$details}', 'n', '" . USER_DIV . "', '{$date}')";
    $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
    $sql = "INSERT INTO open_stmnt(cusnum, invid, amount, balance, date, type, st, div) VALUES('{$cust['cusnum']}', '0', '{$samount}', '{$samount}', '{$date}', '{$details}', 'n', '" . 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 + '{$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, $totamt, $type);
    db_connect();
    $get_credid = "SELECT last_value FROM seq WHERE type = 'cred_note' LIMIT 1";
    $run_credid = db_exec($get_credid) or errDie("Unable to get credit note number.");
    $crednote_num = pg_fetch_result($run_credid, 0, 0);
    if (!isset($vataccid)) {
        $vataccid = 0;
    }
    if (!isset($vatamt)) {
        $vatamt = 0;
    }
    if (!isset($vatdedacc)) {
        $vatdedacc = 0;
    }
    if (!isset($vatcode)) {
        $vatcode = 0;
    }
    #record this credit note for records ...
    $ins_sql = "\n\t\t\t\t\t\tINSERT INTO credit_notes \n\t\t\t\t\t\t\t(cusnum,creditnote_num,tdate,sdate,refnum,contra,charge_vat,vatinc,vatacc,vatamt,vatacc_type,vatcode,used_stock,amount,totamt) \n\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t('{$cusnum}','{$crednote_num}','{$date}','now','{$refnum}','{$accid}','{$vatinc}','{$vatinc}','{$vataccid}','{$vatamt}','{$vatdedacc}','{$vatcode}','{$used_stock}','{$amt}','{$totamt}')\n\t\t\t\t\t";
    $run_ins = db_exec($ins_sql) or errDie("Unable to record credit note information.");
    $cred_id = pglib_lastid("credit_notes", "id");
    if ($used_stock) {
        foreach ($stock_items as $stkid => $unitnum) {
            $ins_creditnote_sql = "\n\t\t\t\t\t\t\t\t\t\tINSERT INTO credit_notes_stock\n\t\t\t\t\t\t\t\t\t\t\t(creditnote_id,stkid,stkunits,stkcosts) \n\t\t\t\t\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t\t\t\t\t\t('{$cred_id}','{$stkid}','{$unitnum}','" . sprint(($unitnum * $stock_cost[$stkid] + $stock_prof[$stkid]) / $unitnum) . "')";
            $run_creditnote_sql = db_exec($ins_creditnote_sql) or errDie("Unable to record credit note returned stock item information.");
        }
    }
    #update seq
    $upd_seq = "UPDATE seq SET last_value = last_value + 1 WHERE type = 'cred_note'";
    $run_seq = db_exec($upd_seq) or errDie("Unable to update credit note number.");
    # Commit updates
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    if (isset($gds_note) and strlen($gds_note) > 0) {
        $show_gds_note = "\n\t\t\t\t\t<script>\n\t\t\t\t\t\twindow.open(\"" . SELF . "?key=recv_print&genid={$cred_id}\");\n\t\t\t\t\t</script>\n\t\t\t\t\t\t";
    } else {
        $show_gds_note = "";
    }
    // Start layout
    $write = "\n    \t\t\t<script>\n    \t\t\t\twindow.open('credit-note-print.php?id={$cred_id}');\n    \t\t\t</script>\n    \t\t\t{$show_gds_note}\n    \t\t\t<h3>Credit Note Has Been Recorded</h3>\n\t\t        <table " . TMPL_tblDflts . " width='500'>\n\t\t        \t<tr>\n\t\t        \t\t<td width='50%'><h3>Debit</h3></td>\n\t\t        \t\t<td width='50%'><h3>Credit</h3></td>\n\t\t        \t</tr>\n\t\t        \t{$tran}\n\t\t        \t<tr><td><br></td></tr>\n\t\t        \t<tr colspan='2'>\n\t\t        \t\t<td><h4>Amount</h4></td>\n\t\t        \t</tr>\n\t\t        \t<tr class='" . bg_class() . "'>\n\t\t        \t\t<td colspan='2'><b>" . CUR . " {$amount}</b></td>\n\t\t        \t</tr>\n\t\t        \t" . TBL_BR . "\n\t\t        </table>";
    return $write;
}
function write($_POST)
{
    # processes
    db_connect();
    # Get vars
    extract($_POST);
    if (isset($back)) {
        return add($_POST);
    }
    if (!isset($vat) or strlen($vat) < 1) {
        $vat = 0;
    }
    # 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.");
    $v->isOk($chrgvat, "string", 1, 4, "Invalid vat option.");
    $v->isOk($accinv, "string", 1, 255, "Invalid account number (account involved).");
    $v->isOk($vat, "float", 0, 16, "Invalid vat amount.");
    $vatcode += 0;
    # 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;
    }
    if (empty($descript)) {
        $descript = "Payment to {$name}";
    }
    # date format
    $date_arr = explode("-", $date);
    $date = $date_arr[2] . "-" . $date_arr[1] . "-" . $date_arr[0];
    #update/set the global date
    $_SESSION["global_day"] = $date_arr[0];
    $_SESSION["global_month"] = $date_arr[1];
    $_SESSION["global_year"] = $date_arr[2];
    $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
    #refnum
    $refnum = getrefnum();
    # Start rattling vat
    //	$vatp = TAX_VAT;
    $totamt = $amount;
    // 	db_conn('cubit');
    // 	$Sl="SELECT * FROM vatcodes WHERE id='$vatcode' AND zero='Yes'";
    // 	$Ri=db_exec($Sl) or errDie("Unable to get vat codes");
    //
    // 	$vd = pg_fetch_array($Ri);
    // 	if(pg_num_rows($Ri)>0) {
    // 		$chrgvat="no";
    // 	}
    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);
    $vatp = $vd['vat_amount'];
    if ($chrgvat == "exc") {
        $totamt += $vat;
    } elseif ($chrgvat == "inc") {
        $amount = sprint($totamt - $vat);
    } else {
        $vat = "No VAT";
    }
    /* -- 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.</li>";
    }
    $banklnk = pg_fetch_array($rslt);
    /* -- End Hooks -- */
    $cheqnum = 0 + $cheqnum;
    $vat += 0;
    $vatcode += 0;
    pglib_transaction("BEGIN");
    if (isset($batch)) {
        db_connect();
        $sql = "\n\t\t\tINSERT INTO batch_cashbook (\n\t\t\t\tbankid, trantype, date, name, descript, cheqnum, amount, \n\t\t\t\tvat, chrgvat, banked, accinv, div, vatcode, reference, bt\n\t\t\t) VALUES (\n\t\t\t\t'{$bankid}', 'withdrawal', '{$date}', '{$name}', '{$descript}', '{$cheqnum}', '{$totamt}', \n\t\t\t\t'{$vat}', '{$chrgvat}', 'no', '{$accinv}', '" . USER_DIV . "', '{$vatcode}', '{$reference}', 'payment'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        # Status report
        $write = "\n\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Bank Payment</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>Bank Payment added to batch.</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    } else {
        # Record the payment record
        db_connect();
        $sql = "\n\t\t\tINSERT INTO cashbook (\n\t\t\t\tbankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div, reference, vatcode\n\t\t\t) VALUES (\n\t\t\t\t'{$bankid}', 'withdrawal', '{$date}', '{$name}', '{$descript}', '{$cheqnum}', '{$totamt}', '{$vat}', '{$chrgvat}', 'no', '{$accinv}', '" . USER_DIV . "', '{$reference}', '{$vatcode}'\n\t\t\t)";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
        vatr($vd['id'], $date, "INPUT", $vd['code'], $refnum, $descript, -($amount + $vat), -$vat);
        # DT(account involved), CT(bank)
        writetrans($accinv, $banklnk['accnum'], $date, $refnum, $amount, $descript);
        if ($vat != 0) {
            # DT(VAT), CT(Bank)
            writetrans($vatacc, $banklnk['accnum'], $date, $refnum, $vat, $descript);
        }
        if (cc_TranTypeAcc($accinv, $banklnk['accnum']) != false) {
            $cc_trantype = cc_TranTypeAcc($accinv, $banklnk['accnum']);
            $cc = "<script> CostCenter('{$cc_trantype}', 'Bank Transaction', '{$date}', '{$descript}', '{$amount}', '../'); </script>";
        } else {
            $cc = "";
        }
        $dif = sprint($amount + $vat - $totamt);
        if ($dif > 0) {
            writetrans($banklnk['accnum'], $varacc, $date, $refnum, $dif, "Variance on bank payment Ref: {$refnum}");
        } elseif ($dif < 0) {
            $dif = $dif * -1;
            writetrans($varacc, $banklnk['accnum'], $date, $refnum, $dif, "Variance on bank payment Ref: {$refnum}");
        }
        # Status report
        $write = "\n\t\t\t{$cc}\n\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Bank Payment</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='datacell'>\n\t\t\t\t\t<td>Bank Payment added to cash book.</td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    pglib_transaction("COMMIT");
    # 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'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\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<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='bank-pay-add.php'>Add Bank Payment</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='bank-recpt-add.php'>Add Bank Receipt</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><a href='cashbook-view.php'>View Cash Book</a></td>\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 write($_POST)
{
    # Get vars
    global $_FILES;
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    $vatcode += 0;
    # Validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($cashid, "num", 1, 4, "Invalid Reference number.");
    $v->isOk($refno, "string", 0, 255, "Invalid Receipt/Ref No.");
    $v->isOk($ret, "float", 0, 10, "Invalid Returned/Change amount.");
    $vatret += 0;
    # 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;
    }
    $date = DATE_STD;
    if (is_uploaded_file($_FILES["doc"]["tmp_name"])) {
        $doctyp = $_FILES["doc"]["type"];
        $filename = $_FILES["doc"]["name"];
        # Open file in "read, binary" mode
        $docu = "";
        $file = fopen($_FILES['doc']['tmp_name'], "rb");
        while (!feof($file)) {
            # fread is binary safe
            $docu .= fread($file, 1024);
        }
        fclose($file);
        # Compress and encode the file
        $docu = doclib_encode($docu, 9);
    }
    # Connect to database
    db_Connect();
    $sql = "SELECT * FROM pettycashbook WHERE cashid = '{$cashid}' AND div = '" . USER_DIV . "'";
    $cashRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve cashbook entry details from database.", SELF);
    $cash = pg_fetch_array($cashRslt);
    # Mourn if the is not sufficient money
    if ($ret > $cash['amount']) {
        return "<li class=err>Error : Returned/Change amount is more than the requisistion amount.</li>\n\t\t<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
    }
    # Ya Nasty zero
    $ret += 0;
    $refnum = getrefnum($date);
    # Check available funds
    $cashacc = gethook("accnum", "bankacc", "name", "Petty Cash");
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$vatcode}' AND zero='Yes'";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    if (pg_num_rows($Ri) > 0) {
        $cash['chrgvat'] = "exc";
    }
    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 amount is not equal to zero, write tran
    if ($ret != 0) {
        # If subtract vat
        if ($cash['chrgvat'] == "inc") {
            # Get vat account
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            $VATP = TAX_VAT;
            //$vatret = sprint(($VATP/($VATP + 100)) * $ret);
            $sret = $ret - $vatret;
            # Write returning transaction
            writetrans($cashacc, $cash['accid'], date("Y-m-d"), $refnum, $sret, "Petty Cash Change");
            # Write VAT returning  transaction
            writetrans($cashacc, $vatacc, date("Y-m-d"), $refnum, $vatret, "VAT return, " . $cash['det']);
            vatr($vd['id'], date("Y-m-d"), "INPUT", $vd['code'], $refnum, "VAT return, " . $cash['det'], $sret + $vatret, $vatret);
            /*
            # Record vat statement
            db_connect();
            $sql = "INSERT INTO svatrec(edate, ref, amount, descript, div) VALUES('".date("Y-m-d")."', '$refnum', '$vatret', 'VAT returned on Petty Cash Change.', '".USER_DIV."')";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.",SELF);
            */
        } elseif ($cash['chrgvat'] == "exc") {
            # Get vat account
            $vatacc = gethook("accnum", "salesacc", "name", "VAT");
            $VATP = TAX_VAT;
            //$vatret = sprint(($VATP/100) * $ret);
            $sret = $ret;
            $ret += $vatret;
            # Write returning transaction
            writetrans($cashacc, $cash['accid'], date("Y-m-d"), $refnum, $sret, "Petty Cash Change");
            # Write VAT returning  transaction
            writetrans($cashacc, $vatacc, date("Y-m-d"), $refnum, $vatret, "VAT return, " . $cash['det']);
            vatr($vd['id'], date("Y-m-d"), "INPUT", $vd['code'], $refnum, "VAT return, " . $cash['det'], $sret + $vatret, $vatret);
            /*
            # Record vat statement
            db_connect();
            $sql = "INSERT INTO svatrec(edate, ref, amount, descript, div) VALUES('".date("Y-m-d")."', '$refnum', '$vatret', 'VAT returned on Petty Cash Change.', '".USER_DIV."')";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.",SELF);
            */
        } else {
            # Write returning transaction
            writetrans($cashacc, $cash['accid'], date("Y-m-d"), $refnum, $ret, "Petty Cash Change");
            $sret = $ret;
        }
        # Record tranfer for patty cash report
        db_connect();
        $date = date("Y-m-d");
        $sql = "INSERT INTO pettyrec(date, type, det, amount, name, div) VALUES ('{$date}', 'Change', 'Petty Cash Change', '{$ret}', 'Cash Received From : {$cash['name']}', '" . USER_DIV . "')";
        $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
    }
    if (!isset($sret)) {
        $sret = 0;
    }
    # Update
    db_connect();
    $sql = "UPDATE pettycashbook SET refno = '{$refno}', amount = (amount - '{$ret}'), reced = 'yes' WHERE cashid='{$cashid}' AND div = '" . USER_DIV . "'";
    $Rslt = db_exec($sql) or errDie("Unable to cancel cheque.", SELF);
    if (isset($docu)) {
        db_conn(YR_DB);
        $sql = "INSERT INTO documents(typeid, typename, xin, docref, docdate, docname, filename, mimetype, descrip, docu, div) VALUES ('prec', 'Petty Cash Receipt', '{$refno}', '{$refno}', '{$date}', '{$filename}', '{$filename}', '{$doctyp}', 'Receipt from {$cash['name']}', '{$docu}', '" . USER_DIV . "')";
        $docRslt = db_exec($sql) or errDie("Unable to add {$docname} to system.", SELF);
    }
    if (cc_TranTypeAcc($cashacc, $cash['accid']) != false) {
        $cc_trantype = cc_TranTypeAcc($cashacc, $cash['accid']);
        $cc = "<script> CostCenter('{$cc_trantype}', 'Petty Cash Receipt', '{$date}', '{$cash['det']}', '{$sret}', '../'); </script>";
    } else {
        $cc = "";
    }
    # Status report
    $write = "{$cc}\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width='30%'>\n\t\t<tr><th>Petty Cash Requisition Approved</th></tr>\n\t\t<tr class=datacell><td>Petty Cash Requisition has been approved .</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=15%>\n\t\t<tr><th>Quick Links</th></tr>\n\t\t<tr class='bg-odd'><td><a href='petty-req-add.php'>Add Petty Cash Requisition</a></td></tr>\n\t\t<tr class='bg-odd'><td><a href='pettycashbook-view.php'>View Petty Cash Requisitions</a></td></tr>\n\t\t<tr class='bg-odd'><td><a href='../main.php'>Main Menu</a></td></tr>\n\t</table>";
    return $write;
}
Пример #12
0
function write()
{
    # Get vars
    extract($_REQUEST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order 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.");
    # 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", 1, 20, "Invalid Unit Price for product number : <b>" . ($keys + 1) . "</b>.");
            if ($qtys[$keys] <= 0) {
                $v->isOk("#", "num", 0, 0, "Error : Item Quantity must be more than zero. Product number : <b>" . ($keys + 1) . "</b>");
            }
            if ($qtys[$keys] > $qts[$keys]) {
                $v->isOk("#", "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.");
            # Validate ddate[]
            $v->isOk($d_day[$keys], "num", 1, 2, "Invalid Delivery Date day.");
            $v->isOk($d_month[$keys], "num", 1, 2, "Invalid Delivery Date month.");
            $v->isOk($d_year[$keys], "num", 1, 5, "Invalid Delivery Date year.");
            $ddate[$keys] = $d_year[$keys] . "-" . $d_month[$keys] . "-" . $d_day[$keys];
            if (!checkdate($d_month[$keys], $d_day[$keys], $d_year[$keys])) {
                $v->isOk($ddate[$keys], "num", 1, 1, "Invalid Delivery Date.");
            }
        }
        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>";
        }
        return details($_POST, $err);
    }
    # 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> - Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $td = $pur['pdate'];
    # check if purchase 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");
    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);
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['delvat']}'";
    $Ri = db_exec($Sl);
    if (pg_num_rows($Ri) < 1) {
        $Sl = "SELECT * FROM vatcodes";
        $Ri = db_exec($Sl);
    }
    $vd = pg_fetch_array($Ri);
    $VATP = $vd['vat_amount'];
    if ($vd['zero'] != "Yes") {
        # If vat is not included (shipchrg)
        if ($pur['vatinc'] == "no") {
            $scvat = sprint($VATP / 100 * $shipchrg);
            $shipexvat = $shipchrg;
        } elseif ($pur['vatinc'] == "yes") {
            $scvat = sprint($shipchrg / ($VATP + 100) * $VATP);
            $shipexvat = $shipchrg - $scvat;
        } else {
            $scvat = 0;
            $shipexvat = $shipchrg;
        }
    } else {
        $scvat = 0;
        $shipexvat = $shipchrg;
    }
    db_conn("exten");
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # 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;
    $vatacc = gethook("accnum", "salesacc", "name", "VAT");
    $cvacc = gethook("accnum", "pchsacc", "name", "Cost Variance");
    $flag = TRUE;
    $checkid = 0;
    $nonstot = 0;
    foreach ($recvd as $sk => $keys) {
        if ($checkid == $ids[$keys]) {
            $flag = FALSE;
        } else {
            $flag = TRUE;
        }
        $checkid = $ids[$keys];
        # Skip zeros
        if ($qtys[$keys] <= 0) {
            continue;
        }
        db_connect();
        # 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;
        }
        # Get selected stock line
        $sql = "SELECT * FROM pur_items WHERE id = '{$ids[$keys]}' AND purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $stkd = pg_fetch_array($stkdRslt);
        if ($pur['vatinc'] == "yes") {
            $unitcost[$keys] = sprint(($stkd['amt'] - $stkd['svat']) / $stkd['qty']);
        } else {
            $unitcost[$keys] = sprint($stkd['amt'] / $stkd['qty']);
        }
        //$perc[$keys] = sprint((($unitcost[$keys]*$qtys[$keys])/$pur['subtot']) * 100);
        $perc[$keys] = sprint($unitcost[$keys] / $pur['subtot'] * 100);
        $ffs = $perc[$keys] * $qtys[$keys];
        # Get percentage from shipping charges excluding vat
        $shipc[$keys] = sprint($perc[$keys] / 100 * $shipexvat);
        //print "cost: percent:$ffs ship: part1".($unitcost[$keys]*$qtys[$keys])."part2".($shipc[$keys]*$qtys[$keys])."<br>";
        # add delivery charges = amt + del chrg excluding vat
        $unitcost[$keys] += $shipc[$keys];
        if ($stkd['udiscount'] > 0) {
            $discps = round($stkd['udiscount'] / 100 * $unitcost[$keys], 2);
        } else {
            $discps = 0;
        }
        $amt[$keys] = sprint($qtys[$keys] * $unitcost[$keys]);
        #serialized items are broken into multiples .... we only want to process the first ... so FLAG is used
        if (isset($invoice)) {
            $iq = $qtys[$keys];
            $iq += 0;
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            if ($pur['vatinc'] == "yes") {
                $iamount = $stkd['amt'];
            } else {
                $iamount = sprint($stkd['amt'] + $stkd['svat']);
            }
            if ($flag) {
                vatr($vd['id'], $pur['pdate'], "INPUT", $vd['code'], $refnum, "VAT for Purchase No. {$pur['purnum']}", -$iamount, -$stkd['svat']);
            }
            $Sl = "UPDATE pur_items SET iqty=iqty-'{$iq}' WHERE id='{$stkd['id']}'";
            $Ri = db_exec($Sl) or errDie("Unable to update invoice qty.");
        }
        $resub += $amt[$keys];
        # Update purchase items
        $sql = "\n\t\t\tUPDATE pur_items \n\t\t\tSET rqty = (rqty + '{$qtys[$keys]}'), ddate = '{$ddate[$keys]}' \n\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);
        $cc = "";
        if ($stkd['account'] > 0) {
            if ($pur['vatinc'] == "yes") {
                #calculate the vat of this amount as we dont store it !!
                $vatcod = $stkd['vatcode'] + 0;
                $get_v = "SELECT vat_amount FROM vatcodes WHERE id = '{$vatcod}' LIMIT 1";
                $run_v = db_exec($get_v) or errDie("Unable to get vatcode information.");
                $varr = pg_fetch_array($run_v);
                $clearvat = $varr['vat_amount'] + 0;
                $remvat = sprint($stkd['amt'] / ($clearvat + 100) * $clearvat);
                $nonstot = $nonstot + $stkd['amt'] - $remvat;
            } else {
                $nonstot = $nonstot + $stkd['amt'];
            }
            $stk['whid'] = $stkd['account'];
            $sql = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '" . USER_DIV . "' LIMIT 1";
            $banks = db_exec($sql);
            if (pg_numrows($banks) < 1) {
                return "<li class='err'> There are no accounts held at the selected Bank.\n\t\t\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
            }
            $barr = pg_fetch_array($banks);
            $bankid = $barr['bankid'];
            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);
            $cc_trantype = cc_TranTypeAcc($stkd['account'], $banklnk['accnum']);
        } else {
            # Update stock(ordered + qty, units + qty, csamt + (csamt + amt))
            $sql = "\n\t\t\t\tUPDATE stock \n\t\t\t\tSET ordered = (ordered - '{$qtys[$keys]}'), units = (units + '{$qtys[$keys]}' +'{$min_stock}'), csamt = (csamt + '{$amt[$keys]}') \n\t\t\t\tWHERE 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], $pur['supname'], $pur['purnum'], "pur", $td);
                $serial = $sers[$stkids[$keys]][$keys];
                db_connect();
                $sql = "\n\t\t\t\t\tINSERT INTO pserec (\n\t\t\t\t\t\tpurid, purnum, stkid, serno, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$pur['purnum']}', '{$stkids[$keys]}', '{$serial}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $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 = "\n\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, csprice, \n\t\t\t\t\tcsamt, details, div\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$td}', '{$stk['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'purchase', '{$qtys[$keys]}', '{$amt[$keys]}', \n\t\t\t\t\t'{$cspric}', 'Stock Received from Supplier : {$sup['supname']} - Order No. {$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t\t)";
            $recRslt = db_exec($sql);
            # Just wanted to fix the xxx.xxxxxxe-x value
            if ($stk['units'] > 0) {
                $csprice = round($stk['csamt'] / $stk['units'], 2);
            } else {
                $csprice = round($stk['csprice'], 2);
            }
            # update stock(csprice = (csamt/units))
            $sql = "\n\t\t\t\tUPDATE stock \n\t\t\t\tSET csprice = '{$csprice}', lcsprice = '{$cspric}' \n\t\t\t\tWHERE stkid = '{$stkids[$keys]}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
        }
        # Keep records for transactions
        if (isset($totstkamt[$stk['whid']])) {
            $totstkamt[$stk['whid']] += $amt[$keys];
        } else {
            $totstkamt[$stk['whid']] = $amt[$keys];
        }
        db_connect();
        # check if there are any outstanding items
        $sql = "SELECT * FROM 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 purchases SET received = 'y' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update Orders in Cubit.", SELF);
        }
        if ($min_stock > 0) {
            $cost = sprint($unitcost[$keys] * $min_stock);
            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 purchase {$pur['purnum']}");
            stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $td, 0, $cost, "Cost Of Sales for stock sold before purchase {$pur['purnum']}");
            db_connect();
            $Sl = "\n\t\t\t\tINSERT INTO pcost (\n\t\t\t\t\tpurnum, cost, qty, rqty, stkid\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$pur['purnum']}', '{$unitcost[$keys]}', '{$min_stock}', '0', '{$stk['stkid']}'\n\t\t\t\t)";
            $Ri = db_exec($Sl);
        }
    }
    //	$darr = explode ("-",$date);
    //	$cdate = "$darr[2]-$darr[1]-$darr[0]";
    #if non stock total is set, process the cost center
    if ($nonstot != "0") {
        $nonstot = sprint($nonstot);
        if ($cc_trantype != false) {
            $date = date("Y-m-d");
            $cc .= "\n\t\t\t\t<script>\n\t\t\t\t\tCostCenter('{$cc_trantype}', 'Non Stock Purchase', '{$date}', '{$stkd['description']}', {$nonstot}, '');\n\t\t\t\t</script>";
        } else {
            $cc .= "";
        }
    }
    if (isset($invoice)) {
        ###################VAT CALCS#######################
        $pur['delvat'] += 0;
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$pur['delvat']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            $Sl = "SELECT * FROM vatcodes";
            $Ri = db_exec($Sl);
        }
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        $vr = vatcalc($shipchrg, $pur['vatinc'], $excluding, 0, $vd['vat_amount']);
        $vrs = explode("|", $vr);
        $ivat_tmp = $vrs[0];
        $iamount_tmp = $vrs[1];
        vatr($vd['id'], $td, "INPUT", $vd['code'], $refnum, "VAT Paid for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.", sprint(-$iamount_tmp), -$scvat);
        ####################################################
        db_conn("exten");
        $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        db_connect();
        # update the supplier (make balance more)
        $sql = "UPDATE suppliers SET balance = (balance + '{$itotal}') WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        $sql = "\n\t\t\tINSERT INTO sup_stmnt (\n\t\t\t\tsupid, edate, cacc, amount, descript, ref, ex, div\n\t\t\t) VALUES (\n\t\t\t\t'{$pur['supid']}', '{$pur['pdate']}', '{$wh['conacc']}', '{$itotal}', \n\t\t\t\t'Stock Received - Purchase {$pur['purnum']} Inv:{$pur['supinv']}', '{$refnum}', '{$pur['purnum']}', '" . USER_DIV . "'\n\t\t\t)";
        $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, $isubtot, "Invoice Received for Purchase No. {$pur['purnum']} from Supplier : {$pur['supname']}.");
        # Transfer vat
        writetrans($vatacc, $dept['credacc'], $td, $refnum, $ivat, "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.", $itotal, '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 + '{$itotal}') 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 = "\n\t\t\t\t\tINSERT INTO suppurch (\n\t\t\t\t\t\tsupid, purid, pdate, balance, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$pur['supid']}', '{$pur['purnum']}', '{$pur['pdate']}', '{$itotal}', '" . USER_DIV . "'\n\t\t\t\t\t)";
            $purcRslt = db_exec($sql) or errDie("Unable to update Order information in Cubit.", SELF);
        }
        /* Make transaction record  for age analysis */
        # commit updating
        $sql = "UPDATE purchases SET iamount = iamount+'{$itotal}',ivat=ivat+'{$ivat}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
        $sql = "SELECT SUM(iqty) FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
        $stktRslt = db_exec($sql);
        $data = pg_fetch_array($stktRslt);
        $left = $data['sum'];
        if ($left == 0) {
            /* Start moving if purchase */
            if ($pur['received'] == "y") {
                if (strlen($pur['appdate']) < 8) {
                    $pur['appdate'] = date("Y-m-d");
                }
                # copy purchase
                db_conn($pur['prd']);
                $sql = "\n\t\t\t\t\tINSERT INTO purchases (\n\t\t\t\t\t\tpurid, deptid, supid, supname, supaddr, supno, \n\t\t\t\t\t\tterms, pdate, ddate, shipchrg, subtot, total, \n\t\t\t\t\t\tbalance, vatinc, vat, shipping, remarks, refno, received, done, \n\t\t\t\t\t\tdiv, purnum, supinv, ordernum, appname, appdate\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', \n\t\t\t\t\t\t'{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', \n\t\t\t\t\t\t'0', '{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$remarks}', '{$pur['refno']}', 'y', 'y', \n\t\t\t\t\t\t'" . USER_DIV . "', '{$pur['purnum']}', '{$supinv}', '{$pur['ordernum']}', '{$pur['appname']}', '{$pur['appdate']}'\n\t\t\t\t\t)";
                $rslt = db_exec($sql) or errDie("Unable to insert Order to Cubit.", SELF);
                /*-- Cost varience -- */
                //$nsubtot = sprint($pur['total'] - $pur['vat']);
                $nsubtot = sprint($p['iamount'] - $p['ivat']);
                if ($p['rsubtot'] > $nsubtot) {
                    $diff = sprint($p['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 > $p['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($pur['prd']);
                    $sql = "\n\t\t\t\t\t\tINSERT INTO pur_items (\n\t\t\t\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, \n\t\t\t\t\t\t\tamt, svat, ddate, div\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', \n\t\t\t\t\t\t\t'{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "'\n\t\t\t\t\t\t)";
                    $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
                }
                # begin updating
                //pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);
                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
                //pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);
            } else {
                # insert Order to DB
                $sql = "UPDATE purchases SET invcd = 'y',supinv='{$pur['supinv']}' WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update Order status in Cubit.", SELF);
            }
        }
    }
    if (strlen($refno) > 0) {
        if (strlen($pur['refno']) > 0) {
            $refno = "{$pur['refno']}-{$refno}";
        } else {
            $refno = $refno;
        }
    } else {
        $refno = $pur['refno'];
    }
    db_connect();
    # Update purchase on the DB
    if ($pur['part'] == 'y') {
        $sql = "\n\t\t\tUPDATE purchases \n\t\t\tSET rsubtot = (rsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', edit = 1 \n\t\t\tWHERE purid = '{$purid}'";
    } else {
        $sql = "\n\t\t\tUPDATE purchases \n\t\t\tSET part = 'y', rsubtot = (rsubtot + '{$resub}'), refno = '{$refno}', remarks = '{$remarks}', edit = 1 \n\t\t\tWHERE purid = '{$purid}'";
    }
    $rslt = db_exec($sql) or errDie("Unable to update Order in Cubit.", SELF);
    /* Transactions */
    db_conn(PRD_DB);
    # get last ref number
    //$refnum = getrefnum();
    /* - Start Hooks - */
    /* - 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);
        if (pg_num_rows($whRslt) < 1) {
            $sql = "SELECT stkacc,conacc FROM warehouses";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            $wh['stkacc'] = $whid;
        } else {
            $wh = pg_fetch_array($whRslt);
        }
        # Debit Stock and Credit Stock control
        writetrans($wh['stkacc'], $wh['conacc'], $td, $refnum, $wamt, "Stock Received for Purchase No. {$pur['purnum']} 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 purchase info
    db_connect();
    $sql = "SELECT * FROM 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" && $pur['invcd'] == 'y') {
        if (strlen($pur['appdate']) < 8) {
            $pur['appdate'] = date("Y-m-d");
        }
        # copy purchase
        db_conn(PRD_DB);
        $sql = "\n\t\t\t\tINSERT INTO purchases (\n\t\t\t\t\tpurid, deptid, supid, supname, supaddr, supno, \n\t\t\t\t\tterms, pdate, ddate, shipchrg, subtot, total, balance, \n\t\t\t\t\tvatinc, vat, shipping, remarks, refno, received, done, div, \n\t\t\t\t\tpurnum, supinv, ordernum, appname, appdate, delvat\n\t\t\t\t) VALUES (\n\t\t\t\t\t'{$purid}', '{$pur['deptid']}', '{$pur['supid']}',  '{$pur['supname']}', '{$pur['supaddr']}', '{$pur['supno']}', \n\t\t\t\t\t'{$pur['terms']}', '{$pur['pdate']}', '{$pur['ddate']}', '{$pur['shipchrg']}', '{$pur['subtot']}', '{$pur['total']}', '0', \n\t\t\t\t\t'{$pur['vatinc']}', '{$pur['vat']}', '{$pur['shipping']}', '{$pur['remarks']}', '{$pur['refno']}', 'y', 'y', '" . USER_DIV . "', \n\t\t\t\t\t'{$pur['purnum']}', '{$pur['supinv']}', '{$pur['ordernum']}', '{$pur['appname']}', '{$pur['appdate']}', '{$pur['delvat']}'\n\t\t\t\t)";
        $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 = "\n\t\t\t\t\tINSERT INTO pur_items (\n\t\t\t\t\t\tpurid, whid, stkid, qty, rqty, unitcost, \n\t\t\t\t\t\tamt, svat, ddate, div, vatcode, \n\t\t\t\t\t\taccount, description, udiscount\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$purid}', '{$stktc['whid']}', '{$stktc['stkid']}', '{$stktc['qty']}', '{$stktc['rqty']}', '{$stktc['unitcost']}', \n\t\t\t\t\t\t'{$stktc['amt']}', '{$stktc['svat']}', '{$stktc['ddate']}', '" . USER_DIV . "','{$stktc['vatcode']}', \n\t\t\t\t\t\t'{$stktc['account']}', '{$stktc['description']}', '{$stktc['udiscount']}'\n\t\t\t\t\t)";
            $rslt = db_exec($sql) or errDie("Unable to insert Order items to Cubit.", SELF);
        }
        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 Orders 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 Orders 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 Orders information in Cubit.", SELF);
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    /* End moving purchase received */
    if (isset($gds_note) and strlen($gds_note) > 0) {
        $cc .= "\n\t\t\t<script>\n\t\t\t\tprinter(\"" . SELF . "?key=recv_print&purid={$purid}\");\n\t\t\t</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>Order received</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Order receipt 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='purchase-new.php'>New Purchase</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='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;
}