function recvpayment()
{
    extract($_POST);
    $v = new validate();
    $v->isOk($cusnum, "num", 1, 10, "Invalid customer id.");
    $v->isOk($invid, "num", 1, 10, "Invalid invoice id.");
    $v->isOk($pcc, "float", 1, 40, "Invalid credit card amount.");
    $v->isOk($pcash, "float", 1, 40, "Invalid cash amount.");
    $v->isOk($pcheque, "float", 1, 40, "Invalid cheque amount.");
    $date = mkdate($pinv_year, $pinv_month, $pinv_day);
    $v->isOk($date, "date", 1, 1, "Invalid invoice date.");
    if ($v->isError()) {
        return details($_POST, $v->genErrors());
    }
    $amt = sprint($pcc + $pcash + $pcheque);
    $cus = qryCustomer($cusnum);
    $bank_acc = qryAccountsName("Cash on Hand");
    $OUT = "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th colspan='2'>Payment Details</th>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Account</td>\n\t\t<td>{$bank_acc['topacc']}/{$bank_acc['accnum']} {$bank_acc['accname']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Date</td>\n\t\t<td valign='center'>{$date}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Received from</td>\n\t\t<td valign='center'>{$cus['cusname']} {$cus['surname']}</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Description</td>\n\t\t<td valign='center'>POS Payment Received</td>\n\t</tr>\n\t<tr class='" . bg_class() . "'>\n\t\t<td>Amount</td>\n\t\t<td valign='center'>" . CUR . " {$amt}</td>\n\t</tr>\n\t</table>\n\n\t<form method='post' action='" . SELF . "'>\n\t<input type='hidden' name='key' value='recvpayment_write' />\n\t<input type='hidden' name='bank_acc' value='{$bank_acc['accid']}' />\n\t<input type='hidden' name='invid' value='{$invid}' />\n\t<input type='hidden' name='pcc' value='{$pcc}' />\n\t<input type='hidden' name='pcash' value='{$pcash}' />\n\t<input type='hidden' name='pcheque' value='{$pcheque}' />\n\t<input type='hidden' name='amt' value='{$amt}' />\n\t<input type='hidden' name='date' value='{$date}' />\n\t<input type='hidden' name='cusnum' value='{$cusnum}' />\n\t<input type='hidden' name='descript' value='POS Payment Received' />\n\n\t<input type='hidden' name='stkerr' value='{$stkerr}' />\n\t<input type='hidden' name='prev_cusnum' value='{$prev_cusnum}' />\n\t<input type='hidden' name='deptid' value='{$deptid}' />\n\t<input type='hidden' name='telno' value='{$telno}' />\n\t<input type='hidden' name='cordno' value='{$cordno}' />\n\t<input type='hidden' name='bar' value='{$bar}' />\n\t<input type='hidden' name='des' value='{$des}' />\n\t<input type='hidden' name='sel_frm' value='{$sel_frm}' />\n\t<input type='hidden' name='ordno' value='{$ordno}' />\n\t<input type='hidden' name='pinv_day' value='{$pinv_day}' />\n\t<input type='hidden' name='pinv_month' value='{$pinv_month}' />\n\t<input type='hidden' name='pinv_year' value='{$pinv_year}' />\n\t<input type='hidden' name='chrgvat' value='{$chrgvat}' />\n\t<input type='hidden' name='salespn' value='{$salespn}' />\n\t<input type='hidden' name='traddisc' value='{$traddisc}' />\n\t<input type='hidden' name='delchrg' value='{$delchrg}' />\n\t<input type='hidden' name='delvat' value='{$delvat}' />\n\t<input type='hidden' name='user' value='{$user}' />\n\t<input type='hidden' name='SUBTOT' value='{$subtot}' />\n\t<input type='hidden' name='comm' value='{$comm}' />\n\n\t<table " . TMPL_tblDflts . ">";
    // Connect to database
    db_connect();
    $sql = "SELECT invnum,invid,balance,terms,odate FROM invoices\n\t\t\tWHERE cusnum = '{$cusnum}' AND printed = 'y' AND balance>0\n\t\t\t\tAND div = '" . USER_DIV . "'\n\t\t\tORDER BY odate ASC";
    $prnInvRslt = db_exec($sql);
    $i = 0;
    while (($inv = pg_fetch_array($prnInvRslt)) && $amt > 0) {
        if ($i == 0) {
            $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>&nbsp;</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><h3>Outstanding Invoices</h3></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Invoice</th>\n\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t<th>Terms</th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t</tr>";
        }
        $invid = $inv['invid'];
        $val = allocamt($amt, $inv["balance"]);
        $OUT .= "\n\t\t<input type='hidden' name='paidamt[{$invid}]' size=10 value='{$val}'>\n\t\t<input type='hidden' size=20 name=invids[{$invid}] value='{$inv['invid']}'>\n\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t<td>{$inv['odate']}</td>\n\t\t\t<td>" . CUR . " {$val}</td>\n\t\t</tr>";
    }
    $sql = "SELECT invnum,invid,balance,sdate as odate FROM nons_invoices\n\t\t\tWHERE cusid='{$cusnum}' AND done='y' AND balance>0\n\t\t\t\tAND div='" . USER_DIV . "'\n\t\t\tORDER BY odate ASC";
    $prnInvRslt = db_exec($sql);
    while (($inv = pg_fetch_array($prnInvRslt)) && $amt > 0) {
        if ($i == 0) {
            $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>&nbsp;</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><h3>Outstanding Non-Stock Invoices</h3></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Invoice</th>\n\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t<th></th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t</tr>";
        }
        $invid = $inv['invid'];
        $val = allocamt($amt, $inv["balance"]);
        $OUT .= "\n\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' value='{$val}'>\n\t\t\t\t<input type='hidden' name='itype[{$invid}]' value='Yes'>\n\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t<td><input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>{$inv['invnum']}</td>\n\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t</tr>";
    }
    $amt = sprint($amt);
    /* pos invoices */
    $sqls = array();
    for ($i = 1; $i <= 12; ++$i) {
        $sqls[] = "SELECT invnum,invid,balance,odate FROM \"{$i}\".pinvoices\n\t\t\t\t\tWHERE cusnum='{$cusnum}' AND done='y' AND balance>0\n\t\t\t\t\t\tAND div='" . USER_DIV . "'";
    }
    $sql = implode(" UNION ", $sqls);
    $prnInvRslt = db_exec($sql);
    if (pg_numrows($prnInvRslt) > 0) {
        $OUT .= "\n\t\t<tr>\n\t\t\t<td colspan='2'><br></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td colspan='2'><h3>Outstanding POS Invoices</h3></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th>Invoice</th>\n\t\t\t<th>Outstanding Amount</th>\n\t\t\t<th></th>\n\t\t\t<th>Date</th>\n\t\t\t<th>Amount</th>\n\t\t</tr>";
        $i = 0;
        while ($inv = pg_fetch_array($prnInvRslt)) {
            $invid = $inv['invid'];
            $val = allocamt($amt, $inv["balance"]);
            $OUT .= "\n\t\t\t<input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>\n\t\t\t<input type='hidden' name='paidamt[{$invid}]' size=10 value='{$val}'>\n\t\t\t<input type='hidden' name='ptype[{$invid}]' value='YnYn'>\n\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t<td></td>\n\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t</tr>";
        }
    }
    if ($amt > 0) {
        /* START OPEN ITEMS */
        $ox = "";
        $sql = "SELECT * FROM cubit.open_stmnt WHERE balance>0 AND cusnum='{$cusnum}'\n\t\t\t\t\tAND type!='Invoice' AND type!='Non-Stock Invoice'\n\t\t\t\t\tAND type!='Interest on Outstanding balance'\n\t\t\t\tORDER BY date";
        $rslt = db_exec($sql) or errDie("Unable to get open items.");
        $open_out = $amt;
        $i = 0;
        while ($od = pg_fetch_array($rslt)) {
            if ($open_out == 0) {
                continue;
            }
            $oid = $od['id'];
            if ($open_out >= $od['balance']) {
                $open_amount[$oid] = $od['balance'];
                $open_out = sprint($open_out - $od['balance']);
                $ox .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$oid}]' value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t<td><input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t</tr>";
            } elseif ($open_out < $od['balance']) {
                $open_amount[$oid] = $open_out;
                $open_out = 0;
                $ox .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$oid}]' value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t<td><input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t</tr>";
            }
            $i++;
        }
        if (open()) {
            $OUT .= "\n\t\t\t" . TBL_BR . "\n\t\t\t<input type='hidden' name='bout' value='{$amt}'>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'><h3>Outstanding Transactions</h3></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Description</th>\n\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t</tr>";
            $OUT .= $ox;
            $bout = $amt;
            $amt = $open_out;
            if ($amt > 0) {
                $OUT .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='4'><b>A general transaction will credit the client's account with " . CUR . " {$amt}</b></td>\n\t\t\t\t</tr>";
            }
            //$amt=$bout;
        } else {
            $OUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='4'><b>A general transaction will credit the client's account with " . CUR . " {$amt} </b></td>\n\t\t\t</tr>";
        }
    }
    $OUT .= "\n\t<input type='hidden' name='out' value='{$amt}' />\n\t<tr>\n\t\t<td colspan='5' align='right'>\n\t\t\t<input type='submit' name='btn_back' value='&laquo; Correction' />\n\t\t\t<input type='submit' value='Record Payment' />\n\t\t</td>\n\t</table>";
    return $OUT;
}
function alloc($_POST, $err = "")
{
    extract($_POST);
    if (isset($back)) {
        if (isset($e)) {
            header("Location: cashbook-entry.php");
            exit;
        }
        return sel_cus($_POST);
    }
    if (isset($print_recpt) and strlen($print_recpt) > 0) {
        $send_print = "<input type='hidden' name='print_recpt' value='{$print_recpt}'>";
    } else {
        $send_print = "";
    }
    if (isset($bulk_pay) and strlen($bulk_pay) > 0) {
        $send_bulk = "<input type='hidden' name='bulk_pay' value='yes'>";
    } else {
        $send_bulk = "";
    }
    $all = 0;
    $date_arr = explode("-", $tdate);
    $date_year = $date_arr[0];
    $date_month = $date_arr[1];
    $date_day = $date_arr[2];
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Select Bank Account.");
    $v->isOk($date_day, "num", 1, 2, "Invalid Date day.");
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    $v->isOk($date_month, "num", 1, 2, "Invalid Date month.");
    $v->isOk($date_year, "num", 1, 4, "Invalid Date Year.");
    $v->isOk($descript, "string", 0, 255, "Invalid Description.");
    $v->isOk($reference, "string", 0, 50, "Invalid Reference Name/Number.");
    $v->isOk($cheqnum, "num", 0, 30, "Invalid Cheque number.");
    $v->isOk($amt, "float", 1, 40, "Invalid amount.");
    $v->isOk($cusid, "num", 1, 10, "Invalid customer number.");
    if (strlen($date_year) != 4) {
        $v->isOk($bankname, "num", 1, 1, "Invalid Date year.");
    }
    if ($amt < 0.01) {
        $v->addError($amt, "Amount too small.");
    }
    $date = $date_day . "-" . $date_month . "-" . $date_year;
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        $confirm .= "<br>" . "<input type='button' onClick='history.back();' value='&laquo Correction'>";
        return $confirm;
        //.alloc($_POST);
    }
    # CHECK IF THIS DATE IS IN THE BLOCKED RANGE
    $blocked_date_from = getCSetting("BLOCKED_FROM");
    $blocked_date_to = getCSetting("BLOCKED_TO");
    if (strtotime($date) >= strtotime($blocked_date_from) and strtotime($date) <= strtotime($blocked_date_to) and !user_is_admin(USER_ID)) {
        return "<li class='err'>Period Range Is Blocked. Only an administrator can process entries within this period.</li>";
    }
    // bank account name
    if ($bankid == "0" or ($bank = qryBankAcct($bankid, "accname, bankname")) === false) {
        $bank['accname'] = "Cash";
        $bank['bankname'] = "";
    }
    // customer name
    $cus = qryCustomer($cusid, "cusname, surname");
    if ($print_recpt == "yes") {
        $show_print_recpt = "Yes";
    } else {
        $show_print_recpt = "No";
    }
    $confirm = "\n\t\t<h3>New Bank Receipt</h3>\n\t\t{$err}\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t<input type='hidden' name='accnum' value=''>\n\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t\t<input type='hidden' name='date' value='{$date}'>\n\t\t\t<input type='hidden' name='all' value='{$all}'>\n\t\t\t<input type='hidden' name='cusid' value='{$cusid}'>\n\t\t\t<input type='hidden' name='date_day' value='{$date_day}'>\n\t\t\t<input type='hidden' name='date_month' value='{$date_month}'>\n\t\t\t<input type='hidden' name='date_year' value='{$date_year}'>\n\t\t\t<input type='hidden' name='descript' value='{$descript}'>\n\t\t\t<input type='hidden' name='reference' value='{$reference}'>\n\t\t\t<input type='hidden' name='cheqnum' value='{$cheqnum}'>\n\t\t\t<input type='hidden' name='amt' value='{$amt}'>\n\t\t\t{$send_bulk}\n\t\t\t{$send_print}\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Field</th>\n\t\t\t\t<th>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Account</td>\n\t\t\t\t<td>{$bank['accname']} - {$bank['bankname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Date</td>\n\t\t\t\t<td valign='center'>{$date}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Received from</td>\n\t\t\t\t<td valign='center'>{$cus['cusname']} {$cus['surname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Description</td>\n\t\t\t\t<td valign='center'>" . nl2br($descript) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Reference</td>\n\t\t\t\t<td valign='center'>{$reference}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Cheque Number</td>\n\t\t\t\t<td valign='center'>{$cheqnum}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Amount</td>\n\t\t\t\t<td valign='center'>" . CUR . " {$amt}</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Print Receipt</td>\n\t\t\t\t<td>{$show_print_recpt}</td>\n\t\t\t</tr>";
    /* OPTION 1 : AUTO ALLOCATE (allocate) */
    #we need a new why of allocating this ... stock,nonstock,pos order is counter productive
    #so, we get them all into an array, and sort that ...
    if ($all == 0) {
        $out = $amt;
        $invs_arr = array();
        // Connect to database
        db_connect();
        #####################[ GET OUTSTANDING INVOICES ]######################
        $sql = "SELECT invnum, invid, balance, terms, odate FROM invoices WHERE cusnum = '{$cusid}' AND printed = 'y' AND balance>0 AND div = '" . USER_DIV . "' ORDER BY odate ASC";
        $prnInvRslt = db_exec($sql);
        while (($inv = pg_fetch_array($prnInvRslt)) && $out > 0) {
            $invs_arr[] = array("s", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
        }
        #####################[ GET OUTSTANDING NON STOCK INVOICES ]######################
        $sql = "SELECT invnum, invid, balance, odate FROM nons_invoices WHERE cusid='{$cusid}' AND done='y' AND balance>0 AND div='" . USER_DIV . "' ORDER BY odate ASC";
        $prnInvRslt = db_exec($sql);
        while (($inv = pg_fetch_array($prnInvRslt)) && $out > 0) {
            $invs_arr[] = array("n", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
        }
        $out = sprint($out);
        #####################[ GET OUTSTANDING POS INVOICES ]######################
        $sqls = array();
        for ($i = 1; $i <= 12; ++$i) {
            $sqls[] = "\n\t\t\t\tSELECT invnum, invid, balance, odate \n\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\tWHERE cusnum='{$cusid}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "'";
        }
        $sql = implode(" UNION ", $sqls);
        $prnInvRslt = db_exec($sql);
        while ($inv = pg_fetch_array($prnInvRslt)) {
            $invs_arr[] = array("p", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
        }
        if (isset($invs_arr) and is_array($invs_arr)) {
            $confirm .= "\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Type</th>\n\t\t\t\t\t<th>Invoice</th>\n\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t<th></th>\n\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t<th>Amount</th>\n\t\t\t\t</tr>";
        }
        #compile results into an array we can sort by date
        $search_arr = array();
        foreach ($invs_arr as $key => $array) {
            $search_arr[$key] = $array[1];
        }
        #sort array by date
        asort($search_arr);
        #add sorted invoices to payment listing
        foreach ($search_arr as $key => $date) {
            $arr = $invs_arr[$key];
            if ($arr[0] == "s") {
                $get_sql = "SELECT invnum, invid, balance, terms, odate FROM invoices WHERE cusnum = '{$cusid}' AND printed = 'y' AND balance>0 AND div = '" . USER_DIV . "' AND invid = '{$arr['2']}'  LIMIT 1";
                $run_sql = db_exec($get_sql) or errDie("Unable to get stock invoice information.");
                if (pg_numrows($run_sql) > 0) {
                    $inv = pg_fetch_array($run_sql);
                    $invid = $inv['invid'];
                    $val = allocamt($out, $inv["balance"]);
                    $confirm .= "\n\t\t\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' size='10' value='{$val}'>\n\t\t\t\t\t\t<input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t<td>Stock Invoice</td>\n\t\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t</tr>";
                }
            } elseif ($arr[0] == "n") {
                //sdate as
                $get_sql = "SELECT invnum, invid, balance, odate FROM nons_invoices WHERE cusid='{$cusid}' AND done='y' AND balance>0 AND div='" . USER_DIV . "' AND invid = '{$arr['2']}' LIMIT 1";
                $run_sql = db_exec($get_sql) or errDie("Unable to get non stock information.");
                if (pg_numrows($run_sql) > 0) {
                    $inv = pg_fetch_array($run_sql);
                    $invid = $inv['invid'];
                    $val = allocamt($out, $inv["balance"]);
                    $confirm .= "\n\t\t\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' value='{$val}'>\n\t\t\t\t\t\t<input type='hidden' name='itype[{$invid}]' value='Yes'>\n\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t<td>Non Stock Invoice</td>\n\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t</tr>";
                }
            } else {
                $sqls = array();
                for ($i = 1; $i <= 12; ++$i) {
                    $sqls[] = "\n\t\t\t\t\t\tSELECT invnum, invid, balance, odate \n\t\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\t\tWHERE cusnum='{$cusid}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "' AND invid = '{$arr['2']}'";
                }
                $get_sql = implode(" UNION ", $sqls);
                $run_sql = db_exec($get_sql) or errDie("Unable to get pos invoice information.");
                if (pg_numrows($run_sql) > 0) {
                    $inv = pg_fetch_array($run_sql);
                    $invid = $inv['invid'];
                    $val = allocamt($out, $inv["balance"]);
                    $confirm .= "\n\t\t\t\t\t\t<input type='hidden' size='20' name='invids[{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t\t<input type='hidden' name='paidamt[{$invid}]' size='10' value='{$val}'>\n\t\t\t\t\t\t<input type='hidden' name='ptype[{$invid}]' value='YnYn'>\n\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t<td>POS Invoice</td>\n\t\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t</tr>";
                }
            }
        }
        #if there is any amount unallocated, it goes to general transaction
        $confirm .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='6'><b>A general transaction will credit the client's account with " . CUR . " {$out} </b></td>\n\t\t\t</tr>";
    }
    vsprint($out);
    $confirm .= "\n\t\t\t<input type='hidden' name='out' value='{$out}'>\n\t\t\t<tr>\n\t\t\t\t<td><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t\t<td align='right'><input type='submit' value='Confirm &raquo'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>" . mkQuickLinks(ql("../core/trans-new.php", "Journal Transactions"), ql("../customers-view.php", "View Customers"));
    return $confirm;
}
function cp2($id, $amount, $description, $contra, $refnum, $date, $cheque = 0, $bankid)
{
    $cheque += 0;
    $sdate = date("Y-m-d");
    $accdate = $date;
    if ($accdate == 0) {
        $accdate = date("Y-m-d");
    }
    $cus = qryCustomer($id, "cusnum, deptid, cusname, surname");
    $dept = qryDepartment($cus["deptid"], "debtacc");
    // 	db_connect();
    //
    // 	$Sl = "SELECT cusnum,deptid,cusname,surname FROM customers WHERE cusnum = '$id' AND div = '".USER_DIV."'";
    // 	$Ri = db_exec($Sl) or errDie("Unable to get data.");
    // 	$cus = pg_fetch_array($Ri);
    db_conn('core');
    $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
    $Rx = db_exec($Sl) or errDie("Uanble to get bank acc.");
    if (pg_numrows($Rx) < 1) {
        return "Invalid bank acc.";
    }
    $link = pg_fetch_array($Rx);
    #######################################################################################################
    ########################################### COMPILE ###################################################
    #######################################################################################################
    $out = $amount;
    $invs_arr = array();
    // Connect to database
    db_connect();
    #####################[ GET OUTSTANDING INVOICES ]######################
    $sql = "\n\t\tSELECT invnum, invid, balance, terms, odate \n\t\tFROM invoices \n\t\tWHERE cusnum = '{$id}' AND printed = 'y' AND balance>0 AND div = '" . USER_DIV . "' ORDER BY odate ASC";
    $prnInvRslt = db_exec($sql);
    while (($inv = pg_fetch_array($prnInvRslt)) && $out > 0) {
        $invs_arr[] = array("s", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
    }
    #####################[ GET OUTSTANDING NON STOCK INVOICES ]######################
    $sql = "\n\t\tSELECT invnum, invid, balance, odate \n\t\tFROM nons_invoices \n\t\tWHERE cusid='{$id}' AND done='y' AND balance>0 AND div='" . USER_DIV . "' ORDER BY odate ASC";
    $prnInvRslt = db_exec($sql);
    while (($inv = pg_fetch_array($prnInvRslt)) && $out > 0) {
        $invs_arr[] = array("n", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
    }
    $out = sprint($out);
    #####################[ GET OUTSTANDING POS INVOICES ]######################
    $sqls = array();
    for ($i = 1; $i <= 12; ++$i) {
        $sqls[] = "\n\t\t\tSELECT invnum, invid, balance, odate \n\t\t\tFROM \"{$i}\".pinvoices \n\t\t\tWHERE cusnum='{$id}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "'";
    }
    $sql = implode(" UNION ", $sqls);
    $prnInvRslt = db_exec($sql);
    while ($inv = pg_fetch_array($prnInvRslt)) {
        $invs_arr[] = array("p", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
    }
    #compile results into an array we can sort by date
    $search_arr = array();
    foreach ($invs_arr as $key => $array) {
        $search_arr[$key] = $array[1];
    }
    #sort array by date
    asort($search_arr);
    #add sorted invoices to payment listing
    foreach ($search_arr as $key => $date) {
        $arr = $invs_arr[$key];
        if ($arr[0] == "s") {
            db_connect();
            $get_sql = "\n\t\t\t\tSELECT invnum, invid, balance, terms, odate \n\t\t\t\tFROM invoices \n\t\t\t\tWHERE cusnum = '{$id}' AND printed = 'y' AND balance>0 AND div = '" . USER_DIV . "' AND invid = '{$arr['2']}'  LIMIT 1";
            $run_sql = db_exec($get_sql) or errDie("Unable to get stock invoice information.");
            if (pg_numrows($run_sql) > 0) {
                $inv = pg_fetch_array($run_sql);
                $invid = $inv['invid'];
                $val = allocamt($out, $inv["balance"]);
                if ($val == 0.0) {
                    continue;
                }
                $inv['invnum'] += 0;
                // reduce invoice balance
                $sql = "\n\t\t\t\t\tUPDATE cubit.invoices \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$id}','{$inv['invnum']}', '" . ($val - $val * 2) . "', '{$accdate}', \n\t\t\t\t\t\t'Payment for Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $link['accnum'], $accdate, $inv['invnum'], "Payment for Invoice No. {$inv['invnum']}", $val, "c");
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                if ($inv['prd'] == "0") {
                    $inv['prd'] = PRD_DB;
                }
                $invprds .= "|{$inv['prd']}";
                $rages .= "|0";
                $invidsers .= " - {$inv['invnum']}";
            }
        } elseif ($arr[0] == "n") {
            db_connect();
            $get_sql = "\n\t\t\t\tSELECT invnum, invid, balance, odate \n\t\t\t\tFROM nons_invoices \n\t\t\t\tWHERE cusid='{$id}' AND done='y' AND balance>0 AND div='" . USER_DIV . "' AND invid = '{$arr['2']}' LIMIT 1";
            $run_sql = db_exec($get_sql) or errDie("Unable to get non stock information.");
            if (pg_numrows($run_sql) > 0) {
                $inv = pg_fetch_array($run_sql);
                $invid = $inv['invid'];
                $val = allocamt($out, $inv["balance"]);
                if ($val == 0.0) {
                    continue;
                }
                $inv['invnum'] += 0;
                # reduce the money that has been paid
                $sql = "\n\t\t\t\t\tUPDATE cubit.nons_invoices \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, \n\t\t\t\t\t\tdiv, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$id}', '{$inv['invnum']}', '" . ($val - $val * 2) . "', '{$accdate}', \n\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}', \n\t\t\t\t\t\t'" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $link['accnum'], $accdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']} - {$inv['descrip']}", $val, "c");
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                $invprds .= "|0";
                $rages .= "|{$inv['age']}";
                $invidsers .= " - {$inv['invnum']}";
            }
        } else {
            db_connect();
            $sqls = array();
            for ($i = 1; $i <= 12; ++$i) {
                $sqls[] = "\n\t\t\t\t\tSELECT invnum, invid, balance, odate, '{$i}' AS prd  \n\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\tWHERE cusnum='{$id}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "' AND invid = '{$arr['2']}'";
            }
            $get_sql = implode(" UNION ", $sqls);
            $run_sql = db_exec($get_sql) or errDie("Unable to get pos invoice information.");
            if (pg_numrows($run_sql) > 0) {
                $inv = pg_fetch_array($run_sql);
                $invid = $inv['invid'];
                $val = allocamt($out, $inv["balance"]);
                if ($val == 0.0) {
                    continue;
                }
                // reduce the invoice balance
                $sql = "\n\t\t\t\t\tUPDATE \"{$inv['prd']}\".pinvoices \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                $sql = "\n\t\t\t\t\tUPDATE cubit.open_stmnt \n\t\t\t\t\tSET balance = (balance - {$val}::numeric(13,2)) \n\t\t\t\t\tWHERE invid = '{$inv['invnum']}' AND div = '" . USER_DIV . "'";
                $payRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
                # record the payment on the statement
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, date, \n\t\t\t\t\t\ttype, div, allocation_date\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cus['cusnum']}', '{$inv['invnum']}', '" . ($val - $val * 2) . "', '{$accdate}', \n\t\t\t\t\t\t'Payment for Non Stock Invoice No. {$inv['invnum']}', '" . USER_DIV . "', '{$inv['odate']}'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
                custledger($cus['cusnum'], $link['accnum'], $accdate, $inv['invnum'], "Payment for Non Stock Invoice No. {$inv['invnum']}", $val, "c");
                $rinvids .= "|{$invids[$key]}";
                $amounts .= "|{$paidamt[$key]}";
                $invprds .= "|{$inv['prd']}";
                $rages .= "|0";
                $invidsers .= " - {$inv['invnum']}";
            }
        }
    }
    #if there is any amount unallocated, it goes to general transaction
    $confirm .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='6'><b>A general transaction will credit the client's account with " . CUR . " {$out} </b></td>\n\t\t</tr>";
    vsprint($out);
    $confirm .= "<input type='hidden' name='out' value='{$out}'>";
    ###############################################################################################################################
    ###############################################################################################################################
    ###############################################################################################################################
    #######################################################################################################
    ########################################### PROCESS ###################################################
    #######################################################################################################
    # update the customer (make balance less)
    $sql = "\n\t\tUPDATE cubit.customers \n\t\tSET balance = (balance - '{$amount}'::numeric(13,2)) \n\t\tWHERE cusnum = '{$id}' AND div = '" . USER_DIV . "'";
    $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
    $cols = grp(m("bankid", $bankid), m("trantype", "deposit"), m("date", $accdate), m("name", "{$cus['cusname']} {$cus['surname']}"), m("descript", "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}"), m("cheqnum", $cheque), m("amount", $amount), m("banked", "no"), m("accinv", $dept["debtacc"]), m("cusnum", $cus["cusnum"]), m("rinvids", $rinvids), m("amounts", $amounts), m("invprds", $invprds), m("rages", $rages), m("reference", $reference), m("div", USER_DIV));
    $dbobj = new dbUpdate("cashbook", "cubit", $cols);
    $dbobj->run(DB_INSERT);
    $dbobj->free();
    writetrans($link['accnum'], $dept['debtacc'], $accdate, $refnum, $amount, "Payment for Invoices {$invidsers} from customer {$cus['cusname']} {$cus['surname']}");
    db_conn('cubit');
    if ($out > 0) {
        /* START OPEN ITEMS */
        $openstmnt = new dbSelect("open_stmnt", "cubit", grp(m("where", "balance>0 AND cusnum='{$id}'"), m("order", "date")));
        $openstmnt->run();
        $open_out = $out;
        $i = 0;
        $ox = "";
        while ($od = $openstmnt->fetch_array()) {
            if ($open_out == 0) {
                continue;
            }
            $oid = $od['id'];
            if ($open_out >= $od['balance']) {
                $open_amount[$oid] = $od['balance'];
                $open_out = sprint($open_out - $od['balance']);
                $ox .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$oid}]' value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t</tr>";
                $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                $Ri = db_exec($Sl) or errDie("Unable to update statement.");
            } elseif ($open_out < $od['balance']) {
                $open_amount[$oid] = $open_out;
                $open_out = 0;
                $ox .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$oid}]' value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$oid}]' value='{$open_amount[$oid]}'>" . CUR . " {$open_amount[$oid]}</td>\n\t\t\t\t\t</tr>";
                $Sl = "UPDATE cubit.open_stmnt SET balance=balance-'{$open_amount[$oid]}' WHERE id='{$oid}'";
                $Ri = db_exec($Sl) or errDie("Unable to update statement.");
            }
            $i++;
        }
        if (open()) {
            $bout = $out;
            $out = $open_out;
            if ($out > 0) {
                $sql = "\n\t\t\t\t\tINSERT INTO cubit.open_stmnt (\n\t\t\t\t\t\tcusnum, invid, amount, balance, date, type, st, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$cus['cusnum']}', '0', '-{$out}', '-{$out}', '{$accdate}', 'Payment Received', 'n', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $stmntRslt = db_exec($sql) or errDie("Unable to Insert statement record in Cubit.", SELF);
            }
            $out = $bout;
        }
        if ($out > 0) {
            recordCT($out, $cus['cusnum'], $accdate, 0);
            $cols = grp(m("cusnum", $cus["cusnum"]), m("invid", 0), m("amount", -$out), m("date", $accdate), m("type", "Payment Received"), m("div", USER_DIV), m("allocation_date", $accdate));
            $dbobj = new dbUpdate("stmnt", "cubit", $cols);
            $dbobj->run(DB_INSERT);
            $dbobj->free();
            custledger($cus['cusnum'], $link['accnum'], $accdate, "PAYMENT", "Payment received.", $out, "c");
        }
    }
    /* start moving invoices */
    // move invoices that are fully paid
    $sql = "SELECT * FROM cubit.invoices WHERE balance=0 AND printed = 'y' AND done = 'y' AND div = '" . USER_DIV . "'";
    $invbRslt = db_exec($sql) or errDie("Unable to update Invoice information in Cubit.", SELF);
    while ($x = pg_fetch_array($invbRslt)) {
        if (($prd = $x['prd']) == "0") {
            $prd = PRD_DB;
        }
        // move invoice
        $cols = grp(m("invid", $x["invid"]), m("invnum", $x["invnum"]), m("deptid", $x["deptid"]), m("cusnum", $x["cusnum"]), m("deptname", $x["deptname"]), m("cusacc", $x["cusacc"]), m("cusname", $x["cusname"]), m("surname", $x["surname"]), m("cusaddr", $x["cusaddr"]), m("cusvatno", $x["cusvatno"]), m("cordno", $x["cordno"]), m("ordno", $x["ordno"]), m("chrgvat", $x["chrgvat"]), m("terms", $x["terms"]), m("traddisc", $x["traddisc"]), m("salespn", $x["salespn"]), m("odate", $x["odate"]), m("delchrg", $x["delchrg"]), m("subtot", $x["subtot"]), m("vat", $x["vat"]), m("total", $x["total"]), m("age", $x["age"]), m("comm", $x["comm"]), m("discount", $x["discount"]), m("delivery", $x["delivery"]), m("docref", $x["docref"]), m("prd", $x["prd"]), m("delvat", $x["delvat"]), m("balance", 0), m("printed", "y"), m("done", "y"), m("username", USER_NAME), m("div", USER_DIV));
        $dbobj = new dbUpdate("invoices", $prd, $cols);
        $dbobj->run(DB_INSERT);
        $dbobj->free();
        // record movement
        $cols = grp(m("invtype", "inv"), m("invnum", $x["invnum"]), m("prd", $x["prd"]), m("docref", $x["docref"]), m("div", USER_DIV));
        $dbobj->setTable("movinv", "cubit");
        $dbobj->setOpt($cols);
        $dbobj->run();
        $dbobj->free();
        // move invoice items
        $inv_items = new dbSelect("inv_items", "cubit", grp(m("where", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)))));
        $inv_items->run();
        while ($xi = $inv_items->fetch_array()) {
            $xi['vatcode'] += 0;
            $xi['account'] += 0;
            $xi['del'] += 0;
            $cols = grp(m("invid", $x["invid"]), m("whid", $xi["whid"]), m("stkid", $xi["stkid"]), m("qty", $xi["qty"]), m("unitcost", $xi["unitcost"]), m("amt", $xi["amt"]), m("disc", $xi["disc"]), m("discp", $xi["discp"]), m("vatcode", $xi["vatcode"]), m("account", $xi["account"]), m("description", $xi["description"]), m("del", $xi["del"]), m("noted", $xi["noted"]), m("serno", $xi["serno"]), m("div", USER_DIV));
            $dbobj->setTable("inv_items", $prd);
            $dbobj->setOpt($cols);
            $dbobj->run();
            $dbobj->free();
        }
        /* remove invoice from cubit schema */
        $dbobj = new dbDelete("invoices", "cubit", wgrp(m("invid", $x["invid"]), m("div", USER_DIV)));
        $dbobj->run();
        $dbobj->setTable("inv_items", "cubit");
        $dbobj->run();
    }
}
function alloc($_POST)
{
    extract($_POST);
    if (isset($back)) {
        if (isset($e)) {
            header("Location: cashbook-entry.php");
            exit;
        }
        return sel_cus($_POST);
    }
    $passon = "";
    require_lib("validate");
    $v = new validate();
    $v->isOk($all, "num", 1, 1, "Invalid allocation.");
    for ($i = 0; $i < $rec_amount; $i++) {
        if (!isset($descript[$i]) or !isset($reference[$i]) or !isset($setamt[$i]) or empty($descript[$i]) or empty($reference[$i]) or empty($setamt[$i])) {
            continue;
        }
        $v->isOk($bankid[$i], "num", 1, 30, "Select Bank Account.");
        $v->isOk($date_day[$i], "num", 1, 2, "Invalid Date day.");
        $v->isOk($date_month[$i], "num", 1, 2, "Invalid Date month.");
        $v->isOk($date_year[$i], "num", 1, 4, "Invalid Date Year.");
        $v->isOk($descript[$i], "string", 0, 255, "Invalid Description.");
        $v->isOk($reference[$i], "string", 0, 50, "Invalid Reference Name/Number.");
        $v->isOk($cheqnum[$i], "num", 0, 30, "Invalid Cheque number.");
        $v->isOk($amt[$i], "float", 1, 40, "Invalid amount.");
        $v->isOk($setamt[$i], "float", 1, 40, "Invalid Settlement Amount.");
        $v->isOk($setvat[$i], "string", 1, 10, "Invalid Settlement VAT Option.");
        $v->isOk($setvatcode[$i], "string", 1, 40, "Invalid Settlement VAT code");
        $v->isOk($cusid[$i], "num", 1, 10, "Invalid customer number.");
        if (strlen($date_year[$i]) != 4) {
            $v->isOk($bankname, "num", 1, 1, "Invalid Date year.");
        }
        if ($amt < 0.01) {
            $v->addError($amt[$i], "Amount too small.");
        }
        $date[$i] = $date_day[$i] . "-" . $date_month[$i] . "-" . $date_year[$i];
        if (!checkdate($date_month[$i], $date_day[$i], $date_year[$i])) {
            $v->isOk($date[$i], "num", 1, 1, "Invalid date.");
        }
        // bank account name
        if (($bank = qryBankAcct($bankid[$i], "accname, bankname")) === false) {
            $bank[$i]['accname'] = "Cash";
            $bank[$i]['bankname'] = "";
        }
        // customer name
        $cus[$i] = qryCustomer($cusid[$i], "cusnum, cusname, surname");
    }
    if ($v->isError()) {
        $confirm = $v->genErrors();
        return $confirm . method($_POST);
    }
    //	<input type='hidden' name='bankid' value='$bankid'>
    $cust_arr = array();
    $confirm = "\n\t\t<h3>New Bank Receipt</h3>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t<input type='hidden' name='accnum' value=''>\n\t\t\t<input type='hidden' name='rec_amount' value='{$rec_amount}'>\n\t\t\t<input type='hidden' name='all' value='{$all}'>\n\t\t<table " . TMPL_tblDflts . ">";
    for ($t = 0; $t < $rec_amount; $t++) {
        if (!isset($descript[$t]) or !isset($reference[$t]) or !isset($setamt[$t]) or empty($descript[$t]) or empty($reference[$t]) or empty($setamt[$t])) {
            continue;
        }
        $cus0 = $cus[$t]['cusnum'];
        $cus1 = $cus[$t]['cusname'];
        $cus2 = $cus[$t]['surname'];
        // we dont do this ...
        //		$amt[$t] = $amt[$t] + $setamt[$t];
        $amt[$t] = sprint($amt[$t]);
        $setamt[$t] = sprint($setamt[$t]);
        if ($setvat[$t] == "inc") {
            $showsetvat = "VAT Inclusive";
        } else {
            $showsetvat = "No VAT";
        }
        $confirm .= "\n\t\t\t<tr>\n\t\t\t\t<th>Field</th>\n\t\t\t\t<th>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Account</td>\n\t\t\t\t<td>{$bank['accname']} - {$bank['bankname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Date</td>\n\t\t\t\t<td valign='center'>{$date[$t]}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Received from</td>\n\t\t\t\t<td valign='center'>{$cus1} {$cus2}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Description</td>\n\t\t\t\t<td valign='center'>" . nl2br($descript[$t]) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Reference</td>\n\t\t\t\t<td valign='center'>{$reference[$t]}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Cheque Number</td>\n\t\t\t\t<td valign='center'>{$cheqnum[$t]}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Amount</td>\n\t\t\t\t<td valign='center'>" . CUR . " {$amt[$t]}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Settlement Discount</td>\n\t\t\t\t<td valign='center'>" . CUR . " {$setamt[$t]} {$showsetvat}</td>\n\t\t\t</tr>";
        /* OPTION 1 : AUTO ALLOCATE (allocate) */
        if ($all == 0) {
            $out[$t] = $amt[$t];
            $invs_arr = array();
            // Connect to database
            db_connect();
            #####################[ GET OUTSTANDING INVOICES ]######################
            $sql = "SELECT invnum, invid, balance, terms, odate FROM invoices WHERE cusnum = '{$cusid[$t]}' AND printed = 'y' AND balance>0 AND div = '" . USER_DIV . "' ORDER BY odate ASC";
            $prnInvRslt = db_exec($sql);
            while (($inv = pg_fetch_array($prnInvRslt)) && $out > 0) {
                $invs_arr[] = array("s", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
            }
            #####################[ GET OUTSTANDING NON STOCK INVOICES ]######################
            $sql = "SELECT invnum, invid, balance, odate FROM nons_invoices WHERE cusid='{$cusid[$t]}' AND done='y' AND balance>0 AND div='" . USER_DIV . "' ORDER BY odate ASC";
            $prnInvRslt = db_exec($sql);
            while (($inv = pg_fetch_array($prnInvRslt)) && $out > 0) {
                $invs_arr[] = array("n", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
            }
            #####################[ GET OUTSTANDING POS INVOICES ]######################
            $sqls = array();
            for ($i = 1; $i <= 12; ++$i) {
                $sqls[] = "\n\t\t\t\t\tSELECT invnum, invid, balance, odate \n\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\tWHERE cusnum='{$cusid[$t]}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "'";
            }
            $sql = implode(" UNION ", $sqls);
            $prnInvRslt = db_exec($sql);
            while ($inv = pg_fetch_array($prnInvRslt)) {
                $invs_arr[] = array("p", $inv['odate'], "{$inv['invid']}", "{$inv['balance']}");
            }
            if (isset($invs_arr) and is_array($invs_arr)) {
                $confirm .= "\n\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Type</th>\n\t\t\t\t\t\t<th>Invoice</th>\n\t\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t\t<th></th>\n\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t<th>Amount</th>\n\t\t\t\t\t</tr>";
            }
            #compile results into an array we can sort by date
            $search_arr = array();
            foreach ($invs_arr as $key => $array) {
                $search_arr[$key] = $array[1];
            }
            #sort array by date
            asort($search_arr);
            #add sorted invoices to payment listing
            foreach ($search_arr as $key => $date_arr) {
                $arr = $invs_arr[$key];
                if ($arr[0] == "s") {
                    $get_sql = "SELECT invnum, invid, balance, terms, odate FROM invoices WHERE cusnum = '{$cusid[$t]}' AND printed = 'y' AND balance>0 AND div = '" . USER_DIV . "' AND invid = '{$arr['2']}'  LIMIT 1";
                    $run_sql = db_exec($get_sql) or errDie("Unable to get stock invoice information.");
                    if (pg_numrows($run_sql) > 0) {
                        $inv = pg_fetch_array($run_sql);
                        $invid = $inv['invid'];
                        if (in_array($invid, $cust_arr[$cus0])) {
                            continue;
                        } else {
                            $val = allocamt($out[$t], $inv["balance"]);
                            if ($val > 0) {
                                $cust_arr[$cus0][] = $invid;
                            } else {
                                continue;
                            }
                        }
                        $confirm .= "\n\t\t\t\t\t\t\t<input type='hidden' name='paidamt[{$t}][{$invid}]' size='10' value='{$val}'>\n\t\t\t\t\t\t\t<input type='hidden' size='20' name='invids[{$t}][{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t\t<td>Stock Invoice</td>\n\t\t\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t\t</tr>";
                    }
                } elseif ($arr[0] == "n") {
                    $get_sql = "SELECT invnum, invid, balance, odate FROM nons_invoices WHERE cusid='{$cusid[$t]}' AND done='y' AND balance>0 AND div='" . USER_DIV . "' AND invid = '{$arr['2']}' LIMIT 1";
                    $run_sql = db_exec($get_sql) or errDie("Unable to get non stock information.");
                    if (pg_numrows($run_sql) > 0) {
                        $inv = pg_fetch_array($run_sql);
                        $invid = $inv['invid'];
                        if (in_array($invid, $cust_arr[$cus0])) {
                            continue;
                        } else {
                            $val = allocamt($out[$t], $inv["balance"]);
                            if ($val > 0) {
                                $cust_arr[$cus0][] = $invid;
                            } else {
                                continue;
                            }
                        }
                        $confirm .= "\n\t\t\t\t\t\t\t<input type='hidden' name='paidamt[{$t}][{$invid}]' value='{$val}'>\n\t\t\t\t\t\t\t<input type='hidden' name='itype[{$t}][{$invid}]' value='Yes'>\n\t\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t\t<td>Non Stock Invoice</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='invids[{$t}][{$invid}]' value='{$inv['invid']}'>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t\t</tr>";
                    }
                } else {
                    $sqls = array();
                    for ($i = 1; $i <= 12; ++$i) {
                        $sqls[] = "\n\t\t\t\t\t\t\tSELECT invnum, invid, balance, odate \n\t\t\t\t\t\t\tFROM \"{$i}\".pinvoices \n\t\t\t\t\t\t\tWHERE cusnum='{$cusid[$t]}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "' AND invid = '{$arr['2']}'";
                    }
                    $get_sql = implode(" UNION ", $sqls);
                    $run_sql = db_exec($get_sql) or errDie("Unable to get pos invoice information.");
                    if (pg_numrows($run_sql) > 0) {
                        $inv = pg_fetch_array($run_sql);
                        $invid = $inv['invid'];
                        if (in_array($invid, $cust_arr[$cus0])) {
                            continue;
                        } else {
                            $val = allocamt($out[$t], $inv["balance"]);
                            if ($val > 0) {
                                $cust_arr[$cus0][] = $invid;
                            } else {
                                continue;
                            }
                        }
                        $confirm .= "\n\t\t\t\t\t\t\t<input type='hidden' size='20' name='invids[{$t}][{$invid}]' value='{$inv['invid']}'>\n\t\t\t\t\t\t\t<input type='hidden' name='paidamt[{$t}][{$invid}]' size='10' value='{$val}'>\n\t\t\t\t\t\t\t<input type='hidden' name='ptype[{$t}][{$invid}]' value='YnYn'>\n\t\t\t\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t\t\t\t<td>POS Invoice</td>\n\t\t\t\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t\t\t\t</tr>";
                    }
                    $out[$t] = sprint($out[$t]);
                }
            }
        }
        if ($out[$t] > 0) {
            $out[$t] = sprint($out[$t]);
            $confirm .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='4'><b>A general transaction will credit the client's account with " . CUR . " {$out[$t]} </b></td>\n\t\t\t\t</tr>";
        }
        $confirm .= TBL_BR . TBL_BR . TBL_BR;
    }
    for ($i = 0; $i < $rec_amount; $i++) {
        $passon .= "\n\t\t\t<input type='hidden' name='bankid[{$i}]' value='{$bankid[$i]}'>\n\t\t\t<input type='hidden' name='date[{$i}]' value='{$date[$i]}'>\n\t\t\t<input type='hidden' name='cusid[{$i}]' value='{$cusid[$i]}'>\n\t\t\t<input type='hidden' name='date_day[{$i}]' value='{$date_day[$i]}'>\n\t\t\t<input type='hidden' name='date_month[{$i}]' value='{$date_month[$i]}'>\n\t\t\t<input type='hidden' name='date_year[{$i}]' value='{$date_year[$i]}'>\n\t\t\t<input type='hidden' name='descript[{$i}]' value='{$descript[$i]}'>\n\t\t\t<input type='hidden' name='reference[{$i}]' value='{$reference[$i]}'>\n\t\t\t<input type='hidden' name='cheqnum[{$i}]' value='{$cheqnum[$i]}'>\n\t\t\t<input type='hidden' name='amt[{$i}]' value='{$amt[$i]}'>\n\t\t\t<input type='hidden' name='setamt[{$i}]' value='{$setamt[$i]}'>\n\t\t\t<input type='hidden' name='setvat[{$i}]' value='{$setvat[$i]}'>\n\t\t\t<input type='hidden' name='setvatcode[{$i}]' value='{$setvatcode[$i]}'>\n\t\t\t<input type='hidden' name='out[{$i}]' value='{$out[$i]}'>";
    }
    $confirm .= "\n\t\t\t{$passon}\n\t\t\t<tr>\n\t\t\t\t<td><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t\t<td align='right'><input type='submit' value='Confirm &raquo'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>" . mkQuickLinks(ql("trans-new.php", "Journal Transactions"), ql("../customers-view.php", "View Customers"));
    return $confirm;
}
function cusalloc($all, $k, $cusid, $totamt, &$cust_arr)
{
    $custinfo = qryCustomer($cusid);
    $cus0 = $custinfo['cusnum'];
    $amt = $totamt;
    $OUT = "\n\t\t<input type='hidden' name='cusids[{$k}]' value='{$cusid}' />\n\t\t<input type='hidden' name='amts[{$k}]' value='{$totamt}' />";
    $OUT .= "<table " . TMPL_tblDflts . ">";
    if ($all != 0) {
        $OUT .= "\n\t\t\t<tr>\n\t\t\t\t<th colspan='10'>Amount to Allocate: " . CUR . " {$amt}</th>\n\t\t\t</tr>";
    }
    /* OPTION 1 : AUTO ALLOCATE (allocate) */
    if ($all == 0) {
        /* stock invoices */
        $sql = "\n\t\t\tSELECT invnum,invid,balance,terms,odate FROM cubit.invoices \n\t\t\tWHERE cusnum = '{$cusid}' AND printed = 'y' AND balance > 0 AND div = '" . USER_DIV . "' \n\t\t\tORDER BY odate ASC";
        $rslt = db_exec($sql);
        if (pg_num_rows($rslt) > 0) {
            $OUT .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><h3>Outstanding Invoices</h3></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Invoice</th>\n\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t<th>Terms</th>\n\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t<th>Amount</th>\n\t\t\t\t</tr>";
        }
        $i = 0;
        while (($inv = pg_fetch_array($rslt)) && $amt > 0) {
            $invid = $inv['invid'];
            if (in_array($invid, $cust_arr[$cus0])) {
                continue;
            } else {
                $val = allocamt($amt, $inv["balance"]);
                if ($val > 0) {
                    $cust_arr[$cus0][] = $invid;
                } else {
                    continue;
                }
            }
            //			$val = allocamt($amt, $inv["balance"]);
            $OUT .= "\n\t\t\t\t<input type='hidden' name='paidamt[{$k}][{$invid}]' value='{$val}' />\n\t\t\t\t<input type='hidden' name='invids[{$k}][{$invid}]' value='{$inv['invid']}' />\n\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t<td>{$inv['terms']} days</td>\n\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t</tr>";
        }
        /* non stock invoices */
        $sql = "\n\t\t\tSELECT invnum, invid, balance, sdate AS odate \n\t\t\tFROM cubit.nons_invoices \n\t\t\tWHERE cusid='{$cusid}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "' \n\t\t\tORDER BY odate ASC";
        $rslt = db_exec($sql);
        if (pg_num_rows($rslt) > 0) {
            $OUT .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><h3>Outstanding Non-Stock Invoices</h3></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Invoice</th>\n\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t<th></th>\n\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t<th>Amount</th>\n\t\t\t\t</tr>";
        }
        $i = 0;
        while (($inv = pg_fetch_array($rslt)) && $amt > 0) {
            $invid = $inv['invid'];
            if (in_array($invid, $cust_arr[$cus0])) {
                continue;
            } else {
                $val = allocamt($amt, $inv["balance"]);
                if ($val > 0) {
                    $cust_arr[$cus0][] = $invid;
                } else {
                    continue;
                }
            }
            //			$val = allocamt($amt, $inv["balance"]);
            $OUT .= "\n\t\t\t\t<input type='hidden' name='paidamt[{$k}][{$invid}]' value='{$val}' />\n\t\t\t\t<input type='hidden' name='itype[{$k}][{$invid}]' value='Yes' />\n\t\t\t\t<input type='hidden' name='invids[{$k}][{$invid}]' value='{$inv['invid']}' />\n\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t</tr>";
        }
        /* pos invoices */
        $sqls = array();
        for ($i = 1; $i <= 12; ++$i) {
            $sqls[] = "\n\t\t\t\tSELECT invnum,invid,balance,odate FROM \"{$i}\".pinvoices \n\t\t\t\tWHERE cusnum='{$cusid}' AND done='y' AND balance > 0 AND div='" . USER_DIV . "'";
        }
        $sql = implode(" UNION ", $sqls);
        $rslt = db_exec($sql);
        if (pg_num_rows($rslt) > 0) {
            $OUT .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'><h3>Outstanding POS Invoices</h3></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Invoice</th>\n\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t<th></th>\n\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t<th>Amount</th>\n\t\t\t\t</tr>";
        }
        $i = 0;
        while ($inv = pg_fetch_array($rslt)) {
            $invid = $inv['invid'];
            if (in_array($invid, $cust_arr[$cus0])) {
                continue;
            } else {
                $val = allocamt($amt, $inv["balance"]);
                if ($val > 0) {
                    $cust_arr[$cus0][] = $invid;
                } else {
                    continue;
                }
            }
            //			$val = allocamt($amt, $inv["balance"]);
            $OUT .= "\n\t\t\t\t<input type='hidden' name='invids[{$k}][{$invid}]' value='{$inv['invid']}' />\n\t\t\t\t<input type='hidden' name='paidamt[{$k}][{$invid}]' value='{$val}' />\n\t\t\t\t<input type='hidden' name='ptype[{$k}][{$invid}]' value='YnYn' />\n\t\t\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t\t\t<td>{$inv['invnum']}</td>\n\t\t\t\t\t<td>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>{$inv['odate']}</td>\n\t\t\t\t\t<td>" . CUR . " {$val}</td>\n\t\t\t\t</tr>";
        }
        /* open items */
        if (sprint($amt) > 0) {
            $ox = "";
            $sql = "\n\t\t\t\tSELECT * FROM cubit.open_stmnt \n\t\t\t\tWHERE balance>0 AND cusnum='{$cusid}' AND type!='Invoice' AND type!='Non-Stock Invoice' \n\t\t\t\t\tAND type!='Interest on Outstanding balance' \n\t\t\t\tORDER BY date";
            $rslt = db_exec($sql) or errDie("Unable to get open items.");
            $open_out = $amt;
            $i = 0;
            while ($od = pg_fetch_array($rslt)) {
                if ($open_out == 0) {
                    continue;
                }
                $bgColor = bgcolor($i);
                $oid = $od['id'];
                if ($open_out >= $od['balance']) {
                    $open_out = sprint($open_out - $od['balance']);
                    $ox .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><input type='hidden' size='20' name='open[{$k}][{$oid}]' value='{$oid}'>{$od['type']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$k}][{$oid}]' value='{$od['balance']}'>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t</tr>";
                } elseif ($open_out < $od['balance']) {
                    $tmp = $open_out;
                    $open_out = 0;
                    $ox .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><input type='hidden' name='open[{$k}][{$oid}]' value='{$od['id']}'>{$od['type']}</td>\n\t\t\t\t\t\t\t<td>" . CUR . " {$od['balance']}</td>\n\t\t\t\t\t\t\t<td>{$od['date']}</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='open_amount[{$k}][{$oid}]' value='{$tmp}'>" . CUR . " {$tmp}</td>\n\t\t\t\t\t\t</tr>";
                }
            }
            if (open()) {
                $OUT .= "\n\t\t\t\t\t<input type='hidden' name='bout[{$k}]' value='{$amt}'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='2'><h3>Outstanding Transactions</h3></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t<th>Outstanding Amount</th>\n\t\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t\t<th>Amount</th>\n\t\t\t\t\t</tr>";
                $OUT .= $ox;
                $bout = $amt;
                $amt = $open_out;
                if (sprint($amt) > 0) {
                    $OUT .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan='4'><b>A general transaction will credit the client's\n\t\t\t\t\t\t\t\taccount with " . CUR . " " . sprint($amt) . "</b>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>";
                }
            } else {
                $amt = sprint($amt);
                $OUT .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='4'><b>A general transaction will credit the client's\n\t\t\t\t\t\t\taccount with " . CUR . " {$amt}</b>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>";
            }
        }
    }
    vsprint($amt);
    $OUT .= "<input type='hidden' name='out[{$k}]' value='{$amt}'>";
    $OUT .= "</table>";
    return array($amt, $OUT);
}