function confirm($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($run)) {
        foreach ($run as $key => $value) {
            $v->isOk($run[$key], "num", 1, 50, "Invalid Transaction number.");
        }
    } else {
        return "<li> - No Recurring Transactions Seleted. Please select at least one entry.</li>";
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    $refnum = getrefnum();
    /*refnum*/
    $trans = "";
    # Transactions
    foreach ($run as $key => $value) {
        # connect to core
        core_Connect();
        # Get all the details
        $sql = "SELECT * FROM rectrans WHERE recid = '{$value}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to access database.");
        $tran = pg_fetch_array($rslt);
        # get account to be debited
        $dtaccRs = get("core", "accname,topacc,accnum", "accounts", "accid", $tran['debit']);
        if (pg_numrows($dtaccRs) < 1) {
            return "<li> Accounts to be debited does not exist.</li>";
        }
        $dtacc = pg_fetch_array($dtaccRs);
        # get account to be debited
        $ctaccRs = get("core", "accname,topacc,accnum", "accounts", "accid", $tran['credit']);
        if (pg_numrows($ctaccRs) < 1) {
            return "<li> Accounts to be debited does not exist.</li>";
        }
        $ctacc = pg_fetch_array($ctaccRs);
        //script ignored the refnum given to it ???
        //".($refnum + $key)."
        $trans .= "\n\t\t\t<tr bgcolor=" . bgcolorg() . ">\n\t\t\t\t<td nowrap>" . mkDateSelecta("date", $key) . "<input type='hidden' size='20' name='run[]' value='{$value}'></td>\n\t\t\t\t<td><input type='text' size='7' name='refnum[]' value='{$tran['refnum']}'></td>\n\t\t\t\t<td valign='center'><input type='hidden' name='dtaccid[]' value='{$tran['debit']}'>{$dtacc['topacc']}/{$dtacc['accnum']} - {$dtacc['accname']}</td>\n\t\t\t\t<td valign='center'><input type='hidden' name='ctaccid[]' value='{$tran['credit']}'>{$ctacc['topacc']}/{$ctacc['accnum']} - {$ctacc['accname']}</td>\n\t\t\t\t<input type='hidden' name='vatcodes[]' value='{$tran['vatcode']}'>\n\t\t\t\t<td nowrap>" . CUR . " <input type='text' name='amount[]' size='8' value='{$tran['amount']}'></td>\n\t\t\t\t<td><input type='hidden' name='descript[]' value ='{$tran['details']}'>{$tran['details']}</td>";
        if ($tran['chrgvat'] == "yes") {
            $vataccRs = get("core", "*", "accounts", "accid", $tran['vataccid']);
            $vatacc = pg_fetch_array($vataccRs);
            $vataccRs = get("core", "*", "accounts", "accid", $tran['vatdedacc']);
            $vatdedacc = pg_fetch_array($vataccRs);
            $trans .= "\n\t\t\t\t<input type='hidden' name='chrgvat[{$value}]' value ='yes'>\n\t\t\t\t<td align='center'><input type='hidden' name='vatinc[{$value}]' value ='{$tran['vatinc']}'>{$tran['vatinc']}</td>\n\t\t\t\t<td align='center'><input type='hidden' name='vataccid[{$value}]' value ='{$tran['vataccid']}'>{$vatacc['accname']}</td>\n\t\t\t\t<td align='center'><input type='hidden' name='vatdedacc[{$value}]' value ='{$tran['vatdedacc']}'>{$vatdedacc['accname']}</td>";
        } else {
            $trans .= "<td></td><td></td><td></td>";
        }
        $trans .= "</tr>";
    }
    $confirm = "\n\t\t<center>\n\t\t<h3>Process Recurring Journal Transaction(s)</h3>\n\t\t<h4>Confirm entry</h4>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='cconfirm'>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Ref num</th>\n\t\t\t\t<th>Debit</th>\n\t\t\t\t<th>Credit</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t\t<th>Description</th>\n\t\t\t\t<th>VAT Inclusive</th>\n\t\t\t\t<th>VAT Account</th>\n\t\t\t\t<th>VAT Deductable Account</th>\n\t\t\t</tr>\n\t\t\t{$trans}\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input type='button' value='&laquo Back' onClick='javascript:history.back()'></td>\n\t\t\t\t<td align='right' colspan='2'><input type='submit' value='Confirm &raquo'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>\n\t\t<p>\n\t\t<table border=0 cellpadding='2' cellspacing='1' 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='datacell'>\n\t\t\t\t<td align='center'><a href='rectrans-new.php'>Add Recurring Transaction</td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $confirm;
}
function method($_POST, $ex = "")
{
    extract($_POST);
    // customers Drop down selections
    db_connect();
    $cust = "<select name='cusid'>";
    $sql = "SELECT cusnum,cusname,surname FROM customers WHERE div = '" . USER_DIV . "' ORDER BY surname,cusname";
    $cusRslt = db_exec($sql) or errDie("Unable to get customers information.");
    $numrows = pg_numrows($cusRslt);
    if (empty($numrows)) {
        return "<li class='err'> There are no Debtors in Cubit.</li>" . mkQuickLinks(ql("trans-new.php", "Journal Transactions"), ql("../customers-view.php", "View Customers"));
    }
    if (!isset($rec_amount)) {
        $rec_amount = 1;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($rec_amount, "num", 1, 10, "Invalid amount of receipt.");
    # 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;
    }
    $jump_bot = "";
    if (isset($another)) {
        $jump_bot = "\n\t\t\t<script>\n\t\t\t\twindow.location.hash='bottom';\n\t\t\t</script>";
        $rec_amount++;
    }
    if (isset($_GET["e"])) {
        $ex = "<input type='hidden' name='e' value='y'>";
    } else {
        $ex = "";
    }
    $listing = "";
    for ($i = 0; $i < $rec_amount; $i++) {
        #here we will make the entries ...
        ##################[ check the vars ]#####################
        if (!isset($cusid[$i])) {
            $bankid[$i] = "0";
            $descript[$i] = "";
            $cheqnum[$i] = "";
            $amt[$i] = "";
            $setamt[$i] = "";
            $setvat[$i] = "";
            $setvatcode = "";
            $reference[$i] = "";
            $setvat[$i] = "";
            $setvatcode[$i] = "";
        }
        if (!isset($date_day[$i])) {
            $trans_date_setting = getCSetting("USE_TRANSACTION_DATE");
            if (isset($trans_date_setting) and $trans_date_setting == "yes") {
                $trans_date_value = getCSetting("TRANSACTION_DATE");
                $date_arr = explode("-", $trans_date_value);
                $date_year[$i] = $date_arr[0];
                $date_month[$i] = $date_arr[1];
                $date_day[$i] = $date_arr[2];
            } else {
                if (isset($_SESSION["global_day"]) and strlen($_SESSION["global_day"]) > 0) {
                    $date_day[$i] = $_SESSION["global_day"];
                } else {
                    $date_day[$i] = date("d");
                }
                if (isset($_SESSION["global_month"]) and strlen($_SESSION["global_month"]) > 0) {
                    $date_month[$i] = $_SESSION["global_month"];
                } else {
                    $date_month[$i] = date("m");
                }
                if (isset($_SESSION["global_year"]) and strlen($_SESSION["global_year"]) > 0) {
                    $date_year[$i] = $_SESSION["global_year"];
                } else {
                    $date_year[$i] = date("Y");
                }
            }
        }
        #########################################################
        ##################[ get customer information ]###########
        db_connect();
        $customerdrop = "<select name='cusid[{$i}]'>";
        $sql = "SELECT cusnum,cusname,surname FROM customers WHERE div = '" . USER_DIV . "' ORDER BY surname,cusname";
        $cusRslt = db_exec($sql) or errDie("Unable to get customer information");
        if (pg_numrows($cusRslt) < 1) {
            return "\n\t\t\t\t<li> There are no Customers in Cubit.</li>\n\t\t\t\t<p>\n\t\t\t\t" . mkQuickLinks(ql("trans-new.php", "Journal Transactions"), ql("../customers-view.php", "View Customers"));
        }
        if (!isset($cusid[$i])) {
            $cusid[$i] = 0;
        }
        while ($cus = pg_fetch_array($cusRslt)) {
            if ($cus['cusnum'] == $cusid[$i]) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $customerdrop .= "<option {$sel} value='{$cus['cusnum']}'>{$cus['cusname']} {$cus['surname']}</option>";
        }
        $customerdrop .= "</select>";
        #########################################################
        ##################[ get Bank accounts ]##################
        $bankaccs = "<select name='bankid[{$i}]'>";
        db_connect();
        $sql = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '" . USER_DIV . "' ORDER BY accname,bankname";
        $banks = db_exec($sql) or errDie("Unable to get bank accounts information.");
        $numrows = pg_numrows($banks);
        if (empty($numrows)) {
            return "\n\t\t\t\t<li class='err'> There are no accounts held at the selected Bank.\n\t\t\t\t<p>\n\t\t\t\t<input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
        }
        while ($acc = pg_fetch_array($banks)) {
            $sel = fsel($bankid[$i] == $acc["bankid"]);
            $bankaccs .= "<option {$sel} value='{$acc['bankid']}'>{$acc['accname']} - {$acc['bankname']} ({$acc['acctype']})</option>";
        }
        if (isset($_GET['cash'])) {
            $sel = fsel($bankid[$i] == $acc["bankid"]);
            $bankaccs .= "<option {$sel} value='0'>Receive Cash</option>";
        }
        $bankaccs .= "</select>";
        ##########################################################
        $setamt[$i] = sprint($setamt[$i]);
        $get_vatcodes = "SELECT * FROM vatcodes ORDER BY code";
        $run_vatcodes = db_exec($get_vatcodes) or errDie("Unable to get vat code information.");
        if (pg_numrows($run_vatcodes) < 1) {
            $setvatcode_drop = "<input type='hidden' name='setvatcode[{$i}]' value=''>";
        } else {
            $setvatcode_drop = "<select name='setvatcode[{$i}]'>";
            while ($vcarr = pg_fetch_array($run_vatcodes)) {
                if ($setvatcode[$i] == $vcarr['id']) {
                    $setvatcode_drop .= "<option value='{$vcarr['id']}' selected>{$vcarr['code']} {$vcarr['description']}</option>";
                } else {
                    $setvatcode_drop .= "<option value='{$vcarr['id']}'>{$vcarr['code']} {$vcarr['description']}</option>";
                }
            }
            $setvatcode_drop .= "</select>";
        }
        $listing .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$customerdrop}</td>\n\t\t\t\t<td>{$bankaccs}</td>\n\t\t\t\t<td>" . mkDateSelecta("date", $i, $date_year[$i], $date_month[$i], $date_day[$i]) . "</td>\n\t\t\t\t<td><textarea cols='25' rows='2' name='descript[{$i}]'>{$descript[$i]}</textarea></td>\n\t\t\t\t<td><input type='text' name='reference[{$i}]' value='{$reference[$i]}'></td>\n\t\t\t\t<td><input type='text' name='cheqnum[{$i}]' value='{$cheqnum[$i]}'></td>\n\t\t\t\t<td nowrap>" . CUR . " <input type='text' name='amt[{$i}]' size='7' value='{$amt[$i]}'></td>\n\t\t\t\t<td nowrap>" . CUR . " <input type='text' name='setamt[{$i}]' size='7' value='{$setamt[$i]}'></td>\n\t\t\t\t<td nowrap>\n\t\t\t\t\t{$setvatcode_drop} <br>\n\t\t\t\t\t<input type='radio' name='setvat[{$i}]' value='inc' checked='yes'> VAT Inclusive <br>\n\t\t\t\t\t<input type='radio' name='setvat[{$i}]' value='novat'> No VAT\n\t\t\t\t</td>\n\t\t\t</tr>";
    }
    $listing .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='6' align='right'><b>Total:</b></td>\n\t\t\t<td align='right'>" . CUR . " " . sprint(array_sum($amt)) . "</td>\n\t\t\t<td colspan='2'></td>\n\t\t</tr>";
    #set method option
    if (!isset($all)) {
        $all = "0";
    }
    //	$as1 = "";
    //	$as2 = "";
    //	$as3 = "";
    //	if ($all == 0) {
    //		$as1 = "selected";
    //	} else if($all == 1) {
    //		$as2 = "selected";
    //	} else if ($all == 2) {
    //		$as3 = "selected";
    //	}
    //	$alls = "
    //			<select name='all'>
    //				<option value='0' $as1>Auto</option>
    //				<option value='1' $as2>Allocate To Age Analysis</option>
    //				<option value='2' $as3>Allocate To Each invoice</option>
    //			</select>";
    //		<tr>
    //			<th colspan='2'>Receive Method</th>
    //		</tr>
    //		<tr class='".bg_class()."'>
    //			<td>Allocation</td>
    //			<td>$alls</td>
    //		</tr>
    // layout
    $add = "\n\t\t<h3>New Multiple Receipts</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t{$ex}\n\t\t\t<input type='hidden' name='rec_amount' value='{$rec_amount}'>\n\t\t\t<input type='hidden' name='key' value='alloc'>\n\t\t\t<input type='hidden' name='cusid' value='{$cusid}'>\n\t\t\t<input type='hidden' name='all' value='0'>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td colspan='9'><li class='err'>NOTE: This functionality will automatically allocate any amount received to the oldest unpaid/partially paid recorded invoice.</li></td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<th colspan='9'>Receipt Details</th>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th>Customer</th>\n\t\t\t\t<th>Bank Account / Cash</th>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Description</th>\n\t\t\t\t<th>Reference</th>\n\t\t\t\t<th>Cheque Number</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t\t<th>Settlement Amount</th>\n\t\t\t\t<th>Settlement VAT</th>\n\t\t\t</tr>\n\t\t\t{$listing}\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td><input type='submit' name='another' value='Add Another'></td>\n\t\t\t\t<td valign='center' align='right'><input type='submit' value='Allocate >'></td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t</form>\n\t\t</table>\n\t\t<a name='bottom'>\n\t\t{$jump_bot}" . mkQuickLinks(ql("trans-new.php", "Journal Transactions"), ql("../customers-view.php", "View Customers"));
    return $add;
}
function details($_GET)
{
    # get vars
    extract($_GET);
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($invids as $key => $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid recuring invoice number.");
    }
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (!isset($all_day)) {
        $all_day = "";
    }
    if (!isset($all_month)) {
        $all_month = "";
    }
    if (!isset($all_year)) {
        $all_year = "";
    }
    if (!isset($just_month)) {
        $just_month = "";
    }
    /* --- Start Display --- */
    $printInv = "\n\t\t<h3>Confirm Invoice Process</h3>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='process'>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<td class='err'>Please Note : This process might take long depending on the number of invoices. It is best to run it overnight.</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<th>Set All Invoices To This Date</th>\n\t\t\t\t<td width='10'></td>\n\t\t\t\t<th>Change All To This Month</th>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td class='" . bg_class() . "' align='center'>\n\t\t\t\t\t<input type='text' size='2' name='all_day' value='{$all_day}'> \n\t\t\t\t\t<input type='text' size='2' name='all_month' value='{$all_month}'> \n\t\t\t\t\t<input type='text' size='4' name='all_year' value='{$all_year}'> \n\t\t\t\t\t<input type='submit' name='set_date' value='Set All Dates'>\n\t\t\t\t</td>\n\t\t\t\t<td></td>\n\t\t\t\t<td class='" . bg_class() . "' align='center'>\n\t\t\t\t\t<input type='text' size='2' name='just_month' value='{$just_month}'> \n\t\t\t\t\t<input type='submit' name='set_month' value='Change'>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t</table>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Department</th>\n\t\t\t\t<th>Sales Person</th>\n\t\t\t\t<th>Invoice No.</th>\n\t\t\t\t<th>Invoice Date</th>\n\t\t\t\t<th>Customer Name</th>\n\t\t\t\t<th>Order No</th>\n\t\t\t\t<th>Grand Total</th>\n\t\t\t</tr>";
    $i = 0;
    $inv_tot = 0;
    foreach ($invids as $key => $invid) {
        # Get recuring invoice info
        db_connect();
        $sql = "SELECT * FROM rec_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $invRslt = db_exec($sql) or errDie("Unable to get recuring invoice information");
        if (pg_numrows($invRslt) < 1) {
            return "<i class='err'>Not Found</i>";
        }
        $inv = pg_fetch_array($invRslt);
        if (isset($inv['cusnum']) and $inv['cusnum'] != "0") {
            #customer set ... check if he's blocked
            $cust_sql = "SELECT cusnum FROM customers WHERE cusnum = '{$inv['cusnum']}' AND blocked != 'yes'";
            $run_cust = db_exec($cust_sql) or errDie("Unable to get customer information.");
            if (pg_numrows($run_cust) < 1) {
                #blocked? customer found !!
                return "<li class='err'>Invalid Customer/Customer is blocked.</li><br><input type='button' onClick=\"document.location='rec-invoice-view.php';\" value='&laquo Correction'>";
            }
        }
        $inv['total'] = sprint($inv['total']);
        $inv['balance'] = sprint($inv['balance']);
        # Format date
        if (strlen($all_day) > 0 and strlen($all_month) > 0 and strlen($all_year) > 0) {
            $o_day = $all_day;
            $o_month = $all_month;
            $o_year = $all_year;
        } else {
            list($o_year, $o_month, $o_day) = explode("-", $inv['odate']);
        }
        if (strlen($just_month) > 0) {
            $o_month = $just_month;
        }
        $printInv .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><input type='hidden' name='invids[]' value='{$inv['invid']}'>{$inv['deptname']}</td>\n\t\t\t\t<td>{$inv['salespn']}</td>\n\t\t\t\t<td>RI {$inv['invid']}</td>\n\t\t\t\t<td valign='center'>\n\t\t\t\t\t<table cellspacing='0'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>" . mkDateSelecta("o", array("{$i}"), $o_year, $o_month, $o_day) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td>{$inv['cusname']} {$inv['surname']}</td>\n\t\t\t\t<td align='right'>{$inv['ordno']}</td>\n\t\t\t\t<td align='right'>" . CUR . " " . sprint($inv['total']) . "</td>\n\t\t\t</tr>";
        $inv_tot += $inv['total'];
        $i++;
    }
    $printInv .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><b>Totals:</b></td>\n\t\t\t\t<td colspan='5' align='right'>Invoices : {$i}</td>\n\t\t\t\t<td align='right'>" . CUR . " " . sprint($inv_tot) . "</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='6' align='right'><input type='submit' value='Process >>'></td>\n\t\t\t</tr>\n\t\t</form></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='rec-invoice-new.php'>New Recurring Invoice</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='rec-invoice-view.php'>View Recurring Invoices</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $printInv;
}
function details($_POST, $error = "")
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($purid)) {
        $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    } else {
        $v->isOk($deptid, "num", 1, 20, "Invalid department number.");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (!isset($purid)) {
        $purid = create_dummy($deptid);
    }
    # 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 class='err'>Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $deptid = $pur['deptid'];
    # check if purchase has been printed
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : Order no. {$pur['purnum']} has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    if (!isset($ordernum)) {
        $ordernum = '';
    }
    if (!isset($supinv)) {
        $supinv = '';
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<li class='err'>Department not Found.</li>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    $supname = $pur['supname'];
    $supaddr = $pur['supaddr'];
    $supno = $pur['supno'];
    /* --- Start Drop Downs --- */
    # Select warehouse
    db_conn("exten");
    $whs = "<select name='whidss[]' onChange='javascript:document.form.submit();'>";
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
    $whRslt = db_exec($sql);
    if (pg_numrows($whRslt) < 1) {
        return "<li class='err'> There are no Stores found in Cubit.</li>";
    } else {
        $whs .= "<option value='-S' disabled selected>Select Store</option>";
        while ($wh = pg_fetch_array($whRslt)) {
            $whs .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
        }
    }
    $whs .= "</select>";
    # days drop downs
    $days = array("0" => "0", "7" => "7", "14" => "14", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $pur['terms']);
    # format date
    list($p_year, $p_month, $p_day) = explode("-", $pur['pdate']);
    # keep the charge vat option stable
    if ($pur['vatinc'] == "yes") {
        $chy = "checked=yes";
        $chn = "";
        $chv = "";
    } elseif ($pur['vatinc'] == "no") {
        $chy = "";
        $chn = "checked=yes";
        $chv = "";
    } else {
        $chy = "";
        $chn = "";
        $chv = "checked=yes";
    }
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # select all products
    $products = "\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>STORE</th>\n\t\t\t\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t\t\t\t<th>VAT CODE</th>\n\t\t\t\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t\t\t\t<th>QTY</th>\n\t\t\t\t\t\t\t<th>PRICE PER UNIT</th>\n\t\t\t\t\t\t\t<th>DELIVERY DATE</th>\n\t\t\t\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t\t\t\t<th>VAT</th>\n\t\t\t\t\t\t\t<th>Remove</th>\n\t\t\t\t\t\t<tr>";
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # keep track of selected stock amounts
        $amts[$i] = $stkd['amt'];
        $i++;
        # get warehouse name
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # get selected stock in this warehouse
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        list($d_year[$i], $d_month[$i], $d_day[$i]) = explode("-", $stkd['ddate']);
        $stkd['amt'] = sprint($stkd['amt']);
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "Please select the vatcode for all your stock.";
        }
        $vd = pg_fetch_array($Ri);
        if ($pur['vatinc'] == 'no' && $stk['exvat'] != 'yes') {
            $vunitamt = sprint($stkd['unitcost']);
        } else {
            $vunitamt = sprint($stkd['unitcost']);
        }
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
        $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($stkd['vatcode'] == $vd['id']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $Vatcodes .= "</select>";
        $tip = "&nbsp;&nbsp;&nbsp;";
        if (isset($vatc[$key])) {
            $tip = "<font color=red>#</font>";
            $error = "<div class=err> {$tip}&nbsp;&nbsp;=&nbsp;&nbsp; Vat amount is different from amount calculated by cubit. To allow cubit to recalculate the vat amount, please delete the vat amount from the input box.";
        }
        # put in product
        $products .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><input type='hidden' name='whids[]' value='{$stkd['whid']}'>{$wh['whname']}</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t\t\t<td><input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'></td>\n\t\t\t\t\t\t\t<td>" . CUR . " <input type='text' size='8' name='unitcost[]' value='{$vunitamt}'></td>\n\t\t\t\t\t\t\t<td>" . mkDateSelecta("d", $key, $d_year[$i], $d_month[$i], $d_day[$i]) . "</td>\n\t\t\t\t\t\t\t<td align='right'><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t\t\t<td>{$tip} <input type='text' name='svat[]' size='9' value='{$stkd['svat']}'></td>\n\t\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$key}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t\t\t\t</tr>";
        $key++;
    }
    # Look above(remprod keys)
    $keyy = $key;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    }
    $l = $i++;
    # check if stock warehouse was selected
    if (isset($whidss)) {
        foreach ($whidss as $key => $whid) {
            if (isset($stkidss[$key]) && $stkidss[$key] != "-S") {
                # skip if not selected
                if ($whid == "-S") {
                    continue;
                }
                # Get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                # Get selected stock in this warehouse
                db_connect();
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkidss[$key]}' AND div = '" . USER_DIV . "' ORDER BY stkcod ASC";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                # Calculate amount
                $amt[$key] = sprint($qtyss[$key] * 0);
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "<select name=vatcodes[]>\n\t\t\t\t<option value='0'>Select</option>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($stk['vatcode'] == $vd['id']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                # Put in selected warehouse and stock
                $products .= "\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td><input type='hidden' name='whids[]' value='{$whid}'>{$wh['whname']}</td>\n\t\t\t\t\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stk['stkid']}'><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t\t\t\t\t<td><input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'></td>\n\t\t\t\t\t\t\t\t\t<td><input type='hidden' name='novat[{$keyy}]' value='1'>" . CUR . " <input type='text' size='8' name='unitcost[]' value='0'></td>\n\t\t\t\t\t\t\t\t\t<td>" . mkDateSelecta("d", $key, $d_year[$l], $d_month[$l], $d_day[$l]) . "</td>\n\t\t\t\t\t\t\t\t\t<td align='right'><input type='hidden' name='amt[]' value='{$amt[$key]}'> " . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t\t\t\t\t\t</tr>";
                $key++;
            } else {
                if (!isset($diffwhBtn)) {
                    # Skip if not selected
                    if ($whid == "-S") {
                        continue;
                    }
                    # Get warehouse name
                    db_conn("exten");
                    $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
                    $whRslt = db_exec($sql);
                    $wh = pg_fetch_array($whRslt);
                    # Get stock on this warehouse
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE whid = '{$whid}' AND div = '" . USER_DIV . "' ORDER BY stkcod ASC";
                    $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
                    if (pg_numrows($stkRslt) < 1) {
                        $error .= "<li class='err'>There are no stock items in the selected warehouse.</li>";
                        continue;
                    }
                    $stks = "<select name='stkidss[]' onChange='javascript:document.form.submit();'>";
                    $stks .= "<option value='-S' disabled selected>Select Item Number</option>";
                    $count = 0;
                    while ($stk = pg_fetch_array($stkRslt)) {
                        $stks .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . ($stk['units'] - $stk['alloc']) . ")</option>";
                    }
                    $stks .= "</select> ";
                    # Put in drop down and warehouse
                    $products .= "\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td><input type='hidden' name='whidss[]' value='{$whid}'>{$wh['whname']}</td>\n\t\t\t\t\t\t\t\t\t\t<td>{$stks}</td>\n\t\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]'  value='1'></td>\n\t\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t\t<td>" . mkDateSelecta("d", $key, $d_year[$l], $d_month[$l], $d_day[$l]) . "</td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'><input type='hidden' name='amts[]' value='0.00'>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t</tr>";
                }
            }
            $l++;
        }
    } else {
        if (!isset($diffwhBtn)) {
            # take todays date
            list($date_year, $date_month, $date_day) = explode("-", $pur['pdate']);
            # check if setting exists
            db_connect();
            $sql = "SELECT value FROM set WHERE label = 'DEF_WH' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to check database for existing settings.");
            if (pg_numrows($Rslt) > 0) {
                $set = pg_fetch_array($Rslt);
                $whid = $set['value'];
                if (isset($wtd)) {
                    $whid = $wtd;
                }
                # get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                # get stock on this warehouse
                db_connect();
                $sql = "SELECT * FROM stock WHERE whid = '{$whid}' AND div = '" . USER_DIV . "' ORDER BY stkcod ASC";
                $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
                if (pg_numrows($stkRslt) < 1) {
                    if (!isset($err)) {
                        $err = "";
                    }
                    $err .= "<li>There are no stock items in the selected warehouse.</li>";
                }
                $stks = "<select name='stkidss[]' onChange='javascript:document.form.submit();'>";
                $stks .= "<option value='-S' disabled selected>Select Item Number</option>";
                $count = 0;
                while ($stk = pg_fetch_array($stkRslt)) {
                    $stks .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . ($stk['units'] - $stk['alloc']) . ")</option>";
                }
                $stks .= "</select> ";
                $products .= "\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td><input type='hidden' name='whidss[]' value='{$whid}'>{$wh['whname']}</td>\n\t\t\t\t\t\t\t\t\t<td>{$stks}</td>\n\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td><td> </td>\n\t\t\t\t\t\t\t\t\t<td>" . mkDateSelecta("d", "", $date_year, $date_month, $date_day) . "</td>\n\t\t\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t\t</tr>";
            } else {
                $products .= "\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td>{$whs}</td>\n\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t<td>" . mkDateSelecta("d", "", $date_year, $date_month, $date_day) . "</td>\n\t\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t\t</tr>";
            }
        }
    }
    /* -- start Listeners -- */
    if (isset($diffwhBtn)) {
        # take todays date
        list($date_year, $date_month, $date_day) = explode("-", $pur['pdate']);
        $products .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>{$whs}</td>\n\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t<td>" . mkDateSelecta("d", "", $date_year, $date_month, $date_day) . "</td>\n\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t</tr>";
    }
    /* -- End Listeners -- */
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = sprint($pur['subtot']);
    # Get Total
    $TOTAL = sprint($pur['total']);
    # Get vat
    $VAT = sprint($pur['vat']);
    # Shipping Charges
    $pur['shipchrg'] = sprint($pur['shipchrg']);
    $pur['delvat'] += 0;
    if ($pur['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $pur['delvat'] = $vd['id'];
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    $Vatcodes = "<select name='delvat'>\n\t<option value='0'>Select</option>";
    while ($vd = pg_fetch_array($Ri)) {
        if ($vd['id'] == $pur['delvat']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $Vatcodes .= "</select>";
    /* --- End Some calculations --- */
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h3>New Order</h3>\n\t\t\t\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t\t\t\t<input type='hidden' name='purid' value='{$purid}'>\n\t\t\t\t\t\t<input type='hidden' name='deptid' value='{$deptid}'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t\t\t \t<tr>\n\t\t\t\t\t \t\t<td valign='top'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th colspan='2'> Supplier Details </th>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Department</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$dept['deptname']}</td></tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Supplier</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='20' name='supname' value='{$supname}'></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Supplier No</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='20' name='supno' value='{$supno}'></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><textarea name='supaddr' rows=4 cols='18'>{$supaddr}</textarea></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th colspan='2'> Order Details </th>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Purchase No.</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['purnum']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Order No.</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='ordernum' value='{$pur['ordernum']}'></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Supplier Inv</td>\n\t\t\t\t\t\t\t\t\t\t<td><input type='text' name='supinv' size='10' value='{$pur['supinv']}'></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("p", $p_year, $p_month, $p_day) . "</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' size='7' name='vatinc' value='yes' {$chy}> No<input type='radio' size='7' name='vatinc' value='no' {$chn}> No Vat<input type='radio' size='7' name='vatinc' value='novat' {$chv}></td>\n\t\t\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Delivery Charges</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='7' name='shipchrg' value='{$pur['shipchrg']}'></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Delivery Charges VAT Code</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$Vatcodes}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t\t\t\t<th width='25%'>Remarks</th>\n\t\t\t\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='purchase-view.php'>View Orders</a></td>\n\t\t\t\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='remarks' rows='4' cols='20'>{$pur['remarks']}</textarea></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td align='right'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type=hidden name=subtot value='{$SUBTOT}'>{$SUBTOT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Delivery Charges</td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$pur['shipping']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>VAT {$vat14}</td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$VAT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='total' value='{$TOTAL}'>{$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='right'><input type='button' value='&laquo Back' onClick='javascript:history.back()'> | <input name=diffwhBtn type=submit value='Different Store'> |</td><td><input type=submit name='upBtn' value='Update'>{$done}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</form>\n\t\t\t\t\t</center>";
    return $details;
}
function details($_POST, $error = "")
{
    # get vars
    extract($_POST);
    # Validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # 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 class='err'>Order Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # check if purchase has been printed
    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 department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<li class='err'>Department not Found.</li>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    /* --- Start Drop Downs --- */
    # Select warehouse
    db_conn("exten");
    $whs = "<select name='whidss[]' onChange='javascript:document.form.submit();'>";
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
    $whRslt = db_exec($sql);
    if (pg_numrows($whRslt) < 1) {
        return "<li class='err'> There are no Warehouses found in Cubit.</li>";
    } else {
        $whs .= "<option value='-S' disabled selected>Select Warehouse</option>";
        while ($wh = pg_fetch_array($whRslt)) {
            $whs .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
        }
    }
    $whs .= "</select>";
    # days drop downs
    $days = array("30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $pur['terms']);
    # format date
    list($pyear, $pmon, $pday) = explode("-", $pur['pdate']);
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # select all products
    $products = "\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>STORE</th>\n\t\t\t\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t\t\t\t<th>SERIAL NO.</th>\n\t\t\t\t\t\t\t<th>QTY RECEIVED</th>\n\t\t\t\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t\t\t\t<th>DELIVERY DATE</th>\n\t\t\t\t\t\t\t<th>AMOUNT</th><th>RECEIVED</th>\n\t\t\t\t\t\t<tr>";
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT *,(qty - rqty) as qty FROM pur_items  WHERE purid = '{$purid}' AND (qty - rqty) > 0 AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # keep track of selected stock amounts
        $amts[$i] = $stkd['amt'];
        $i++;
        # get warehouse name
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # get selected stock in this warehouse
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        list($syear, $smon, $sday) = explode("-", $stkd['ddate']);
        # put in product
        if ($stk['serd'] == 'yes') {
            for ($j = 0; $j < $stkd['qty']; $j++) {
                $serial = "";
                if (isset($sers[$stkd['stkid']][$key])) {
                    $serial = $sers[$stkd['stkid']][$key];
                }
                $products .= "\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td><input type='hidden' name='whids[{$key}]' value='{$stkd['whid']}'>{$wh['whname']}</td>\n\t\t\t\t\t\t\t\t\t<td><input type='hidden' name='ids[{$key}]' value='{$stkd['id']}'><input type='hidden' name='stkids[{$key}]' value='{$stkd['stkid']}'><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t\t\t\t\t<td align='center'><input type='text' name='sers[{$stkd['stkid']}][{$key}]' size='20' value='{$serial}'></td>\n\t\t\t\t\t\t\t\t\t<td><input type='hidden' size='5' name='qts[{$key}]' value='1'><input type='hidden' size='5' name='qtys[{$key}]' value='1'>1</td>\n\t\t\t\t\t\t\t\t\t<td><input type='hidden' size='4' name='unitcost[{$key}]' value='{$stkd['unitcost']}'>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t\t\t\t\t\t<td>" . mkDateSelecta("d", $key, "{$syear}", "{$smon}", "{$sday}") . "</td>\n\t\t\t\t\t\t\t\t\t<td>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t\t\t\t\t\t<td><input type='checkbox' name='recvd[]' value='{$key}' checked='yes'></td>\n\t\t\t\t\t\t\t\t</tr>";
                $key++;
            }
        } else {
            $products .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='whids[{$key}]' value='{$stkd['whid']}'>{$wh['whname']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='ids[{$key}]' value='{$stkd['id']}'><input type='hidden' name='stkids[{$key}]' value='{$stkd['stkid']}'><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t\t\t\t<td><br></td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='5' name='qts[{$key}]' value='{$stkd['qty']}'><input type='text' size='5' name='qtys[{$key}]' value='{$stkd['qty']}'></td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' size='4' name='unitcost[{$key}]' value='{$stkd['unitcost']}'>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t\t\t\t\t<td>" . mkDateSelecta("d", $key, "{$syear}", "{$smon}", "{$sday}") . "</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t\t\t\t<td><input type='checkbox' name='recvd[]' value='{$key}' checked='yes'></td>\n\t\t\t\t\t\t\t</tr>";
            $key++;
        }
        # put in product
        // $products .="<tr class='bg-odd'><td><input type=hidden name=whids[] value='$stkd[whid]'>$wh[whname]</td><td><input type=hidden name=ids[] value='$stkd[id]'><input type=hidden name=stkids[] value='$stkd[stkid]'><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid=$stk[stkid]\")'>$stk[stkcod]</a></td><td>$stk[stkdes]</td><td><input type=hidden size=5 name=qts[] value='$stkd[qty]'><input type=hidden size=5 name=qtys[] value='$stkd[qty]'>$stkd[qty]</td><td><input type=hidden size=4 name=unitcost[] value='$stkd[unitcost]'>$stkd[unitcost]</td><td>$sday-$smon-$syear</td><td>".CUR." $stkd[amt]</td></tr>";
        // $key++;
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = sprint($pur['subtot']);
    # Get Total
    $TOTAL = sprint($pur['total']);
    # Get vat
    $VAT = sprint($pur['vat']);
    /* --- End Some calculations --- */
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h3>Order received</h3>\n\t\t\t\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t\t\t\t<input type='hidden' name='purid' value='{$purid}'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td valign='top'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th colspan='2'> Supplier Details </th>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Department</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$dept['deptname']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t   \t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t   \t\t\t\t<td>Supplier</td>\n\t\t\t\t\t\t   \t\t\t\t<td valign='center'>{$pur['supname']}</td>\n\t\t\t\t\t\t   \t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Supplier No.</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['supno']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>" . nl2br($pur['supaddr']) . "</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th colspan='2'> Order Details </th>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Purchase No.</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['purnum']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Delivery Ref No.</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><input type='text' name='refno' size='10' value=''></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['terms']} Days</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pyear}-{$pmon}-{$pday}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['vatinc']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Delivery Charges</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>" . CUR . " <input type='hidden' name='shipchrg' size='10' value='{$pur['shipchrg']}'>{$pur['shipchrg']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t\t\t\t<th width='25%'>Remarks</th>\n\t\t\t\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='purchase-new.php'>New Order</a></td>\n\t\t\t\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='remarks' rows='4' cols='20'>{$pur['remarks']}</textarea></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td><a href='purchase-view.php'>View Orders</a></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td align='right'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$SUBTOT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Delivery Charges</td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$pur['shipping']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>VAT @ " . TAX_VAT . " %</td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$pur['vat']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='right'><input type='button' value='&laquo Back' onClick='javascript:history.back()'> | <input type='submit' name='upBtn' value='Write'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</form>\n\t\t\t\t\t</center>";
    return $details;
}
function slctacc($_POST, $err = "")
{
    # Get vars
    extract($_POST);
    if (!isset($tnum)) {
        $tnum = 1;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($tnum, "num", 1, 3, "Invalid Number of transactions.");
    if ($tnum < 1) {
        $v->isOk("#error#", "num", 1, 1, " - Number of transactions must be at least one.");
    }
    # 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;
    }
    $jump_bot = "";
    if (isset($another)) {
        $jump_bot = "\n\t\t\t<script>\n\t\t\t\twindow.location.hash='bottom';\n\t\t\t</script>";
        $tnum++;
    }
    if (!isset($refnum)) {
        $refnum = getrefnum();
    }
    /*refnum*/
    // Accounts (debit)
    $view = "\n\t\t<center>\n\t\t<h3> Journal transactions </h3>\n\t\t{$err}\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t<input type='hidden' name='vby' value='{$vby}'>\n\t\t\t<input type='hidden' name='tnum' value='{$tnum}'>\n\t\t<table " . TMPL_tblDflts . " align='center'>\n\t\t\t<tr>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Ref num</th>\n\t\t\t\t<th>Debit <input align='right' type='button' onClick=\"window.open('acc-new2.php?update_parent=yes&set_key=slct','accounts','width=700, height=400');\" value='New Account'></th>\n\t\t\t\t<th>Credit <input align='right' type='button' onClick=\"window.open('acc-new2.php?update_parent=yes&set_key=slct','accounts','width=700, height=400');\" value='New Account'></th>\n\t\t\t\t<th>Amount</th>\n\t\t\t\t<th>Description</th>\n\t\t\t</tr>";
    for ($i = 0; $i < $tnum; $i++) {
        if (!isset($date_day[$i])) {
            $trans_date_setting = getCSetting("USE_TRANSACTION_DATE");
            if (isset($trans_date_setting) and $trans_date_setting == "yes") {
                $trans_date_value = getCSetting("TRANSACTION_DATE");
                $date_arr = explode("-", $trans_date_value);
                $date_year[$i] = $date_arr[0];
                $date_month[$i] = $date_arr[1];
                $date_day[$i] = $date_arr[2];
            } else {
                $date_year[$i] = date("Y");
                $date_month[$i] = date("m");
                $date_day[$i] = date("d");
            }
        }
        $view .= "\n\t\t\t<tr bgcolor=" . bgcolorg() . ">\n\t\t\t\t<td>" . mkDateSelecta("date", $i, $date_year[$i], $date_month[$i], $date_day[$i]) . "</td>\n\t\t\t\t<td><input type='text' size='5' name='refnum[{$i}]' value='{$refnum[$i]}'></td>\n\t\t\t\t<td valign='center'>";
        core_connect();
        $sql = "SELECT * FROM accounts WHERE div = '" . USER_DIV . "' ORDER BY {$vby} ASC";
        $accRslt = db_exec($sql);
        if (pg_numrows($accRslt) < 1) {
            return "<li>There are No accounts in Cubit.</li>";
        }
        $dtaccid[$i] += 0;
        $view .= mkAccSelect("dtaccid[{$i}]", $dtaccid[$i]);
        $view .= "\n\t\t\t</td>\n\t\t\t<td valign='center'>";
        $ctaccid[$i] += 0;
        $view .= mkAccSelect("ctaccid[]", $ctaccid[$i]);
        if (isset($amount[$i])) {
            $a_val = $amount[$i];
        } else {
            $a_val = "";
        }
        if (isset($descript[$i])) {
            $d_val = $descript[$i];
        } else {
            $d_val = "";
        }
        $view .= "\n\t\t\t\t</td>\n\t\t\t\t<td><input type='text' size='7' name='amount[]' value='{$a_val}'></td>\n\t\t\t\t<td><input type='text' size='20' name='descript[]' value='{$d_val}'></td>\n\t\t\t</tr>";
    }
    $view .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='4' align='right'><b>Total:</b></td>\n\t\t\t<td>" . CUR . " " . sprint(array_sum($amount)) . "</td>\n\t\t\t<td></td>\n\t\t</tr>";
    $view .= "\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><input type='submit' name='another' value='Add Another'></td>\n\t\t\t\t<td valign='center' colspan='4' align='right'><input type='submit' value='Confirm &raquo;'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>\n\t\t<a name='bottom'>\n\t\t{$jump_bot}\n\t\t<table border='0' cellpadding='2' cellspacing='1' width='15%'>\n\t\t\t<tr><td><br></td></tr>\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='datacell'>\n\t\t\t\t<td align='center'><a href='../reporting/index-reports.php'>Financials</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $view;
}
function details($err = "")
{
    $showvat = TRUE;
    # get vars
    extract($_REQUEST);
    # Validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Purchase number.");
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # 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 class='err'>Purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $get_codes = "SELECT * FROM suppstock WHERE suppid = '{$pur['supid']}' ORDER BY stkid";
    $run_codes = db_exec($get_codes) or errDie("Unable to get supplier stock code information");
    if (pg_numrows($run_codes) > 0) {
        while ($codarr = pg_fetch_array($run_codes)) {
            if (strlen($codarr['stkcod']) > 0) {
                $stockcodes[$codarr['stkid']]['stkcod'] = $codarr['stkcod'];
            }
            if (strlen($codarr['stkdes']) > 0) {
                $stockcodes[$codarr['stkid']]['stkdes'] = $codarr['stkdes'];
            }
        }
    }
    # check if purchase has been printed
    if ($pur['apprv'] != "y") {
        $error = "<li class='err'> Error : purchase number <b>{$purid}</b> has not yet been approved.";
        return $error;
    }
    # check if purchase has been printed
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$purid}</b> has already been received.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<li class='err'>Department not Found.";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # 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 view customer");
    if (pg_numrows($supRslt) < 1) {
        $sup['supname'] = "<li class='err'> Supplier not Found.";
        $sup['supaddr'] = "<br><br><br>";
    } else {
        $sup = pg_fetch_array($supRslt);
        $supaddr = $sup['supaddr'];
    }
    /* --- Start Drop Downs --- */
    # Select warehouse
    db_conn("exten");
    $whs = "<select name='whidss[]' onChange='javascript:document.form.submit();'>";
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
    $whRslt = db_exec($sql);
    if (pg_numrows($whRslt) < 1) {
        return "<li class='err'> There are no Warehouses found in Cubit.";
    } else {
        $whs .= "<option value='-S' disabled selected>Select Warehouse</option>";
        while ($wh = pg_fetch_array($whRslt)) {
            $whs .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
        }
    }
    $whs .= "</select>";
    # days drop downs
    $days = array("30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $pur['terms']);
    # format date
    list($pyear, $pmon, $pday) = explode("-", $pur['pdate']);
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # select all products
    $products = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>STORE</th>\n\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<TH>SERIAL NO.</TH>\n\t\t\t\t<th>QTY RECEIVED</th>\n\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t<th>DISCOUNT</th>\n\t\t\t\t<th>DELIVERY DATE</th>\n\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t<th>RECEIVED</th>\n\t\t\t<tr>";
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT *,(qty - rqty) as qty FROM pur_items  WHERE purid = '{$purid}' AND (qty - rqty) > 0 AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # get warehouse name
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # get selected stock in this warehouse
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        if (isset($stockcodes[$stk['stkid']]['stkcod'])) {
            $stk['stkcod'] = $stockcodes[$stk['stkid']]['stkcod'];
        }
        if (isset($stockcodes[$stk['stkid']]['stkdes'])) {
            $stk['stkdes'] = $stockcodes[$stk['stkid']]['stkdes'];
        }
        list($syear, $smon, $sday) = explode("-", $stkd['ddate']);
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
        $Ri = db_exec($Sl);
        $vd = pg_fetch_array($Ri);
        if (TAX_VAT != $vd['vat_amount'] and $vd['vat_amount'] != "0.00") {
            $showvat = FALSE;
        }
        # put in product
        if ($stk['serd'] == 'yes') {
            for ($j = 0; $j < $stkd['qty']; $j++) {
                $serial = "";
                if (isset($sers[$stkd['stkid']][$key])) {
                    $serial = $sers[$stkd['stkid']][$key];
                }
                $products .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' name='whids[{$key}]' value='{$stkd['whid']}'>{$wh['whname']}</td>\n\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t<input type='hidden' name='ids[{$key}]' value='{$stkd['id']}'>\n\t\t\t\t\t\t\t<input type='hidden' name='stkids[{$key}]' value='{$stkd['stkid']}'>\n\t\t\t\t\t\t\t<a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t\t<td align='center'><input type='text' tabindex='" . ($key + 1) . "' name='sers[{$stkd['stkid']}][{$key}]' size='20' value='{$serial}'></td>\n\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t<input type='hidden' size='5' name='qts[{$key}]' value='1'>\n\t\t\t\t\t\t\t<input type='hidden' size='5' name='qtys[{$key}]' value='1'>1\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td nowrap><input type='hidden' size='4' name='unitcost[{$key}]' value='{$stkd['unitcost']}'>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t\t\t<td nowrap><input type='hidden' size='4' name='udiscount[{$key}]' value='{$stkd['udiscount']}'>" . CUR . " {$stkd['udiscount']}</td>\n\t\t\t\t\t\t<td>" . mkDateSelecta("d", $key, $syear, $smon, $sday) . "</td>\n\t\t\t\t\t\t<td nowrap>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t\t\t<td><input type='checkbox' name='recvd[]' value='{$key}' checked='yes'></td>\n\t\t\t\t\t</tr>";
                $key++;
            }
        } else {
            if ($stkd['account'] > 0) {
                $stk['stkdes'] = $stkd['description'];
                $stk['stkid'] = "";
                $stk['stkcod'] = "";
            }
            $stkd['qty'] = sprint3($stkd['qty']);
            $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='hidden' name='whids[{$key}]' value='{$stkd['whid']}'>{$wh['whname']}</td>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<input type='hidden' name='ids[{$key}]' value='{$stkd['id']}'>\n\t\t\t\t\t\t<input type='hidden' name='stkids[{$key}]' value='{$stkd['stkid']}'>\n\t\t\t\t\t\t<a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t<td><br></td>\n\t\t\t\t\t<td><input type='hidden' size='5' name='qts[{$key}]' value='{$stkd['qty']}'><input type='text' size='7' name='qtys[{$key}]' value='{$stkd['qty']}'></td>\n\t\t\t\t\t<td nowrap><input type='hidden' size='4' name='unitcost[{$key}]' value='{$stkd['unitcost']}'>" . CUR . " {$stkd['unitcost']}</td>\n\t\t\t\t\t<td nowrap><input type='hidden' size='4' name='udiscount[{$key}]' value='{$stkd['udiscount']}'>{$stkd['udiscount']}</td>\n\t\t\t\t\t<td>" . mkDateSelecta("d", $key, $syear, $smon, $sday) . "</td>\n\t\t\t\t\t<td nowrap>" . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t<td><input type='checkbox' name='recvd[]' value='{$key}' checked='yes'></td>\n\t\t\t\t</tr>";
            $key++;
        }
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = sprint($pur['subtot']);
    $TOTAL = sprint($pur['total']);
    $VAT = sprint($pur['vat']);
    /* --- End Some calculations --- */
    global $_GET;
    if (isset($_GET['invoice']) or isset($_POST['invoice'])) {
        $fex = "<input type='hidden' name='invoice' value='invoice'>";
    } else {
        $fex = "";
    }
    if ($TOTAL == 0) {
        return "<li class='err'>The total purchase amount is zero. You cannot receive a R0 purchase. If it doesnt cost anything, its not a purchase.</li>";
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    if (isset($gds_note) and strlen($gds_note) > 0) {
        $gdssel = "checked='yes'";
    } else {
        $gdssel = "";
    }
    /* -- Final Layout -- */
    $details = "\n\t\t<center>\n\t\t<h3>Stock Order received</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t{$err}\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t<input type='hidden' name='purid' value='{$purid}'>\n\t\t\t{$fex}\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Supplier Details </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>Department</td>\n\t\t\t\t\t\t\t<td valign='center'>{$dept['deptname']}</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>Supplier</td>\n\t\t\t\t\t\t\t<td valign='center'>{$sup['supname']}</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>Account number</td>\n\t\t\t\t\t\t\t<td valign='center'>{$sup['supno']}</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 valign=top>Supplier Address</td>\n\t\t\t\t\t\t\t<td valign='center'>" . nl2br($supaddr) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr><th colspan='2'> Purchase Details </th></tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Purchase No.</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pur['purnum']}</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>Supplier Inv.</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' name='supinv' size='10' value='{$pur['supinv']}'></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>Delivery Ref No.</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' name='refno' size='10' value=''></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>Terms</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pur['terms']} Days</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>Date</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pday}-{$pmon}-{$pyear}</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 Inclusive</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pur['vatinc']}</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>Delivery Charges</td>\n\t\t\t\t\t\t\t<td valign='center'>" . CUR . " <input type='hidden' name='shipchrg' size='10' value='{$pur['shipchrg']}'>{$pur['shipchrg']}</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>Print Goods Received Note</td>\n\t\t\t\t\t\t\t<td><input type='checkbox' name='gds_note' value='yes' {$gdssel}></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr><td colspan='2'>{$products}</td></tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t<th width='25%'>Remarks</th>\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='purchase-new.php'>New Stock Order</a></td>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='remarks' rows='4' cols='20'>{$pur['remarks']}</textarea></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='purchase-view.php'>View Stock Orders</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\t<td align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$SUBTOT}</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>Delivery Charges</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$pur['shipping']}</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 {$vat14}</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$pur['vat']}</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<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input type='submit' name='upBtn' value='Confirm'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>\n\t\t</center>";
    return $details;
}
function details($_POST, $error = "")
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($purid)) {
        $v->isOk($purid, "num", 1, 20, "Invalid Non-Stock Order number.");
    } else {
        $v->isOk($ctyp, "string", 0, 20, "Invalid purchase type.");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (!isset($purid)) {
        $purid = create_dummy(0);
    }
    # Get Order info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get Order information");
    if (pg_numrows($purRslt) < 1) {
        return "<li class='err'>Purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    # check if Order has been printed
    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;
    }
    if (!isset($ordernum)) {
        $ordernum = '';
    }
    /* --- Start Drop Downs --- */
    # days drop downs
    $days = array("0" => "0", "7" => "7", "14" => "14", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $pur['terms']);
    # format date
    list($npur_year, $npur_month, $npur_day) = explode("-", $pur['pdate']);
    # keep the charge vat option stable
    if ($pur['vatinc'] == "yes") {
        $chy = "checked=yes";
        $chn = "";
        $chnv = "";
    } else {
        if ($pur['vatinc'] == 'novat') {
            $chy = "";
            $chn = "";
            $chnv = "checked=yes";
        } else {
            $chy = "";
            $chn = "checked=yes";
            $chnv = "";
        }
    }
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # Select all products
    $products = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t<th>VAT CODE</th>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<th>QTY</th>\n\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t<th>DELIVERY DATE</th>\n\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t<th>VAT</th>\n\t\t\t\t<th>Remove</th>\n\t\t\t<tr>";
    # get selected stock in this Order
    db_connect();
    $sql = "SELECT * FROM nons_pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # keep track of selected stock amounts
        $amts[$i] = $stkd['amt'];
        $i++;
        list($syear, $smon, $sday) = explode("-", $stkd['ddate']);
        $stkd['amt'] = round($stkd['amt'], 2);
        $tip = "&nbsp;&nbsp;&nbsp;";
        if (isset($vatc[$key])) {
            $tip = "<font color='red'>#</font>";
            $error = "<div class='err'> {$tip}&nbsp;&nbsp;=&nbsp;&nbsp; Vat amount is different from amount calculated by cubit. To allow cubit to recalculate the vat amount, please delete the vat amount from the input box.";
        }
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
        $Vatcodes = "\n\t\t\t<select name='vatcodes[]'>\n\t\t\t\t<option value='0'>Select</option>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($stkd['vatcode'] == $vd['id']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $Vatcodes .= "</select>";
        $stkd['amt'] = sprint($stkd['amt']);
        # put in product
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value='{$stkd['cod']}'></td>\n\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t<td align='center'><input type='text' size='20' name='des[]' value='{$stkd['des']}'></td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'></td>\n\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'></td>\n\t\t\t\t<td align='center'>" . mkDateSelecta("d", array($i), $syear, $smon, $sday) . "</td>\n\t\t\t\t<td><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t<td>{$tip} <input type='text' name='vat[]' size='9' value='{$stkd['svat']}'></td>\n\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$key}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t</tr>";
        $key++;
    }
    # Look above(remprod keys)
    $keyy = $key;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
        $Vatcodes = "\n\t\t\t<select name='vatcodes[]'>\n\t\t\t\t<option value='0'>Select</option>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($vd['del'] == "Yes") {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $Vatcodes .= "</select>";
        $trans_date_setting = getCSetting("USE_TRANSACTION_DATE");
        if (isset($trans_date_setting) and $trans_date_setting == "yes") {
            $trans_date_value = getCSetting("TRANSACTION_DATE");
            $date_arr = explode("-", $trans_date_value);
            $item_year = $date_arr[0];
            $item_month = $date_arr[1];
            $item_day = $date_arr[2];
        } else {
            $item_year = date("Y");
            $item_month = date("m");
            $item_day = date("d");
        }
        # add one
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value=''></td>\n\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t<td align='center'><input type='text' size='20' name='des[]' value=''></td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='1'></td>\n\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]'></td>\n\t\t\t\t<td align='center'>" . mkDateSelecta("d", array($i), $item_year, $item_month, $item_day) . "</td>\n\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t<td><input type='hidden' name='novat[]' value='1'></td>\n\t\t\t\t<td> </td>\n\t\t\t</tr>";
    }
    /* -- start Listeners -- */
    if (isset($diffwhBtn)) {
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
        $Vatcodes = "\n\t\t\t<select name='vatcodes[]'>\n\t\t\t\t<option value='0'>Select</option>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($vd['del'] == "Yes") {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $Vatcodes .= "</select>";
        $j = $i + 1;
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value=''></td>\n\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t</td><td align='center'><input type='text' size='20' name='des[]' value=''></td>\n\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='1'></td>\n\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]'></td>\n\t\t\t\t<td align='center'>" . mkDateSelecta("d", array($j)) . "</td>\n\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t<td><input type='hidden' name='novat[{$j}]' value='1'></td>\n\t\t\t\t<td> </td>\n\t\t\t</tr>";
        $key++;
    }
    /* -- End Listeners -- */
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = $pur['subtot'];
    # Get Total
    $TOTAL = sprint($pur['total']);
    # Get vat
    $VAT = sprint($pur['vat']);
    /* --- End Some calculations --- */
    if ($pur['ctyp'] == "s") {
        db_connect();
        $sql = "SELECT * FROM suppliers WHERE location != 'int' AND div = '" . USER_DIV . "' ORDER BY supno ASC";
        $supRslt = db_exec($sql) or errDie("Could not retrieve Suppliers Information from the Database.", SELF);
        $sups = "<select name='supplier'>";
        if (pg_numrows($supRslt) < 1) {
            $sups .= "<option value='-S'></option>";
        }
        while ($sup = pg_fetch_array($supRslt)) {
            if ($sup['supid'] == $pur['supplier']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $sups .= "<option value='{$sup['supid']}' {$sel}>{$sup['supno']} {$sup['supname']}</option>";
        }
        $sups .= "</select>";
        $sdata = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Supplier</td>\n\t\t\t\t<td>{$sups}</td>\n\t\t\t</tr>\n\t\t\t<input type='hidden' name='supaddr' value=''>";
    } elseif ($pur['ctyp'] == "cb") {
        $sdata = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Supplier</td>\n\t\t\t\t<td valign='center'><input type='text' name='supplier' value='{$pur['supplier']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t<td valign='center'><textarea name='supaddr' cols='18' rows='3'>{$pur['supaddr']}</textarea></td>\n\t\t\t</tr>";
    } elseif ($pur['ctyp'] == "c") {
        if (strlen($pur['supplier']) < 1) {
            $pur['supplier'] = "Cash Order";
        }
        //Cash Order
        $sdata = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Supplier</td>\n\t\t\t\t<td valign='center'><input type='text' name='supplier' value='{$pur['supplier']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t<td valign='center'><textarea name='supaddr' cols='18' rows='3'>{$pur['supaddr']}</textarea></td>\n\t\t\t</tr>";
    } elseif ($pur['ctyp'] == "p") {
        if (strlen($pur['supplier']) < 1) {
            $pur['supplier'] = "Petty Cash Order";
        }
        //Petty Cash Order
        $sdata = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Supplier</td>\n\t\t\t\t<td valign='center'><input type='text' name='supplier' value='{$pur['supplier']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t<td valign='center'><textarea name='supaddr' cols='18' rows='3'>{$pur['supaddr']}</textarea></td>\n\t\t\t</tr>";
    } elseif ($pur['ctyp'] == "ac") {
        //<input type='text' name='supplier' value='$pur[supplier]'>
        if (strlen($pur['supplier']) < 1) {
            $pur['supplier'] = "Ledger Account Order";
        }
        //Ledger Account Order
        $sdata = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Supplier</td>\n\t\t\t\t<td valign='center'><input type='text' name='supplier' value='{$pur['supplier']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t<td valign='center'><textarea name='supaddr' cols='18' rows='3'>{$pur['supaddr']}</textarea></td>\n\t\t\t</tr>";
    } elseif ($pur['ctyp'] == "c") {
        $sdata = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Supplier</td>\n\t\t\t\t<td valign='center'><input type='text' name='supplier' value='{$pur['supplier']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t<td valign='center'><textarea name='supaddr' cols='18' rows='3'>{$pur['supaddr']}</textarea></td>\n\t\t\t</tr>";
    } else {
        return slct($_POST);
    }
    $pur['delvat'] += 0;
    if ($pur['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $pur['delvat'] = $vd['id'];
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    $Vatcodes = "\n\t\t<select name='delvat'>\n\t\t\t<option value='0'>Select</option>";
    while ($vd = pg_fetch_array($Ri)) {
        if ($vd['id'] == $pur['delvat']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $ex = "";
    if (strlen($pur['supinv']) and $pur['ctyp'] == "s") {
        db_conn('cubit');
        $Sl = "SELECT purnum,pdate FROM nons_purchases WHERE supplier='{$pur['supplier']}' AND supinv='{$pur['supinv']}' AND purid != '{$purid}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) > 0) {
            $pd = pg_fetch_array($Ri);
            $ex .= "<li class='err'>Non Stock Purchase {$pd['purnum']} on {$pd['pdate']} has the same supplier invoice number.</li>";
        }
        for ($i = 1; $i < 13; $i++) {
            db_conn($i);
            $Sl = "SELECT purnum,pdate FROM nons_purchases WHERE supplier='{$pur['supplier']}' AND supinv='{$pur['supinv']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) > 0) {
                $pd = pg_fetch_array($Ri);
                $ex .= "<li class='err'>Non Stock Purchase {$pd['purnum']} on {$pd['pdate']} has same the supplier invoice number.</li>";
            }
        }
        db_conn('cubit');
        $Sl = "SELECT purnum,pdate FROM purchases WHERE supid='{$pur['supplier']}' AND supinv='{$pur['supinv']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) > 0) {
            $pd = pg_fetch_array($Ri);
            $ex .= "<li class='err'>Purchase {$pd['purnum']} on {$pd['pdate']} has the same supplier invoice number.</li>";
        }
        for ($i = 1; $i < 13; $i++) {
            db_conn($i);
            $Sl = "SELECT purnum,pdate FROM purchases WHERE supid='{$pur['supplier']}' AND supinv='{$pur['supinv']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) > 0) {
                $pd = pg_fetch_array($Ri);
                $ex .= "<li class='err'>Purchase {$pd['purnum']} on {$pd['pdate']} has same the supplier invoice number.</li>";
            }
        }
    }
    $Vatcodes .= "</select>";
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    if (!isset($supinv)) {
        $supinv = $pur['supinv'];
    }
    /* -- Final Layout -- */
    $details = "\n\t\t<center>\n\t\t<h3>New Non-Stock Order</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t<input type='hidden' name='purid' value='{$purid}'>\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Supplier Details </th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t{$sdata}\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan=2> Non-Stock Order Details </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>Non-Stock Order No.</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pur['purnum']}</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>Order No.</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='ordernum' value='{$ordernum}'></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>Supplier Inv No</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='supinv' value='{$supinv}'></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>Terms</td>\n\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</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>Date</td>\n\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("npur", $npur_year, $npur_month, $npur_day) . "</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 Inclusive</td>\n\t\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' size='7' name='vatinc' value='yes' {$chy}> No<input type='radio' size='7' name='vatinc' value='no' {$chn}></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>Delivery Charges</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='7' name='shipchrg' value='{$pur['shipchrg']}'>{$Vatcodes}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<p>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t<th width='25%'>Remarks</th>\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$ex} {$error}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='nons-purchase-view.php'>View Non-Stock Orders</a></td>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='remarks' rows='4' cols='20'>{$pur['remarks']}</textarea></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='main.php'>Main Menu</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='subtot' value='{$SUBTOT}'>{$SUBTOT}</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>Delivery Charges</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$pur['shipping']}</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 {$vat14}</td>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$pur['vat']}</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<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='total' value='{$TOTAL}'>{$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='center'><input name='diffwhBtn' type='submit' value='Add Item'> | <input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>\n\t\t</center>";
    return $details;
}
function details($_POST)
{
    # Get vars
    extract($_POST);
    if (!isset($numcont)) {
        $numcont = 1;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($date_day, "num", 1, 2, "Invalid to Date day.");
    $v->isOk($date_month, "num", 1, 2, "Invalid to Date month.");
    $v->isOk($date_year, "num", 1, 4, "Invalid to Date Year.");
    $date = $date_day . "-" . $date_month . "-" . $date_year;
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    $v->isOk($accid, "num", 1, 50, "Invalid Account to be Debited.");
    $v->isOk($tran, "string", 1, 3, "Invalid type of transaction.");
    $v->isOk($numcont, "num", 1, 10, "Invalid number of contra accounts.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $confirm . slctacc($_POST);
    }
    $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>";
    }
    # get account
    $accRs = get("core", "*", "accounts", "accid", $accid);
    $macc = pg_fetch_array($accRs);
    $temprefnum = getrefnum();
    /*refnum*/
    $jump_bot = "";
    if (isset($another)) {
        $jump_bot = "\n\t\t\t<script>\n\t\t\t\twindow.location.hash='bottom';\n\t\t\t</script>";
        $numcont++;
    }
    // Deatils
    $details = "\n\t\t<p>\n\t\t<h3> Journal transactions details</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t<input type='hidden' name='accid' value='{$accid}'>\n\t\t\t<input type='hidden' name='tran' value='{$tran}'>\n\t\t\t<input type='hidden' name='numcont' value='{$numcont}'>\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<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Ref num</th>\n\t\t\t\t<th>Debit <input align='right' type='button' onClick=\"window.open('acc-new2.php?update_parent=yes&set_key=details','accounts','width=700, height=400');\" value='New Account'></th>\n\t\t\t\t<th>Credit <input align='right' type='button' onClick=\"window.open('acc-new2.php?update_parent=yes&set_key=details','accounts','width=700, height=400');\" value='New Account'></th>\n\t\t\t\t<th>Amount</th>\n\t\t\t\t<th>Description</th>\n\t\t\t</tr>";
    for ($i = 0; $i != $numcont; $i++) {
        if (isset($amount[$i])) {
            $ta = $amount[$i];
        } else {
            $ta = "";
        }
        if (isset($descript[$i])) {
            $da = $descript[$i];
        } else {
            $da = "";
        }
        if (!isset($caccid[$i])) {
            $tc = 0;
        } else {
            $tc = $caccid[$i];
        }
        if (!isset($each_day[$i])) {
            $each_day[$i] = $date_day;
            $each_month[$i] = $date_month;
            $each_year[$i] = $date_year;
        }
        if (!isset($refnum[$i])) {
            $refnum[$i] = $temprefnum;
        }
        # details
        $details .= "\n\t\t\t<tr bgcolor=" . bgcolorg() . ">\n\t\t\t\t<td>" . mkDateSelecta("each", $i, $each_year[$i], $each_month[$i], $each_day[$i]) . "</td>\n\t\t\t\t<td align='center'><input type='text' size='5' name='refnum[]' value='{$refnum[$i]}'></td>";
        core_connect();
        $sql = "SELECT * FROM accounts WHERE accid != '{$accid}' AND div = '" . USER_DIV . "' ORDER BY accname ASC";
        $accRslt = db_exec($sql);
        if (pg_numrows($accRslt) < 1) {
            return "<li>There are No accounts in Cubit.</li>";
        }
        $accs = mkAccSelect("caccid[]", $tc);
        // 		$accs = "<select name='caccid[]'>";
        // 		while($acc = pg_fetch_array($accRslt)){
        // 			# Check Disable
        // 			if(isDisabled($acc['accid']))
        // 				continue;
        // 			if($tc == $acc['accid']) {
        // 				$sel = "selected";
        // 			} else {
        // 				$sel = "";
        // 			}
        // 			$accs .= "<option value='$acc[accid]' $sel>$acc[topacc]/$acc[accnum] - $acc[accname]</option>";
        // 		}
        // 		$accs .= "</select>";
        if ($tran == 'dt') {
            $accts = "<td>{$macc['topacc']}/{$macc['accnum']} - {$macc['accname']}</td><td>{$accs}</td>";
        } else {
            $accts = "<td>{$accs}</td><td>{$macc['topacc']}/{$macc['accnum']} - {$macc['accname']}</td>";
        }
        $details .= "\n\t\t\t\t{$accts}\n\t\t\t\t<td><input type='text' size='7' name='amount[]' value='{$ta}'></td>\n\t\t\t\t<td><input type='text' size='20' name='descript[]' value='{$da}'></td>\n\t\t\t</tr>";
    }
    $details .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='4' align='right'><b>Total:</b></td>\n\t\t\t<td>" . CUR . " " . sprint(array_sum($amount)) . "</td>\n\t\t\t<td></td>\n\t\t</tr>";
    $details .= "\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><input type='submit' name='another' value='Add Another'></td>\n\t\t\t\t<td valign='center' colspan='2' align='right'><input type='submit' value='Confirm &raquo;'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>\n\t\t<a name='bottom'>\n\t\t{$jump_bot}\n\t\t<table border='0' cellpadding='2' cellspacing='1' 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 align='center'><a href='../reporting/index-reports.php'>Financials</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td align='center'><a href='trans-new.php'>Journal Transactions</td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $details;
}
function slctacc($_POST, $err = "")
{
    extract($_POST);
    if (!isset($refnum)) {
        $refnum = getrefnum();
    }
    /*refnum*/
    // Accounts (debit)
    $view = "\n\t\t<center>\n\t\t<h3>Add Journal transactions to batch </h3>\n\t\t{$err}\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t<table " . TMPL_tblDflts . " align='center'>\n\t\t\t<tr>\n\t\t\t\t<th>Date</th>\n\t\t\t\t<th>Ref num</th>\n\t\t\t\t<th>Debit <input align='right' type='button' onClick=\"window.open('acc-new2.php?update_parent=yes','accounts','width=700, height=400');\" value='New Account'></th>\n\t\t\t\t<th>Credit <input align='right' type='button' onClick=\"window.open('acc-new2.php?update_parent=yes','accounts','width=700, height=400');\" value='New Account'></th>\n\t\t\t\t<th>Amount</th>\n\t\t\t\t<th>Description</th>\n\t\t\t</tr>";
    for ($i = 0; $i != 20; $i++) {
        // 		if (!isset($date_year[$i])){
        // 			$date_year[$i] = date("Y");
        // 			$date_month[$i] = date("m");
        // 			$date_day[$i] = date ("d");
        // 		}
        if (!isset($date_year[$i])) {
            $trans_date_setting = getCSetting("USE_TRANSACTION_DATE");
            if (isset($trans_date_setting) and $trans_date_setting == "yes") {
                $trans_date_value = getCSetting("TRANSACTION_DATE");
                $date_arr = explode("-", $trans_date_value);
                $date_year[$i] = $date_arr[0];
                $date_month[$i] = $date_arr[1];
                $date_day[$i] = $date_arr[2];
            } else {
                $date_year[$i] = date("Y");
                $date_month[$i] = date("m");
                $date_day[$i] = date("d");
            }
        }
        $view .= "\n\t\t\t<tr bgcolor=" . bgcolorg() . ">\n\t\t\t\t<td>" . mkDateSelecta("date", $i, $date_year[$i], $date_month[$i], $date_day[$i]) . "</td>\n\t\t\t\t<td><input type='text' size='5' name='refnum[]' value='{$refnum[$i]}'></td>\n\t\t\t\t<td valign='center'>";
        core_connect();
        $sql = "SELECT * FROM accounts WHERE div = '" . USER_DIV . "' ORDER BY accname ASC";
        $accRslt = db_exec($sql);
        if (pg_numrows($accRslt) < 1) {
            return "<li>There are No accounts in Cubit.</li>";
        }
        if (isset($dtaccid[$i])) {
            $aval = $dtaccid[$i];
        } else {
            $aval = 0;
        }
        $view .= mkAccSelect("dtaccid[]", $aval);
        // 		$view .= "<select name='dtaccid[]' style='width: 230'>";
        // 		while($acc = pg_fetch_array($accRslt)){
        // 			# Check Disable
        // 			if(isDisabled($acc['accid']))
        // 				continue;
        // 			if($acc['accid'] == $aval) {
        // 				$sel = "selected";
        // 			} else {
        // 				$sel = "";
        // 			}
        // 			$view .= "<option value='$acc[accid]' $sel>$acc[accname]</option>";
        // 		}
        // 		$view .= "</select>";
        $view .= "\n\t\t\t</td>\n\t\t\t<td valign='center'>";
        // 		$sql = "SELECT * FROM accounts WHERE div = '".USER_DIV."' ORDER BY accname ASC";
        // 		$accRslt = db_exec($sql);
        // 		if(pg_numrows($accRslt) < 1){
        // 			return "<li>There are No accounts in Cubit.</li>";
        // 		}
        if (isset($ctaccid[$i])) {
            $aval = $ctaccid[$i];
        } else {
            $aval = 0;
        }
        $view .= mkAccSelect("ctaccid[]", $aval);
        // 		$view .= "<select name='ctaccid[]' style='width: 230'>";
        // 		while($acc = pg_fetch_array($accRslt)){
        // 			# Check Disable
        // 			if(isDisabled($acc['accid']))
        // 				continue;
        // 			if($aval == $acc['accid']) {
        // 				$sel = "selected";
        // 			} else {
        // 				$sel = "";
        // 			}
        // 			$view .= "<option value='$acc[accid]' $sel>$acc[accname]</option>";
        // 		}
        // 		$view .= "</select>";
        if (isset($amount[$i])) {
            $aval = $amount[$i];
        } else {
            $aval = "";
        }
        if (isset($descript[$i])) {
            $dval = $descript[$i];
        } else {
            $dval = "";
        }
        $view .= "\n\t\t\t\t</td>\n\t\t\t\t<td><input type='text' size='7' name='amount[]' value='{$aval}'></td>\n\t\t\t\t<td><input type='text' size='20' name='descript[]' value='{$dval}'></td>\n\t\t\t</tr>";
    }
    $view .= "\n\t\t\t<tr>\n\t\t\t\t<td></td>\n\t\t\t\t<td valign='center' colspan='4' align='right'><input type='submit' value='Confirm &raquo;'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>\n\t\t<table border=0 cellpadding='2' cellspacing='1' width=15%>\n\t\t\t<tr><td><br></td></tr>\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='datacell'>\n\t\t\t\t<td align='center'><a href='../reporting/index-reports.php'>Financials</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td align='center'><a href='batch-view.php'>View batch Entries</td>\n\t\t\t</tr>\n\t\t\t<tr class='datacell'>\n\t\t\t\t<td align='center'><a href='trans-new.php'>Journal Transaction</td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $view;
}
function details($_POST, $error = "")
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($purid, "num", 1, 20, "Invalid Purchase number.");
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get purchase info
    db_connect();
    $sql = "SELECT * FROM nons_purchases WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $purRslt = db_exec($sql) or errDie("Unable to get purchase information");
    if (pg_numrows($purRslt) < 1) {
        return slct($_POST, "<li class='err'>No Non Stock Purchase Found</li>");
    }
    $pur = pg_fetch_array($purRslt);
    # check if purchase has been printed
    if ($pur['received'] == "y") {
        $error = "<li class='err'> Error : purchase number <b>{$purid}</b> has already been received.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    if (!isset($ordernum)) {
        $ordernum = '';
    }
    /* --- Start Drop Downs --- */
    # days drop downs
    $days = array("0" => "0", "7" => "7", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $pur['terms']);
    # format date
    list($lnpur_year, $lnpur_month, $lnpur_day) = explode("-", $pur['pdate']);
    # keep the charge vat option stable
    if ($pur['vatinc'] == "yes") {
        $chy = "checked=yes";
        $chn = "";
        $chnv = "";
    } else {
        if ($pur['vatinc'] == 'novat') {
            $chy = "";
            $chn = "";
            $chnv = "checked=yes";
        } else {
            $chy = "";
            $chn = "checked=yes";
            $chnv = "";
        }
    }
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # Select all products
    $products = "\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>ITEM NUMBER</th>\n\t\t\t\t\t\t\t<th>VAT CODE</th>\n\t\t\t\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t\t\t\t<th>QTY</th>\n\t\t\t\t\t\t\t<th>UNIT PRICE</th>\n\t\t\t\t\t\t\t<th>DELIVERY DATE</th>\n\t\t\t\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t\t\t\t<th>VAT</th>\n\t\t\t\t\t\t\t<th>Remove</th>\n\t\t\t\t\t\t<tr>";
    # get selected stock in this Order
    db_connect();
    $sql = "SELECT * FROM nons_pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # keep track of selected stock amounts
        $amts[$i] = $stkd['amt'];
        $i++;
        list($d_year, $d_month, $d_day) = explode("-", $stkd['ddate']);
        $stkd['amt'] = round($stkd['amt'], 2);
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
        $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($stkd['vatcode'] == $vd['id']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $Vatcodes .= "</select>";
        $stkd['amt'] = sprint($stkd['amt']);
        # put in product
        $products .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value='{$stkd['cod']}'></td>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='20' name='des[]' value='{$stkd['des']}'></td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'></td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'></td>\n\t\t\t\t\t\t\t<td align='center'>" . mkDateSelecta("d", $key, $d_year, $d_month, $d_day) . "</td>\n\t\t\t\t\t\t\t<td nowrap><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t\t\t<td><input type='text' name='vat[]' size='9' value='{$stkd['svat']}'></td>\n\t\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$key}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t\t\t\t</tr>";
        $key++;
    }
    # Look above(remprod keys)
    $keyy = $key;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
        $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($vd['del'] == "Yes") {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $Vatcodes .= "</select>";
        # add one
        $products .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value=''></td>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='20' name='des[]' value=''></td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='1'></td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]'></td>\n\t\t\t\t\t\t\t<td align='center'>" . mkDateSelecta("d", 0) . "</td>\n\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='novat[]' value='1'></td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t</tr>";
    }
    /* -- start Listeners -- */
    if (isset($diffwhBtn)) {
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes ORDER BY code";
        $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
        $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
        while ($vd = pg_fetch_array($Ri)) {
            if ($vd['del'] == "Yes") {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
        }
        $Vatcodes .= "</select>";
        $products .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='10' name='cod[]' value=''></td>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='20' name='des[]' value=''></td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='3' name='qtys[]' value='1'></td>\n\t\t\t\t\t\t\t<td align='center'><input type='text' size='8' name='unitcost[]'></td>\n\t\t\t\t\t\t\t<td align='center'>" . mkDateSelecta("d", $key) . "</td>\n\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='novat[{$key}]' value='1'></td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t</tr>";
        $key++;
    }
    /* -- End Listeners -- */
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = $pur['subtot'];
    # Get Total
    $TOTAL = sprint($pur['total']);
    # Get vat
    $VAT = sprint($pur['vat']);
    /* --- End Some calculations --- */
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h3>New Non-Stock Purchase</h3>\n\t\t\t\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t\t\t\t<input type='hidden' name='purid' value='{$purid}'>\n\t\t\t\t\t\t<input type='hidden' name='shipchrg' value='0'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t\t\t \t<tr>\n\t\t\t\t\t \t\t<td valign='top'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th colspan='2'> Supplier Details </th>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Supplier</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><input type='text' name='supplier' value='{$pur['supplier']}'></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td valign='top'>Supplier Address</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><textarea name='supaddr' cols='18' rows='3'>{$pur['supaddr']}</textarea></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td valign='top' align='right'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th colspan='2'> Non-Stock Purchase Details </th>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Linked Purchase No.</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['spurnum']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Non-Stock Purchase No.</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$pur['purnum']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Order No.</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='ordernum' value='{$ordernum}'></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("lnpur", $lnpur_year, $lnpur_month, $lnpur_day) . "</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' size='7' name='vatinc' value='yes' {$chy}> No<input type='radio' size='7' name='vatinc' value='no' {$chn}></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t\t\t\t<th width='25%'>Remarks</th>\n\t\t\t\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$error}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='nons-purchase-view.php'>View Non-Stock Purchases</a></td>\n\t\t\t\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='4' align='center' valign='top'><textarea name='remarks' rows='4' cols='20'>{$pur['remarks']}</textarea></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td align='right'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='subtot' value='{$SUBTOT}'>{$SUBTOT}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<td>VAT {$vat14}</td>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " {$pur['vat']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t\t\t\t<td align='right'>" . CUR . " <input type='hidden' name='total' value='{$TOTAL}'>{$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='right'><input type='button' value='&laquo Back' onClick='javascript:history.back()'> | <input name='diffwhBtn' type='submit' value='Add Item'> |</td>\n\t\t\t\t\t\t\t<td><input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t</form>\n\t\t\t\t\t</center>";
    return $details;
}
function details($_POST, $error = "")
{
    # get vars
    extract($_POST);
    # Redirect, vars?
    if (isset($cash) && $cash == 'yes') {
        header("Location: purchase-new-cash.php?deptid={$deptid}");
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($purid)) {
        $v->isOk($purid, "num", 1, 20, "Invalid Order number.");
    } else {
        $v->isOk($deptid, "num", 1, 20, "Invalid department number.");
        $v->isOk($letters, "string", 0, 5, "Invalid First 3 Letters.");
    }
    # display errors, if any
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        $confirm .= "{$error}<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (!isset($purid)) {
        $purid = create_dummy($deptid);
    }
    $supprice = 0;
    # Get Order 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 class='err'>Purchase Not Found</li>";
    }
    $pur = pg_fetch_array($purRslt);
    $deptid = $pur['deptid'];
    # check if Order has been printed
    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;
    }
    if (!isset($ordernum)) {
        $ordernum = '';
    }
    if (!isset($supinv)) {
        $supinv = '';
    }
    # get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$pur['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<li class='err'>Department not Found.</li>";
    } else {
        $dept = pg_fetch_array($deptRslt);
    }
    # Get selected customer info
    db_connect();
    $sql = "SELECT * FROM suppliers WHERE supid = '{$pur['supid']}' AND div = '" . USER_DIV . "'";
    $supRslt = db_exec($sql) or errDie("Unable to view Supplier");
    if (pg_numrows($supRslt) < 1) {
        db_connect();
        if ($inv['deptid'] == 0) {
            $searchdept = "";
        } else {
            $searchdept = "deptid = '{$deptid}' AND ";
        }
        # Query server for supplier info
        $sql = "SELECT * FROM suppliers WHERE {$searchdept} location != 'int' AND lower(supname) LIKE lower('{$letters}%') AND div = '" . USER_DIV . "' ORDER BY supname ASC";
        $supRslt = db_exec($sql) or errDie("Unable to view suppliers");
        if (pg_numrows($supRslt) < 1) {
            $err = "<li class='err'>No Supplier names starting with <b>{$letters}</b> in database.</li>";
            return view_err($_POST, $err);
        } else {
            $suppliers = "<select name='supid' onChange='javascript:document.form.submit();'>";
            $suppliers .= "<option value='-S' selected>Select Supplier</option>";
            while ($sup = pg_fetch_array($supRslt)) {
                $suppliers .= "<option value='{$sup['supid']}'>{$sup['supname']}</option>";
            }
            $suppliers .= "</select>";
        }
        # take care of the uset vars
        $supaddr = "";
        $accno = "";
    } else {
        db_connect();
        # Query server for supplier info
        $sql = "SELECT * FROM suppliers WHERE deptid = '{$deptid}' AND location != 'int' AND lower(supname) LIKE lower('{$letters}%') AND div = '" . USER_DIV . "' ORDER BY supname ASC";
        $supRslt = db_exec($sql) or errDie("Unable to view suppliers");
        if (pg_numrows($supRslt) < 1) {
            $err = "<li class='err'>No Supplier names starting with <b>{$letters}</b> in database.</li>";
            return view_err($_POST, $err);
        } else {
            $suppliers = "<select name='supid' onChange='javascript:document.form.submit();'>";
            $supaddr = "";
            $accno = "";
            while ($sup = pg_fetch_array($supRslt)) {
                if ($sup['supid'] == $pur['supid']) {
                    $sel = "selected";
                    $supaddr = $sup['supaddr'];
                    $accno = $sup['supno'];
                    $supprice = $sup['listid'];
                } else {
                    $sel = "";
                }
                $suppliers .= "<option value='{$sup['supid']}' {$sel}>{$sup['supname']}</option>";
            }
            $suppliers .= "</select>";
        }
        $get_codes = "SELECT * FROM suppstock WHERE suppid = '{$pur['supid']}' ORDER BY stkid";
        $run_codes = db_exec($get_codes) or errDie("Unable to get supplier stock code information");
        if (pg_numrows($run_codes) > 0) {
            while ($codarr = pg_fetch_array($run_codes)) {
                if (strlen($codarr['stkcod']) > 0) {
                    $stockcodes[$codarr['stkid']]['stkcod'] = $codarr['stkcod'];
                }
                if (strlen($codarr['stkdes']) > 0) {
                    $stockcodes[$codarr['stkid']]['stkdes'] = $codarr['stkdes'];
                }
            }
        }
    }
    /* --- Start Drop Downs --- */
    # Select warehouse
    db_conn("exten");
    $whs = "<select name='whidss[]' onChange='javascript:document.form.submit();'>";
    $sql = "SELECT * FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
    $whRslt = db_exec($sql);
    if (pg_numrows($whRslt) < 1) {
        return "<li class='err'> No Stores found in Cubit.</li>";
    } else {
        $whs .= "<option value='-S' disabled selected>Select Store</option>";
        while ($wh = pg_fetch_array($whRslt)) {
            $whs .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
        }
    }
    $whs .= "</select>";
    # days drop downs
    $days = array("0" => "0", "7" => "7", "14" => "14", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $pur['terms']);
    # format date
    list($pur_year, $pur_month, $pur_day) = explode("-", $pur['pdate']);
    # keep the charge vat option stable
    if ($pur['vatinc'] == "yes") {
        $chy = "checked='yes'";
        $chn = "";
        $chv = "";
    } elseif ($pur['vatinc'] == "no") {
        $chy = "";
        $chn = "checked='yes'";
        $chv = "";
    } else {
        $chy = "";
        $chn = "";
        $chv = "checked='yes'";
    }
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # select all products
    $products = "\n\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t<tr>\n\t\t\t\t<th>STORE</th>\n\t\t\t\t<th>ITEM NUMBER</th>\n\t\t\t\t<th>VAT CODE</th>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<th>QTY</th>\n\t\t\t\t<th>UNIT PER PACK</th>\n\t\t\t\t<th>PRICE PER PACK</th>\n\t\t\t\t<th>UNITS</th>\n\t\t\t\t<th>PRICE PER UNIT</th>\n\t\t\t\t<th>DISCOUNT</th>\n\t\t\t\t<th>DELIVERY DATE</th>\n\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t<th>VAT</th>\n\t\t\t\t<th>REM</th>\n\t\t\t</tr>";
    # get selected stock in this purchase
    db_connect();
    $sql = "SELECT * FROM pur_items  WHERE purid = '{$purid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] != 0) {
            if (!isset($stk['exvat'])) {
                $stk['exvat'] = "";
            }
            # keep track of selected stock amounts
            $amts[$i] = $stkd['amt'];
            $i++;
            db_conn('core');
            $Sl = "SELECT * FROM accounts WHERE accid='{$stkd['account']}'";
            $Rk = db_exec($Sl);
            $ad = pg_fetch_array($Rk);
            list($syear, $smonth, $sday) = explode("-", $stkd['ddate']);
            $stkd['amt'] = sprint($stkd['amt']);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                //				return "Please select the vatcode for all your stock.";
                $_POST['done'] = "";
                return details($_POST, "<li class='err'>Please select the vatcode for all your items.</li>");
            }
            $vd = pg_fetch_array($Ri);
            if ($pur['vatinc'] == 'no' && $stk['exvat'] != 'yes' && $vd['zero'] != "Yes") {
                $vunitamt = sprint($stkd['unitcost'] + $stkd['svat'] / $stkd['qty']);
            } else {
                $vunitamt = sprint($stkd['unitcost']);
            }
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes ORDER BY code";
            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
            $Vatcodes = "\n\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t<option value='0'>Select</option>";
            while ($vd = pg_fetch_array($Ri)) {
                if ($stkd['vatcode'] == $vd['id']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
            }
            $Vatcodes .= "</select>";
            $tip = "&nbsp;&nbsp;&nbsp;";
            if (isset($vatc[$key])) {
                $tip = "<font color='red'>#</font>";
                $error = "<div class='err'> {$tip}&nbsp;&nbsp;=&nbsp;&nbsp; VAT amount is different from amount calculated by cubit. To allow cubit to recalculate the vat amount, please delete the vat amount from the input box.";
            }
            if ($stkd['udiscount'] > 0) {
                $discps = round($stkd['udiscount'] / 100 * $stkd['unitcost'], 2);
            }
            $stkd['amt'] = sprint($stkd['qty'] * ($stkd['unitcost'] - $discps));
            # put in product
            $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='hidden' name='whids[]' value='0'></td>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<input type='hidden' name='stkids[]' value='{$stkd['stkid']}'>\n\t\t\t\t\t\t{$ad['accname']}\n\t\t\t\t\t\t<input type='hidden' name='accounts[]' value='{$stkd['account']}'>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td><input type='text' name='descriptions[]' value='{$stkd['description']}'></td>\n\t\t\t\t\t<td><input type='text' size='4' name='qtys[]' value='{$stkd['qpack']}'></td>\n\t\t\t\t\t<td><input type='text' size='5' name='upack[]' value='{$stkd['upack']}'></td>\n\t\t\t\t\t<td><input type='text' size='8' name='ppack[]' value='" . sprint($stkd['ppack']) . "'></td>\n\t\t\t\t\t<td>" . sprint3($stkd['qty']) . "</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$vunitamt}</td>\n\t\t\t\t\t<td><input type='text' size='5' name='udiscount[]' value='{$stkd['udiscount']}'></td>\n\t\t\t\t\t<td>" . mkDateSelecta("d", $key, $syear, $smonth, $sday) . "</td>\n\t\t\t\t\t<td align='right' nowrap><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t<td>{$tip} <input type='text' name='svat[]' size='7' value='{$stkd['svat']}'></td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$key}'></td>\n\t\t\t\t</tr>";
            $key++;
        } else {
            # keep track of selected stock amounts
            $amts[$i] = $stkd['amt'];
            $i++;
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            list($syear, $smonth, $sday) = explode("-", $stkd['ddate']);
            $stkd['amt'] = sprint($stkd['amt']);
            db_conn('cubit');
            $Sl = "SELECT * FROM vatcodes ORDER BY code";
            $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
            $Vatcodes = "\n\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t<option value='0'>Select</option>";
            while ($vd = pg_fetch_array($Ri)) {
                if ($stkd['vatcode'] == $vd['id']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
            }
            $Vatcodes .= "</select>";
            if ($pur['vatinc'] == 'no' && $stk['exvat'] != 'yes' && $vd['zero'] != "Yes") {
                $vunitamt = sprint($stkd['unitcost'] + $stkd['svat'] / $stkd['qty']);
            } else {
                $vunitamt = sprint($stkd['unitcost']);
            }
            $tip = "&nbsp;&nbsp;&nbsp;";
            if (isset($vatc[$key])) {
                $tip = "<font color='red'>#</font>";
                $error = "<div class='err'> {$tip}&nbsp;&nbsp;=&nbsp;&nbsp; VAT amount is different from amount calculated by cubit. To allow cubit to recalculate the vat amount, please delete the vat amount from the input box.";
            }
            $discps = 0;
            if ($stkd['udiscount'] > 0) {
                $discps = round($stkd['udiscount'] / 100 * $stkd['unitcost'], 2);
            }
            $stkd['amt'] = sprint($stkd['qty'] * ($stkd['unitcost'] - $discps));
            if (isset($stockcodes[$stk['stkid']]['stkcod'])) {
                $stk['stkcod'] = $stockcodes[$stk['stkid']]['stkcod'];
            }
            if (isset($stockcodes[$stk['stkid']]['stkdes'])) {
                $stk['stkdes'] = $stockcodes[$stk['stkid']]['stkdes'];
            }
            # put in product
            $products .= "\n\t\t\t\t<input type='hidden' name='accounts[]' value='0'>\n\t\t\t\t<input type='hidden' name='descriptions[]' value=''>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><input type='hidden' name='whids[]' value='{$stkd['whid']}'>{$wh['whname']}</td>\n\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t<td><input type='text' size='4' name='qtys[]' value='{$stkd['qpack']}'></td>\n\t\t\t\t\t<td><input type='text' size='5' name='upack[]' value='{$stkd['upack']}'></td>\n\t\t\t\t\t<td><input type='text' size='8' name='ppack[]' value='" . sprint($stkd['ppack']) . "'></td>\n\t\t\t\t\t<td>" . sprint3($stkd['qty']) . "</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$vunitamt}</td>\n\t\t\t\t\t<td><input type='text' size='5' name='udiscount[]' value='{$stkd['udiscount']}'></td>\n\t\t\t\t\t<td>" . mkDateSelecta("d", $key, $syear, $smonth, $sday) . "</td>\n\t\t\t\t\t<td align='right' nowrap><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t<td>{$tip} <input type='text' name='svat[]' size='7' value='{$stkd['svat']}'></td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$key}'></td>\n\t\t\t\t</tr>";
            $key++;
        }
    }
    // select using selection
    if (!isset($sel_frm)) {
        $sel_frm = "stkcod";
    }
    # Look above(remprod keys)
    $keyy = $key;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    }
    # check if stock warehouse was selected
    if (isset($whidss)) {
        foreach ($whidss as $key => $whid) {
            if (isset($stkidss[$key]) && $stkidss[$key] != "-S") {
                # skip if not selected
                if ($whid == "-S") {
                    continue;
                }
                # Get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                $Sl = "SELECT * FROM splist_prices WHERE listid='{$supprice}' AND div='" . USER_DIV . "' AND stkid='{$stkidss[$key]}'";
                $Ry = db_exec($Sl) or errDie("Unable to get price.");
                $listdata = pg_fetch_array($Ry);
                $newprice = $listdata['price'];
                # Get selected stock in this warehouse
                db_connect();
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkidss[$key]}' AND div = '" . USER_DIV . "' ORDER BY stkcod ASC";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                # Calculate amount
                $amt[$key] = sprint($qtyss[$key] * 0);
                $newprice += 0;
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "\n\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t<option value='0'>Select</option>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($stk['vatcode'] == $vd['id']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                $discps = 0;
                if ($udiscount[$key] > 0) {
                    $discps = round($udiscount[$key] / 100 * $newprice, 2);
                }
                $amt[$key] = sprint($qtyss[$key] * ($newprice - $discps));
                if (isset($stockcodes[$stk['stkid']]['stkcod'])) {
                    $stk['stkcod'] = $stockcodes[$stk['stkid']]['stkcod'];
                }
                if (isset($stockcodes[$stk['stkid']]['stkdes'])) {
                    $stk['stkdes'] = $stockcodes[$stk['stkid']]['stkdes'];
                }
                # Put in selected warehouse and stock
                $products .= "\n\t\t\t\t\t<input type='hidden' name='accounts[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='descriptions[]' value=''>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' name='whids[]' value='{$whid}'>{$wh['whname']}</td>\n\t\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stk['stkid']}'><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t\t<td><input type='text' size='4' name='qtys[]' value='{$qtyss[$key]}'></td>\n\t\t\t\t\t\t<td><input type='hidden' name='novat[{$keyy}]' value='1'><input type='text' size='5' name='upack[]' value='{$stk['rate']}'></td>\n\t\t\t\t\t\t<td><input type='text' size='8' name='ppack[]' value='" . sprint($newprice) . "'></td>\n\t\t\t\t\t\t<td>{$stk['rate']}</td>\n\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " 0.00</td>\n\t\t\t\t\t\t<td><input type='text' size='5' name='udiscount[]' value='" . sprint($udiscounts[$key]) . "'></td>\n\t\t\t\t\t\t<td>" . mkDateSelecta("d", $keyy, $d_year[$keyy], $d_month[$keyy], $d_day[$keyy]) . "</td>\n\t\t\t\t\t\t<td align='right' nowrap><input type='hidden' name='amt[]' value='{$amt[$key]}'> " . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
            } elseif (isset($accountss[$key]) && $accountss[$key] != "0") {
                # skip if not selected
                if ($whid == "-S") {
                    continue;
                }
                db_conn('core');
                $Sl = "SELECT * FROM accounts WHERE accid='{$accountss[$key]}'";
                $Ri = db_exec($Sl) or errDie("Unable to get account data.");
                if (pg_num_rows($Ri) < 1) {
                    return "invalid.";
                }
                $ad = pg_fetch_array($Ri);
                # Calculate amount
                $amt[$key] = sprint($qtyss[$keyy] * 0);
                //$newprice+=0;
                db_conn('cubit');
                $Sl = "SELECT * FROM vatcodes ORDER BY code";
                $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                $Vatcodes = "\n\t\t\t\t\t<select name='vatcodes[]'>\n\t\t\t\t\t\t<option value='0'>Select</option>";
                while ($vd = pg_fetch_array($Ri)) {
                    if ($vatcodess[$keyy] == $vd['id']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                }
                $Vatcodes .= "</select>";
                #we want to open the cost center popup here and now if this is and expense ....
                /*				$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.
                					<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);*/
                /*				if(cc_TranTypeAcc($accountss[$key], $banklnk['accnum']) != false){
                					$cc_trantype = cc_TranTypeAcc($accountss[$key], $banklnk['accnum']);
                					$date = date("d-m-Y");
                					$amount = $ppack[$key] * $qtyss[$key];
                					$cc = "<script> CostCenter('$cc_trantype', 'Bank Transaction', '$date', '$descriptionss[$key]', '$amount', ''); </script>";
                				}else{
                					$cc = "";
                				}*/
                # THIS PRODUCT DISPLAYS DIRECTLY AFTER A NON STOCK ACCOUNT HAS BEEN SUBMITTED
                # Put in selected warehouse and stock
                $discps = 0;
                if ($udiscount[$key] > 0) {
                    $discps = round($udiscount[$key] / 100 * $newprice, 2);
                }
                $amt[$key] = sprint($qtyss[$key] * ($newprice - $discps));
                $products .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='2'>\n\t\t\t\t\t\t\t<input type='hidden' name='accounts[]' value='{$accountss[$key]}'>\n\t\t\t\t\t\t\t<input type='hidden' name='whids[]' value='0'>{$ad['accname']}\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='0'>{$Vatcodes}</td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$descriptionss[$keyy]}'></td>\n\t\t\t\t\t\t<td><input type='text' size='4' name='qtys[]' value='{$qtyss[$keyy]}'></td>\n\t\t\t\t\t\t<td><input type='hidden' name='novat[{$keyy}]' value='1'><input type='text' size='5' name='upack[]' value='{$upack[$key]}'></td>\n\t\t\t\t\t\t<td><input type='text' size='8' name='ppack[{$keyy}]' value='" . sprint($ppack[$keyy]) . "'></td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " 0.00</td>\n\t\t\t\t\t\t<td><input type='text' size='5' name='udiscount[{$keyy}]' value='" . sprint($udiscount[$keyy]) . "'></td>\n\t\t\t\t\t\t<td>" . mkDateSelecta("d", $keyy, $d_year[$key], $d_month[$key], $d_day[$key]) . "</td>\n\t\t\t\t\t\t<td align='right' nowrap><input type='hidden' name='amt[]' value='{$amt[$key]}'> " . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
            } else {
                # Skip if not selected
                if ($whid == "-S") {
                    continue;
                }
                if (!isset($addnon)) {
                    if (isset($filter_store) and $filter_store != "0") {
                        # Get warehouse name
                        db_conn("exten");
                        $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
                        $whRslt = db_exec($sql);
                        $wh = pg_fetch_array($whRslt);
                    }
                    if (isset($des) and $des != "") {
                        $len = strlen($des);
                        if ($des == "Show All") {
                            $Wh = "";
                            $des = "";
                        } else {
                            $Wh = "AND (lower(stkdes) LIKE lower('%{$des}%')) OR (lower(stkcod) LIKE lower('%{$des}%'))";
                        }
                    } else {
                        $Wh = "AND FALSE";
                        $des = "";
                    }
                    $check_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
                    if (isset($check_setting) and $check_setting == "yes") {
                        if (isset($filter_class) and $filter_class != "0") {
                            $Wh .= " AND prdcls = '{$filter_class}'";
                        }
                        if (isset($filter_cat) and $filter_cat != "0") {
                            $Wh .= " AND catid = '{$filter_cat}'";
                        }
                    }
                    if (isset($filter_store) and $filter_store != "0") {
                        $Wh .= " AND whid = '{$filter_store}'";
                    }
                    # Get stock on this warehouse
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE div = '" . USER_DIV . "' {$Wh} ORDER BY stkcod ASC LIMIT 200";
                    $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
                    if (pg_numrows($stkRslt) < 1) {
                        //$error .= "<li class='err'>There are no stock items in the selected warehouse.";
                        continue;
                    }
                    if ($sel_frm == "stkcod") {
                        $stks = "<select name='stkidss[]' style='width:200px' onChange='javascript:document.form.submit();'>";
                        $stks .= "<option value='-S' disabled selected>Select Number</option>";
                        $count = 0;
                        while ($stk = pg_fetch_array($stkRslt)) {
                            if (isset($stockcodes[$stk['stkid']]['stkcod'])) {
                                $stk['stkcod'] = $stockcodes[$stk['stkid']]['stkcod'];
                            }
                            if (isset($stockcodes[$stkd['stkid']]['stkdes'])) {
                                $stk['stkdes'] = $stockcodes[$stk['stkid']]['stkdes'];
                            }
                            $stks .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
                        }
                        $stks .= "</select> ";
                    } else {
                        $stks = "<select name='stkidss[]' style='width:200px' onChange='javascript:document.form.submit();'>";
                        $stks .= "<option value='-S' disabled selected>Select Description</option>";
                        $count = 0;
                        while ($stk = pg_fetch_array($stkRslt)) {
                            if (isset($stockcodes[$stk['stkid']]['stkcod'])) {
                                $stk['stkcod'] = $stockcodes[$stk['stkid']]['stkcod'];
                            }
                            if (isset($stockcodes[$stkd['stkid']]['stkdes'])) {
                                $stk['stkdes'] = $stockcodes[$stk['stkid']]['stkdes'];
                            }
                            $stks .= "<option value='{$stk['stkid']}'>{$stk['stkdes']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
                        }
                        $stks .= "</select> ";
                    }
                    # Put in drop down and warehouse
                    $products .= "\n\t\t\t\t\t\t<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>\n\t\t\t\t\t\t<input type='hidden' name='udiscounts[]' value='0.00'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td><input type='hidden' name='whidss[]' value='{$filter_store}'></td>\n\t\t\t\t\t\t\t<td>{$stks}</td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td><input type='text' size='4' name='qtyss[]'  value='1'></td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>" . mkDateSelecta("d", $keyy, $d_year[$keyy], $d_month[$keyy], $d_day[$keyy]) . "</td>\n\t\t\t\t\t\t\t<td align='right' nowrap><input type='hidden' name='amts[]' value='0.00'>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>";
                } else {
                    $Accounts = "\n\t\t\t\t\t\t<select name='accountss[]'>\n\t\t\t\t\t\t\t<option value='0'>Select Account</option>";
                    $useaccdrop = getCSetting("USE_NON_PURCHASES_ACCOUNTS");
                    if (isset($useaccdrop) and $useaccdrop == "yes") {
                        db_connect();
                        $acc_sql = "SELECT * FROM non_purchases_account_list ORDER BY accname";
                        $run_acc = db_exec($acc_sql) or errDie("Unable to get account information.");
                        if (pg_numrows($run_acc) > 0) {
                            while ($acc = pg_fetch_array($run_acc)) {
                                $Accounts .= "<option value='{$acc['accid']}'>{$acc['accname']}</option>";
                            }
                            $Accounts .= "</select>";
                        }
                    } else {
                        db_conn('core');
                        $Sl = "SELECT accid,topacc,accnum,accname FROM accounts ORDER BY accname";
                        $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                        // WHERE acctype='I'
                        while ($ad = pg_fetch_array($Ri)) {
                            if (isDisabled($ad['accid'])) {
                                continue;
                            }
                            $Accounts .= "<option value='{$ad['accid']}'>{$ad['accname']}</option>";
                        }
                        $Accounts .= "</select>";
                    }
                    db_conn('cubit');
                    $Sl = "SELECT * FROM vatcodes ORDER BY code";
                    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
                    $Vatcodes = "\n\t\t\t\t\t\t<select name='vatcodess[{$keyy}]'>\n\t\t\t\t\t\t\t<option value='0'>Select</option>";
                    while ($vd = pg_fetch_array($Ri)) {
                        if ($vd['del'] == "Yes") {
                            $sel = "selected";
                        } else {
                            $sel = "";
                        }
                        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                    }
                    $Vatcodes .= "</select>";
                    # Put in drop down and warehouse
                    $products .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan='2'><input type='hidden' name='whidss[]' value='0'>{$Accounts}</td>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[{$keyy}]' value=''></td>\n\t\t\t\t\t\t\t<td><input type='text' size='4' name='qtyss[{$keyy}]' value='1'></td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='upack[{$keyy}]' value='1'></td>\n\t\t\t\t\t\t\t<td><input type='text' size='8' name='ppack[{$keyy}]' value=''></td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='udiscount[{$keyy}]' value='0.00'></td>\n\t\t\t\t\t\t\t<td>" . mkDateSelecta("d", $keyy, $d_year[$key], $d_month[$key], $d_day[$key]) . "</td>\n\t\t\t\t\t\t\t<td align='right' nowrap><input type='hidden' name='amts[{$keyy}]' value='0.00'>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t</tr>";
                }
            }
            $keyy++;
        }
    } else {
        $ckey = $keyy;
        # take todays date
        list($year, $month, $day) = explode("-", $pur['pdate']);
        if (isset($filter_store) and $filter_store != "0") {
            # get selected warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$filter_store}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
        }
        if (isset($des) and $des != "") {
            $len = strlen($des);
            if ($des == "Show All") {
                $Wh = "";
                $des = "";
            } else {
                $Wh = "AND (lower(stkdes) LIKE lower('%{$des}%')) OR (lower(stkcod) LIKE lower('%{$des}%'))";
            }
        } else {
            $Wh = "AND FALSE";
            $des = "";
        }
        $check_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
        if (isset($check_setting) and $check_setting == "yes") {
            if (isset($filter_class) and $filter_class != "0") {
                $Wh .= " AND prdcls = '{$filter_class}'";
            }
            if (isset($filter_cat) and $filter_cat != "0") {
                $Wh .= " AND catid = '{$filter_cat}'";
            }
        }
        if (isset($filter_store) and $filter_store != "0") {
            $Wh .= " AND whid = '{$filter_store}'";
        }
        # get stock on this warehouse
        db_connect();
        $sql = "SELECT * FROM stock WHERE div = '" . USER_DIV . "' {$Wh} ORDER BY stkcod ASC LIMIT 200";
        $stkRslt = db_exec($sql) or errDie("Unable to retrieve stocks from database.");
        if (pg_numrows($stkRslt) < 1) {
            if (!isset($err)) {
                $err = "";
            }
            $err .= "<li>There are no stock items in the selected warehouse.</li>";
        }
        if ($sel_frm == "stkcod") {
            $stks = "<select name='stkidss[]' style='width:200px' onChange='javascript:document.form.submit();'>";
            $stks .= "<option value='-S' disabled selected>Select Number</option>";
            $count = 0;
            while ($stk = pg_fetch_array($stkRslt)) {
                if (isset($stockcodes[$stk['stkid']]['stkcod'])) {
                    $stk['stkcod'] = $stockcodes[$stk['stkid']]['stkcod'];
                }
                if (isset($stockcodes[$stkd['stkid']]['stkdes'])) {
                    $stk['stkdes'] = $stockcodes[$stk['stkid']]['stkdes'];
                }
                $stks .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
            }
            $stks .= "</select> ";
        } else {
            $stks = "<select name='stkidss[]' style='width:200px' onChange='javascript:document.form.submit();'>";
            $stks .= "<option value='-S' disabled selected>Select Description</option>";
            $count = 0;
            while ($stk = pg_fetch_array($stkRslt)) {
                if (isset($stockcodes[$stk['stkid']]['stkcod'])) {
                    $stk['stkcod'] = $stockcodes[$stk['stkid']]['stkcod'];
                }
                if (isset($stockcodes[$stkd['stkid']]['stkdes'])) {
                    $stk['stkdes'] = $stockcodes[$stk['stkid']]['stkdes'];
                }
                $stks .= "<option value='{$stk['stkid']}'>{$stk['stkdes']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
            }
            $stks .= "</select> ";
        }
        $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>\n\t\t\t\t\t<input type='hidden' name='vatcodess[]' value=''>\n\t\t\t\t\t<input type='hidden' name='udiscounts[]' value='0.00'>\n\t\t\t\t\t<td><input type='hidden' name='whidss[]' value='{$filter_store}'></td>\n\t\t\t\t\t<td>{$stks}</td>\n\t\t\t\t\t<td> </td>\n\t\t\t\t\t<td> </td>\n\t\t\t\t\t<td><input type='text' size='4' name='qtyss[]' value='1'></td>\n\t\t\t\t\t<td> </td>\n\t\t\t\t\t<td> </td>\n\t\t\t\t\t<td> </td>\n\t\t\t\t\t<td> </td>\n\t\t\t\t\t<td> </td>\n\t\t\t\t\t<td>" . mkDateSelecta("d", $ckey, $year, $month, $day) . "</td>\n\t\t\t\t\t<td nowrap>" . CUR . " 0.00</td>\n\t\t\t\t\t<td> </td>\n\t\t\t\t\t<td></td>\n\t\t\t\t</tr>";
        $ckey++;
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Get subtotal
    $SUBTOT = sprint($pur['subtot']);
    # Get Total
    $TOTAL = sprint($pur['total']);
    # Get vat
    $VAT = sprint($pur['vat']);
    # Shipping Charges
    $pur['shipchrg'] = sprint($pur['shipchrg']);
    $pur['delvat'] += 0;
    if ($pur['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $pur['delvat'] = $vd['id'];
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM vatcodes ORDER BY code";
    $Ri = db_exec($Sl) or errDie("Unable to get vat codes");
    $Vatcodes = "\n\t\t<select name='delvat'>\n\t\t\t<option value='0'>Select</option>";
    while ($vd = pg_fetch_array($Ri)) {
        if ($vd['id'] == $pur['delvat']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $Vatcodes .= "</select>";
    /* --- End Some calculations --- */
    $ex = "";
    if (strlen($supinv)) {
        db_conn('cubit');
        $Sl = "SELECT purnum,pdate FROM purchases WHERE supid='{$supid}' AND supinv='{$supinv}' AND purid!='{$purid}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) > 0) {
            $pd = pg_fetch_array($Ri);
            $ex .= "<li class='err'>Purchase {$pd['purnum']} on {$pd['pdate']} has the same supplier invoice number.</li>";
        }
        for ($i = 1; $i < 13; $i++) {
            db_conn($i);
            $Sl = "SELECT purnum,pdate FROM purchases WHERE supid='{$supid}' AND supinv='{$supinv}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) > 0) {
                $pd = pg_fetch_array($Ri);
                $ex .= "<li class='err'>Purchase {$pd['purnum']} on {$pd['pdate']} has same the supplier invoice number.</li>";
            }
        }
        db_conn('cubit');
        $Sl = "SELECT purnum,pdate FROM nons_purchases WHERE supplier='{$supid}' AND supinv='{$supinv}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) > 0) {
            $pd = pg_fetch_array($Ri);
            $ex .= "<li class='err'>Non Stock Purchase {$pd['purnum']} on {$pd['pdate']} has the same supplier invoice number.</li>";
        }
        for ($i = 1; $i < 13; $i++) {
            db_conn($i);
            $Sl = "SELECT purnum,pdate FROM nons_purchases WHERE supplier='{$supid}' AND supinv='{$supinv}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) > 0) {
                $pd = pg_fetch_array($Ri);
                $ex .= "<li class='err'>Non Stock Purchase {$pd['purnum']} on {$pd['pdate']} has same the supplier invoice number.</li>";
            }
        }
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    // Which display method was selected
    if (isset($sel_frm) && $sel_frm == "stkdes") {
        $sel_frm_cod = "";
        $sel_frm_des = "checked";
    } else {
        $sel_frm_cod = "checked";
        $sel_frm_des = "";
    }
    if (isset($addnon) or isset($upBtn) or isset($doneBtn) or isset($invoice) or isset($donePrnt)) {
        $jump_bot = "\n\t\t\t<script>\n\t\t\t\twindow.location.hash='bottom';\n\t\t\t</script>";
    } else {
        $jump_bot = "";
    }
    $optional_filter_setting = getCSetting("OPTIONAL_STOCK_FILTERS");
    if (isset($optional_filter_setting) and $optional_filter_setting == "yes") {
        db_connect();
        $catsql = "SELECT catid, cat, catcod FROM stockcat WHERE div = '" . USER_DIV . "' ORDER BY cat ASC";
        $catRslt = db_exec($catsql);
        if (pg_numrows($catRslt) < 1) {
            $cat_drop = "<input type='hidden' name='filter_cat' value='0'>";
        } else {
            $cat_drop = "<select name='filter_cat'>";
            $cat_drop .= "<option value='0'>All Categories</option>";
            while ($cat = pg_fetch_array($catRslt)) {
                if (isset($filter_cat) and $filter_cat == $cat['catid']) {
                    $cat_drop .= "<option value='{$cat['catid']}' selected>({$cat['catcod']}) {$cat['cat']}</option>";
                } else {
                    $cat_drop .= "<option value='{$cat['catid']}'>({$cat['catcod']}) {$cat['cat']}</option>";
                }
            }
            $cat_drop .= "</select>";
        }
        # Select classification
        $classsql = "SELECT * FROM stockclass WHERE div = '" . USER_DIV . "' ORDER BY classname ASC";
        $clasRslt = db_exec($classsql);
        if (pg_numrows($clasRslt) < 1) {
            $class_drop = "<input type='hidden' name='filter_class' value='0'>";
        } else {
            $class_drop = "<select name='filter_class' style='width: 167'>";
            $class_drop .= "<option value='0'>All Classifications</option>";
            while ($clas = pg_fetch_array($clasRslt)) {
                if (isset($filter_class) and $filter_class == $clas['clasid']) {
                    $class_drop .= "<option value='{$clas['clasid']}' selected>{$clas['classname']}</option>";
                } else {
                    $class_drop .= "<option value='{$clas['clasid']}'>{$clas['classname']}</option>";
                }
            }
            $class_drop .= "</select>";
        }
        $display_optional_filters = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Select Category</td>\n\t\t\t\t<td>{$cat_drop}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Select Classification</td>\n\t\t\t\t<td>{$class_drop}</td>\n\t\t\t</tr>";
    }
    db_conn("exten");
    $sql = "SELECT whid, whname, whno FROM warehouses WHERE div = '" . USER_DIV . "' ORDER BY whname ASC";
    $whRslt = db_exec($sql);
    if (pg_numrows($whRslt) < 1) {
        $store_drop = "<input type='hidden' name='filter_store' value='0'>";
    } else {
        if (!isset($filter_store)) {
            # check if setting exists
            db_connect();
            $sql = "SELECT value FROM set WHERE label = 'DEF_WH' AND div = '" . USER_DIV . "'";
            $Rslt = db_exec($sql) or errDie("Unable to check database for existing settings.");
            if (pg_numrows($Rslt) > 0) {
                $set = pg_fetch_array($Rslt);
                $whid = $set['value'];
            }
        }
        $store_drop = "<select name='filter_store'>";
        $store_drop .= "<option value='0'>All Stores</option>";
        while ($wh = pg_fetch_array($whRslt)) {
            if (isset($filter_store) and $filter_store == $wh['whid']) {
                $store_drop .= "<option value='{$wh['whid']}' selected>({$wh['whno']}) {$wh['whname']}</option>";
            } else {
                $store_drop .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
            }
        }
        $store_drop .= "</select>";
    }
    $details = "\n\t\t<center>\n\t\t<h3>New Order</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='SCROLL' value='1' />\n\t\t\t<input type='hidden' name='key' value='update' />\n\t\t\t<input type='hidden' name='purid' value='{$purid}' />\n\t\t\t<input type='hidden' name='deptid' value='{$deptid}' />\n\t\t\t<input type='hidden' name='letters' value='{$letters}' />\n\t\t\t<input type='hidden' name='total' value='{$TOTAL}' />\n\t\t\t<input type='hidden' name='subtot' value='{$SUBTOT}'>\n\t\t<table " . TMPL_tblDflts . " width='97%'>\n\t\t\t<tr>\n\t\t\t\t<td valign='top'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'> Supplier Details </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>Department</td>\n\t\t\t\t\t\t\t<td valign='center'>{$dept['deptname']}</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>Supplier</td>\n\t\t\t\t\t\t\t<td valign='center'>{$suppliers}</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>Account number</td>\n\t\t\t\t\t\t\t<td valign='center'>{$accno}</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 valign='top'>Supplier Address</td>\n\t\t\t\t\t\t\t<td valign='center'>" . nl2br($supaddr) . "</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>Select Using</td>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\tStock Code\n\t\t\t\t\t\t\t\t<input type='radio' name='sel_frm' value='stkcod' onChange='javascript:document.form.submit();' {$sel_frm_cod}> Stock Description<input type='radio' name='sel_frm' value='stkdes' onChange='javascript:document.form.submit();' {$sel_frm_des} />\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'>Additional Filters</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>Select Store</td>\n\t\t\t\t\t\t\t<td>{$store_drop}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t{$display_optional_filters}\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Stock Filter</td>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<input type='text' size='13' name='des' value='{$des}'> \n\t\t\t\t\t\t\t\t<input type='submit' value='Search'> \n\t\t\t\t\t\t\t\t<input type='submit' name='des' value='Show All'>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td valign='top' align='right' width='35%'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th colspan='2'>Order Details</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>Order No.</td>\n\t\t\t\t\t\t\t<td valign='center'>{$pur['purnum']}</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>Order No.</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='ordernum' value='{$pur['ordernum']}'></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>Supplier Inv</td>\n\t\t\t\t\t\t\t<td><input type='text' size='10' name='supinv' value='{$pur['supinv']}'></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>Terms</td>\n\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</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>Date</td>\n\t\t\t\t\t\t\t<td valign='center' nowrap='t'>" . mkDateSelect("pur", $pur_year, $pur_month, $pur_day) . "</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 Inclusive</td>\n\t\t\t\t\t\t\t<td valign='center'>\n\t\t\t\t\t\t\t\tYes <input type='radio' size='7' name='vatinc' value='yes' {$chy}> \n\t\t\t\t\t\t\t\tNo <input type='radio' size='7' name='vatinc' value='no' {$chn}></td></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>Delivery Charges</td>\n\t\t\t\t\t\t\t<td valign='center'><input type=text size=7 name=shipchrg value='{$pur['shipchrg']}'></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>Delivery Charges VAT Code</td>\n\t\t\t\t\t\t\t<td valign='center'>{$Vatcodes}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t<th width='25%'>Remarks</th>\n\t\t\t\t\t\t\t<td rowspan='5' valign='top' width='50%'>{$ex} {$error}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<a href='supp-new.php?re={$pur['purnum']}'>New Supplier</a>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='5' align='center' valign='top'>\n\t\t\t\t\t\t\t\t<textarea name='remarks' rows='4' cols='20'>{$pur['remarks']}</textarea>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='purchase-view.php'>View Orders</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='main.php'>Main Menu</a></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td align='right'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='80%'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$SUBTOT}</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>Delivery Charges</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$pur['shipping']}</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 {$vat14}</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$VAT}</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<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td colspan='2' align='center'><input name='addnon' type='submit' value='Add Non stock Product'> | <input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<a name='bottom'>\n\t\t</form>\n\t\t</center>\n\t\t{$jump_bot}";
    return $details;
}
function method($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($rec_amount, "num", 1, 10, "Invalid supplier payment amount.");
    # 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;
    }
    global $_GET;
    if (isset($_GET["e"])) {
        $ex = "<input type='hidden' name='e' value='y'>";
    } else {
        $ex = "";
    }
    if (!isset($all)) {
        $all = 0;
    }
    $as1 = "";
    $as2 = "";
    $as3 = "";
    if ($all == 0) {
        $as1 = "selected";
    } elseif ($all == 1) {
        $as2 = "selected";
    } else {
        $as3 = "selected";
    }
    $alls = "\n\t\t\t<select name='all'>\n\t\t\t\t<option value='0' {$as1}>Auto</option>\n\t\t\t\t<option value='1' {$as2}>Allocate To Age Analysis</option>\n\t\t\t\t<option value='2' {$as3}>Allocate To Each invoice</option>\n\t\t\t</select>";
    // layout
    $add = "\n\t\t\t<h3>New Multiple Bank Payments</h3>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t\t<input type='hidden' size='5' name='pur' value=''>\n\t\t\t\t<input type='hidden' size='5' name='inv' value=''>\n\t\t\t\t<input type='hidden' name='key' value='alloc'>\n\t\t\t\t<input type='hidden' name='rec_amount' value='{$rec_amount}'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>Allocation</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2' align='center'>{$alls}</td>\n\t\t\t\t</tr>\n\t\t\t\t" . TBL_BR . "\n\t\t\t\t{$ex}\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Supplier</th>\n\t\t\t\t\t<th>Bank Account</th>\n\t\t\t\t\t<th>Date</th>\n\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t<th>Reference</th>\n\t\t\t\t\t<th>Cheque Number</th>\n\t\t\t\t\t<th>Amount</th>\n\t\t\t\t</tr>";
    for ($t = 0; $t < $rec_amount; $t++) {
        db_connect();
        $get_sup = "SELECT * FROM suppliers WHERE div = '" . USER_DIV . "' AND location = 'loc' ORDER BY supname,supno";
        $run_sup = db_exec($get_sup) or errDie("Unable to get supplier information.");
        if (pg_numrows($run_sup) < 1) {
            return "\n\t\t\t\t\t<li class='err'>No Suppliers Found.</li>\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>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-supp.php'>Add supplier payment</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>";
        } else {
            $supdrop = "<select name='supid[{$t}]'>";
            while ($sarr = pg_fetch_array($run_sup)) {
                $supdrop .= "<option value='{$sarr['supid']}'>({$sarr['supno']}) {$sarr['supname']}</option>";
            }
            $supdrop .= "</select>";
        }
        $bankacc = "<select name='bankid[{$t}]'>";
        $sql = "SELECT * FROM bankacct WHERE btype != 'int' AND div = '" . USER_DIV . "' ORDER BY accname,bankname";
        $banks = db_exec($sql);
        $numrows = pg_numrows($banks);
        if (empty($numrows)) {
            return "<li class='err'> There are no accounts held at the selected Bank.\n\t\t\t<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct Selection'>";
        }
        while ($acc = pg_fetch_array($banks)) {
            $bankacc .= "<option value='{$acc['bankid']}'>{$acc['accname']} - {$acc['bankname']} ({$acc['acctype']})</option>";
        }
        $bankacc .= "</select>";
        // 	if(isset($_GET["cash"])) {
        // 		$add.="<option value='0'>Pay Cash</option>";
        // 	}
        if (!isset($amt[$t])) {
            $amt[$t] = "";
            $descript[$t] = "";
            $cheqnum[$t] = "";
            $reference[$t] = "";
        }
        if (!isset($date_day[$t])) {
            $date_year[$t] = date("Y");
            $date_month[$t] = date("m");
            $date_day[$t] = date("d");
        }
        $add .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='center'>{$supdrop}</td>\n\t\t\t\t\t<td valign='center'>{$bankacc}</td>\n\t\t\t\t\t<td>" . mkDateSelecta("date", $t, $date_year[$t], $date_month[$t], $date_day[$t]) . "</td>\n\t\t\t\t\t<td valign='center'><textarea cols='20' rows='3' name='descript[{$t}]'>{$descript[$t]}</textarea></td>\n\t\t\t\t\t<td valign='center'><input type='text' size='20' name='reference[{$t}]' value='{$reference[$t]}'></td>\n\t\t\t\t\t<td valign='center'><input size='16' name='cheqnum[{$t}]' value='{$cheqnum[$t]}'></td>\n\t\t\t\t\t<td valign='center'>" . CUR . " <input type='text' size='12' name='amt[{$t}]' value='{$amt[$t]}'></td>\n\t\t\t\t</tr>";
    }
    $add .= "\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td valign='center' align='right' colspan='7'><input type='submit' value='Allocate &raquo;'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>";
    $OUTPUT = "\n\t\t\t{$add}\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr><th>Quick Links</th></tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='bank-pay-supp.php'>Add supplier payment</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t</table>";
    return $OUTPUT;
}