function get_current_setting()
{
    db_connect();
    $get_list = "SELECT * FROM non_purchases_account_list";
    $run_list = db_exec($get_list) or errDie("Unable to get account lisit information.");
    if (pg_numrows($run_list) > 0) {
        $account_list = "\n\t\t\t<tr>\n\t\t\t\t<th>Account</th>\n\t\t\t\t<th>Options</th>\n\t\t\t</tr>";
        while ($aarr = pg_fetch_array($run_list)) {
            $account_list .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$aarr['accname']}</td>\n\t\t\t\t\t<td><input type='submit' name='remove[{$aarr['accid']}]' value='Remove'></td>\n\t\t\t\t</tr>";
        }
    }
    $cur_setting = getCsetting("USE_NON_PURCHASES_ACCOUNTS");
    $yes_setting = "";
    $no_setting = "";
    if (!isset($cur_setting) or strlen($cur_setting) < 1) {
        $no_setting = "checked='yes'";
    } else {
        if ($cur_setting == "yes") {
            $yes_setting = "checked";
        } else {
            $no_setting = "checked";
        }
    }
    $display = "\n\t\t<h2>Accounts to Display for Non Stock Purchases</h2>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Use These Accounts Only</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='radio' name='setting' value='yes' {$yes_setting}> Yes\n\t\t\t\t\t<input type='radio' name='setting' value='no' {$no_setting}> No\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='save' value='Save'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<br>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Add Account</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='2'>" . mkAccSelect("newaccount", $newaccount) . " <input type='submit' name='add' value='Add Account'></td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t{$account_list}\n\t\t</table>\n\t\t</form>";
    return $display;
}
function get_limit_setting($err = "")
{
    $cur_setting = getCsetting("PRE_STOCK_TAKE_LIMIT");
    if (!isset($cur_setting) or strlen($cur_setting) < 1) {
        $cur_setting = 0;
    }
    $cur_setting += 0;
    $display = "\n\t\t<h4>Change How Many Stock Items Appear On Pre Stock Take Pages</h4>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='confirm'\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t{$err}\n\t\t\t<tr>\n\t\t\t\t<th>Display Limit</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><input type='text' size='5' name='setting' value='{$cur_setting}'></td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td><input type='submit' value='Save'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>";
    return $display;
}
function get_cubit_setting($err = "")
{
    $cur_setting = getCsetting("OPTIONAL_STOCK_FILTERS");
    $yes_setting = "";
    $no_setting = "";
    if (!isset($cur_setting) or strlen($cur_setting) < 1) {
        $yes_setting = "checked='yes'";
    } else {
        if ($cur_setting == "yes") {
            $yes_setting = "checked";
        } else {
            $no_setting = "checked";
        }
    }
    $display = "\n\t\t<h4>Display Additional Stock Filters On Reports</h4>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t{$err}\n\t\t\t<tr>\n\t\t\t\t<th>Display Filters</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='radio' name='setting' value='yes' {$yes_setting}> Yes\n\t\t\t\t\t<input type='radio' name='setting' value='no' {$no_setting}> No\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><input type='submit' value='Save'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>";
    return $display;
}
function show_setting($err = "")
{
    #get current setting ...
    $neg_setting = getCsetting("SORDER_NEG_STOCK");
    if (!isset($neg_setting) or strlen($neg_setting) < 1) {
        $neg_setting = "yes";
    }
    $check1 = "";
    $check2 = "";
    if ($neg_setting == "yes") {
        $check1 = "checked=yes";
    } else {
        $check2 = "checked=yes";
    }
    $display = "\n\t\t<h4>Change Showing Of Negative Stock On Sales Order Setting</h4>\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='confirm'>\n\t\t\t{$err}\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Display Negative Stock On Sales Orders</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><input type='radio' name='neg_setting' value='yes' {$check1}>Yes</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><input type='radio' name='neg_setting' value='no' {$check2}>No</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td align='right'><input type='submit' value='Write'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>";
    return $display;
}
function details($_POST, $error = "")
{
    extract($_POST);
    # validate input
    include "libs/validate.lib.php";
    $v = new validate();
    if (isset($sordid)) {
        $v->isOk($sordid, "num", 1, 20, "Invalid sales order number.");
    }
    if (isset($deptid)) {
        $v->isOk($deptid, "num", 1, 20, "Invalid department number.");
    }
    if (isset($letters)) {
        $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($sordid)) {
        $sordid = create_dummy($deptid);
        $stkerr = "0,0";
    }
    if (!isset($proforma)) {
        $proforma = "";
    }
    if (!isset($done)) {
        $done = "";
    }
    # Get Sales Order info
    db_connect();
    $sql = "SELECT * FROM sorders WHERE sordid = '{$sordid}' AND div = '" . USER_DIV . "'";
    $sordRslt = db_exec($sql) or errDie("Unable to get Sales Order information");
    if (pg_numrows($sordRslt) < 1) {
        return "<li class='err'>Sales Order Not Found</li>";
    }
    $sord = pg_fetch_array($sordRslt);
    # check if Sales Order has been printed
    if ($sord['accepted'] == "y") {
        $error = "<li class='err'> Error : Sales Order number <b>{$sordid}</b> has already been printed.";
        $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 = '{$sord['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 customers WHERE cusnum = '{$sord['cusnum']}' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    if (pg_numrows($custRslt) < 1) {
        db_connect();
        if ($deptid == "0") {
            $searchdept = "";
        } else {
            $searchdept = "deptid = '{$sord['deptid']}' AND ";
        }
        # Query server for customer info
        $sql = "SELECT cusnum, cusname, surname FROM customers WHERE {$searchdept} location != 'int' AND lower(surname) LIKE lower('{$letters}%') AND div = '" . USER_DIV . "' ORDER BY surname";
        $custRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($custRslt) < 1) {
            $err = "<li class='err'>No customer names starting with <b>{$letters}</b> in database.</li>";
            return view_err($_POST, $err);
        } else {
            $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
            $customers .= "<option value='-S' selected>Select Customer</option>";
            while ($cust = pg_fetch_array($custRslt)) {
                $customers .= "<option value='{$cust['cusnum']}'>{$cust['cusname']} {$cust['surname']}</option>";
            }
            $customers .= "</select>";
        }
        # take care of the unset vars
        $cust['addr1'] = "";
        $cust['cusnum'] = "";
        $cust['vatnum'] = "";
        $cust['accno'] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        # moarn if customer account has been blocked
        if ($cust['blocked'] == 'yes') {
            return "<li class='err'>Error : Selected customer account has been blocked.</li>";
        }
        $customers = "<input type='hidden' name='cusnum' value='{$cust['cusnum']}'>{$cust['cusname']}  {$cust['surname']}";
        $cusnum = $cust['cusnum'];
    }
    /* --- Start Drop Downs --- */
    # Select warehouse
    db_conn("exten");
    //	$whs = "<select name='whidss[]' onChange='javascript:document.form.submit();'>";
    $whs = "<select name='whidss[]'>";
    $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)) {
            if (!user_in_store_team($wh["whid"], USER_ID)) {
                continue;
            }
            $whs .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
        }
    }
    $whs .= "</select>";
    # get sales people
    db_conn("exten");
    $sql = "SELECT * FROM salespeople WHERE div = '" . USER_DIV . "' ORDER BY salesp ASC";
    $salespRslt = db_exec($sql) or errDie("Unable to get sales people.");
    if (pg_numrows($salespRslt) < 1) {
        return "<li class='err'> There are no Sales People found in Cubit.</li>";
    } else {
        $salesps = "<select name='salespn'>";
        while ($salesp = pg_fetch_array($salespRslt)) {
            if ($salesp['salesp'] == $sord['salespn']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $salesps .= "<option value='{$salesp['salesp']}' {$sel}>{$salesp['salesp']}</option>";
        }
        $salesps .= "</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, $sord['terms']);
    # Keep the charge vat option stable
    if ($sord['chrgvat'] == "inc") {
        $chin = "checked=yes";
        $chex = "";
        $chno = "";
    } elseif ($sord['chrgvat'] == "exc") {
        $chin = "";
        $chex = "checked=yes";
        $chno = "";
    } else {
        $chin = "";
        $chex = "";
        $chno = "checked=yes";
    }
    if ($sord["display_costs"] == "yes") {
        $dc_sel["yes"] = "checked";
        $dc_sel["no"] = "";
    } else {
        $dc_sel["yes"] = "";
        $dc_sel["no"] = "checked";
    }
    # format date
    list($sord_year, $sord_month, $sord_day) = explode("-", $sord['odate']);
    list($ddate_year, $ddate_month, $ddate_day) = explode("-", $sord["ddate"]);
    /* --- End Drop Downs --- */
    // get the ID of the first warehouse
    db_conn("exten");
    $sql = "SELECT whid FROM warehouses ORDER BY whid ASC LIMIT 1";
    $rslt = db_exec($sql) or errDie("Error reading warehouses (FWH).");
    if (pg_num_rows($rslt) > 0) {
        $FIRST_WH = pg_fetch_result($rslt, 0, 0);
    } else {
        $FIRST_WH = "-S";
    }
    /* --- 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 PRICE</th>\n\t\t\t\t<th>UNIT DISCOUNT</th>\n\t\t\t\t<th>AMOUNT</th>\n\t\t\t\t<th>Remove</th>\n\t\t\t</tr>";
    # get selected stock in this Sales Order
    db_connect();
    $sql = "SELECT * FROM sorders_items  WHERE sordid = '{$sordid}' 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) {
            # Keep track of selected stock amounts
            $amts[$i] = $stkd['amt'];
            $i++;
            $Accounts = "\n\t\t\t\t<select name='accounts[]'>\n\t\t\t\t\t<option value='0'>Select Account</option>";
            $useaccdrop = getCSetting("USE_NON_STOCK_ACCOUNTS");
            if (isset($useaccdrop) and $useaccdrop == "yes") {
                db_connect();
                $acc_sql = "SELECT * FROM non_stock_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)) {
                        if ($acc['accid'] == $stkd['account']) {
                            $Accounts .= "<option value='{$acc['accid']}' selected>{$acc['accname']}</option>";
                        } else {
                            $Accounts .= "<option value='{$acc['accid']}'>{$acc['accname']}</option>";
                        }
                    }
                    $Accounts .= "</select>";
                }
            } else {
                db_conn('core');
                $Sl = "SELECT accid, topacc, accnum, accname FROM accounts WHERE acctype='I' ORDER BY accname";
                $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                while ($ad = pg_fetch_array($Ri)) {
                    if (isb($ad['accid'])) {
                        continue;
                    }
                    if ($ad['accid'] == $stkd['account']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    $Accounts .= "<option value='{$ad['accid']}' {$sel}>{$ad['accname']}</option>";
                }
                $Accounts .= "</select>";
            }
            $sernos = "";
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'>";
            $stkd['unitcost'] = sprint($stkd['unitcost']);
            $viewcost = "<input type='text' size='8' name='unitcost[]' value='{$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>";
            $stkd['amt'] = sprint($stkd['amt']);
            # Put in product
            $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'>\n\t\t\t\t\t\t{$Accounts}\n\t\t\t\t\t\t<input type='hidden' name='whids[]' value='{$stkd['whid']}'>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'>{$Vatcodes}</td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$stkd['description']}'> {$sernos}</td>\n\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t<td><input type='hidden' name='disc[]' value='{$stkd['disc']}'><input type='hidden' name='discp[]' value='{$stkd['discp']}'></td>\n\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<td><input type='checkbox' name='remprod[]' value='{$key}'><input type='hidden' name='SCROLL' value='yes'></td>\n\t\t\t\t</tr>";
            $key++;
        } else {
            # keep track of selected stock amounts
            $amts[$i] = $stkd['amt'];
            $i++;
            # 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);
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            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[]'>";
            //<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['unitcost'] = sprint($stkd['unitcost']);
            $stkd['amt'] = sprint($stkd['amt']);
            //			$sql = "SELECT * FROM manufact.jobcards WHERE recipe!='yes' AND completion!='1'";
            //			$job_rslt = db_exec($sql) or errDie("Unable to retrieve jobs.");
            //
            //			$job_sel = "<select name='job_id[]' style='width: 100%'>";
            //			while ($job_data = pg_fetch_array($job_rslt)) {
            //				if ($stkd["jobcard_id"] == $job_data["id"]) {
            //					$sel = "selected";
            //				} else {
            //					$sel = "";
            //				}
            //
            //				$job_sel .= "<option value='$job_data[id]' $sel>
            //					$job_data[id] $job_data[description]
            //				</option>";
            //			}
            //			$job_sel .= "</select>";
            //	<tr>
            //				<td bgcolor='#ff0000' width='10%'>
            //					$job_sel<br />
            //					<input type='submit' name='pur[]' value='Add To Purchase Resource Planning'>
            //				</td>
            //			</tr>
            // rowspan='2'
            # 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<input type='hidden' name='amt[]' value='{$stkd['amt']}'>\n\t\t\t\t<input type='hidden' name='pqty[{$stk['stkid']}]' value='{$stkd['qty']}' />\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>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'></td>\n\t\t\t\t\t<td><input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'></td>\n\t\t\t\t\t<td><input type='text' size='4' name='disc[]' value='{$stkd['disc']}'> OR <input type='text' size='4' name='discp[]' value='{$stkd['discp']}' maxlength=5>%</td>\n\t\t\t\t\t<td>" . CUR . " {$stkd['amt']}</td>\n\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</tr>";
            $key++;
        }
    }
    # Look above(remprod keys)
    $keyy = $key;
    # look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    }
    #get negative stock setting
    $neg_setting = getCsetting("SORDER_NEG_STOCK");
    if (!isset($neg_setting) or strlen($neg_setting) < 1) {
        $neg_setting = "yes";
    }
    if ($neg_setting == "yes") {
        $search_neg_stock = "";
    } else {
        $search_neg_stock = " AND (units > 0) ";
    }
    # check if stock warehouse was selected
    if (isset($whidss)) {
        foreach ($whidss as $key => $whid) {
            if (isset($stkidss[$key]) && $stkidss[$key] != "-S" && isset($cust['pricelist'])) {
                # skip if not selected
                if ($whid == "-S") {
                    continue;
                }
                # 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);
                # get selected warehouse name
                db_conn("exten");
                $sql = "SELECT whname FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                # get price from price list if it is set
                if (isset($cust['pricelist'])) {
                    # get selected stock in this warehouse
                    db_conn("exten");
                    $sql = "SELECT price FROM plist_prices WHERE listid = '{$cust['pricelist']}' AND stkid = '{$stk['stkid']}' AND div = '" . USER_DIV . "'";
                    $plRslt = db_exec($sql);
                    if (pg_numrows($plRslt) > 0) {
                        $pl = pg_fetch_array($plRslt);
                        $stk['selamt'] = $pl['price'];
                    }
                }
                /* -- Start Some Checks -- */
                # check if they are selling too much
                if ($stk['units'] - $stk['alloc'] < $qtyss[$key]) {
                    if (!in_array($stk['stkid'], explode(",", $stkerr))) {
                        if ($stk['type'] != 'lab') {
                            $stkerr .= ",{$stk['stkid']}";
                            $error .= "<li class='err'>Warning :  Item number <b>{$stk['stkcod']}</b> does not have enough items available.</li>";
                        }
                    }
                }
                /* -- End Some Checks -- */
                # Calculate the Discount discount
                if ($discs[$key] < 1) {
                    if ($discps[$key] > 0) {
                        $discs[$key] = round($discps[$key] / 100 * $stk['selamt'], 2);
                    }
                } else {
                    $discps[$key] = round($discs[$key] * 100 / $stk['selamt'], 2);
                }
                # Calculate amount
                $amt[$key] = $qtyss[$key] * ($stk['selamt'] - $discs[$key]);
                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>";
                $amt[$key] = sprint($amt[$key]);
                $stk['selamt'] = sprint($stk['selamt']);
                # 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<input type='hidden' name='whids[]' value='{$whid}'>\n\t\t\t\t\t<input type='hidden' name='stkids[]' value='{$stk['stkid']}'>\n\t\t\t\t\t<input type='hidden' name='amt[]' value='{$amt[$key]}'>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>{$wh['whname']}</td>\n\t\t\t\t\t\t<td><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>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\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<td><input type='text' size='8' name='unitcost[]' value='{$stk['selamt']}'></td>\n\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t<input type='text' size='4' name='disc[]' value='{$discs[$key]}'>\n\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t<input type='text' size='4' name='discp[]' value='{$discps[$key]}' maxlength=5>%\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td nowrap>" . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
                $keyy++;
            } else {
                if (isset($accountss[$key]) && $accountss[$key] != "0" && isset($cust['pricelist'])) {
                    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[$key] * $unitcosts[$key]);
                    # Input qty if not serialised
                    $qtyin = "<input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'>";
                    # Check permissions
                    $unitcosts[$key] = sprint($unitcosts[$key]);
                    $viewcost = "<input type='text' size='8' name='unitcost[]' value='{$unitcosts[$key]}'>";
                    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[$key] == $vd['id']) {
                            $sel = "selected";
                        } else {
                            $sel = "";
                        }
                        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
                    }
                    $Vatcodes .= "</select>";
                    $amt[$key] = sprint($amt[$key]);
                    # Put in selected warehouse and stock
                    $products .= "\n\t\t\t\t\t<input type='hidden' name='accounts[]' value='{$accountss[$key]}'>\n\t\t\t\t\t<input type='hidden' name='whids[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='stkids[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='disc[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='discp[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='amt[]' value='{$amt[$key]}'>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td colspan='2'>{$ad['accname']}</td>\n\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$descriptionss[$key]}'></td>\n\t\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t<td nowrap> " . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
                    $keyy++;
                } 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 = '{$filter_store}' AND div = '" . USER_DIV . "'";
                            $whRslt = db_exec($sql);
                            $wh = pg_fetch_array($whRslt);
                        }
                        # get stock on this warehouse
                        db_connect();
                        if (isset($ria) and $ria != "") {
                            $len = strlen($ria);
                            if ($ria == "Show All") {
                                $Wh = "";
                                $ria = "";
                            } else {
                                $Wh = "AND (lower(stkdes) LIKE lower('%{$ria}%')) OR (lower(stkcod) LIKE lower('%{$ria}%'))";
                                $ria = "";
                            }
                        } else {
                            $Wh = "AND FALSE";
                            $ria = "";
                        }
                        $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}'";
                        }
                        $sql = "SELECT * FROM stock WHERE blocked = 'n' {$search_neg_stock} AND div = '" . USER_DIV . "' {$Wh} 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 store.</li>";
                            continue;
                        }
                        if ($sel_frm == "stkcod") {
                            $cods = "<select name='stkidss[]' onChange='javascript:document.form.submit();'>";
                            $cods .= "<option value='-S' disabled selected>Select Number</option>";
                            $count = 0;
                            while ($stk = pg_fetch_array($stkRslt)) {
                                $cods .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
                            }
                            $cods .= "</select> ";
                            $descs = "";
                        } else {
                            $descs = "<select style='width:250px' name='stkidss[]' onChange='javascript:document.form.submit();'>";
                            $descs .= "<option value='-S' disabled selected>Select Description</option>";
                            $count = 0;
                            while ($stk = pg_fetch_array($stkRslt)) {
                                $descs .= "<option value='{$stk['stkid']}'>{$stk['stkdes']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
                            }
                            $descs .= "</select> ";
                            $cods = "";
                        }
                        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[]'>\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<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='whidss[]' value='{$filter_store}'>\n\t\t\t\t\t\t<input type='hidden' name='amts[]' value='0.00'>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td>{$cods}<input type='hidden' name='vatcodess' value='0'></td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t<td>{$descs}</td>\n\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<td>&nbsp;</td>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t" . CUR . " <input type='text' size='4' name='discs[]' value='0'>\n\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t<input type='text' size='4' name='discps[]' value='0' maxlength='5'>%\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t</tr>";
                    } 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_STOCK_ACCOUNTS");
                        if (isset($useaccdrop) and $useaccdrop == "yes") {
                            db_connect();
                            $acc_sql = "SELECT * FROM non_stock_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 WHERE acctype='I' ORDER BY accname";
                            $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                            while ($ad = pg_fetch_array($Ri)) {
                                if (isb($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[]'>\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<input type='hidden' name='whidss[]' value='{$FIRST_WH}'>\n\t\t\t\t\t\t<inpu type='hidden' name='stkidss[]' value=''>\n\t\t\t\t\t\t<input type='hidden' name='discs[]' value='0'>\n\t\t\t\t\t\t<input type='hidden' name='discps[]' value='0' >\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td colspan='2'>{$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[]'></td>\n\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<td><input type='text' name='unitcosts[]' size='7'></td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t</tr>";
                    }
                }
            }
        }
    } else {
        if (!isset($addnon)) {
            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);
            }
            # get stock on this warehouse
            db_connect();
            if (isset($ria) and $ria != "") {
                $len = strlen($ria);
                if ($ria == "Show All") {
                    $Wh = "";
                    $ria = "";
                } else {
                    $Wh = "AND (lower(stkdes) LIKE lower('%{$ria}%')) OR (lower(stkcod) LIKE lower('%{$ria}%'))";
                    $ria = "";
                }
            } else {
                $Wh = "AND FALSE";
                $ria = "";
            }
            $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}'";
            }
            $sql = "SELECT * FROM stock WHERE blocked = 'n' {$search_neg_stock} AND div = '" . USER_DIV . "' {$Wh} 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 Number</option>";
            $count = 0;
            while ($stk = pg_fetch_array($stkRslt)) {
                $stks .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
            }
            $stks .= "</select> ";
            $products .= "\n\t\t\t\t<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>\n\t\t\t\t<input type='hidden' name='vatcodess[]' value=''>\n\t\t\t\t<input type='hidden' name='whidss[]' value='{$filter_store}'>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>{$stks}</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<input type='text' size='4' name='discs[]' value='0'>\n\t\t\t\t\t\tOR\n\t\t\t\t\t\t<input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>\n\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t</tr>";
        } else {
            if (isset($addnon)) {
                $Accounts = "\n\t\t\t\t<select name='accountss[]'>\n\t\t\t\t\t<option value='0'>Select Account</option>";
                $useaccdrop = getCSetting("USE_NON_STOCK_ACCOUNTS");
                if (isset($useaccdrop) and $useaccdrop == "yes") {
                    db_connect();
                    $acc_sql = "SELECT * FROM non_stock_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 WHERE acctype='I' ORDER BY accname";
                    $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                    while ($ad = pg_fetch_array($Ri)) {
                        if (isb($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<select name='vatcodess[]'>\n\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<inpu type='hidden' name='stkidss[]' value=''>\n\t\t\t\t<input type='hidden' name='whidss[]' value='{$FIRST_WH}'>\n\t\t\t\t<input type='hidden' name='discs[]' value='0'>\n\t\t\t\t<input type='hidden' name='discps[]' value='0' >\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'>{$Accounts}</td>\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[]'></td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t\t<td><input type='text' name='unitcosts[]' size='7'></td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t</tr>";
            }
        }
    }
    // 	$products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Calculate subtotal
    $SUBTOT = sprint($sord['subtot']);
    # Calculate tradediscm
    if ($sord['traddisc'] > 0) {
        $traddiscm = sprint($sord['traddisc'] / 100 * ($SUBTOT + $sord['delchrg']));
    } else {
        $traddiscm = "0.00";
    }
    $VATP = TAX_VAT;
    # Calculate subtotal
    $SUBTOT = sprint($sord['subtot']);
    $VAT = sprint($sord['vat']);
    $TOTAL = sprint($sord['total']);
    $sord['delchrg'] = sprint($sord['delchrg']);
    /* --- End Some calculations --- */
    /*--- Start checks --- */
    # check only if the customer is selected
    if (isset($cusnum) && $cusnum != "-S") {
        #check againg credit limit
        if ($cust['credlimit'] != 0 && $TOTAL + $cust['balance'] > $cust['credlimit']) {
            $error .= "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " {$cust['credlimit']}</b> has been exceeded:</li>";
        }
        $avcred = $cust['credlimit'] - $cust['balance'];
    } else {
        $avcred = "0.00";
    }
    /*--- Start checks --- */
    if (!isset($letters)) {
        $letters = "";
    }
    $sord['delvat'] += 0;
    if ($sord['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $sord['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'] == $sord['delvat']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $Vatcodes .= "</select>";
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    $psel1 = "";
    $psel2 = "";
    if (isset($proforma) and $proforma == "yes") {
        $psel1 = "checked=yes";
    } else {
        $psel2 = "checked=yes";
    }
    if ($proforma == "yes") {
        #generate a unique id IF it hasnt been done yet
        if (!isset($pinvnum) or $pinvnum == 0) {
            pglib_transaction("BEGIN") or errDie("Could not start database transaction");
            #get unique id
            $get_uni = "INSERT INTO unique_id (entry) VALUES ('value')";
            $run_uni = db_exec($get_uni) or errDie("Unable to get unique id");
            $pinvnum = pglib_lastid("unique_id", "id");
            $rem_sql = "DELETE FROM unique_id WHERE id = '{$pinvnum}'";
            $run_rem = db_exec($rem_sql) or errDie("Unable to remove unique id check");
            #further check to see if an invoice has this is should be done here...
            pglib_transaction("COMMIT") or errDie("Could not commit database transaction");
        }
        $getpinvnum = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Proforma Invoice Number</td>\n\t\t\t\t<td><input type='hidden' name='pinvnum' value='{$pinvnum}'>{$pinvnum}</td>\n\t\t\t</tr>";
    } else {
        $getpinvnum = "<input type='hidden' name='pinvnum' value='0'>";
    }
    // 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 = "";
    }
    // Retrieve VAT Setting
    $sql = "SELECT value FROM cubit.settings WHERE constant='VAT_INC'";
    $vatinc_rslt = db_exec($sql) or errDie("Unable to retrieve vat setting.");
    $vatinc = pg_fetch_result($vatinc_rslt, 0);
    if ($vatinc != "yes" && $vatinc != "no") {
        $vatinc = "no";
    }
    if ($vatinc == 'yes') {
        $chrgvat = "inc";
    } else {
        $chrgvat = "exc";
    }
    if (isset($diffwhBtn) or isset($addprodBtn) or isset($addnon) or isset($saveBtn) or isset($upBtn) or isset($doneBtn) or isset($donePrnt) or isset($ria)) {
        $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);
                $filter_store = $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>";
    }
    $cust_del_addr = $sord['del_addr'];
    $details = "\n\t\t<center>\n\t\t<h3>New Sales 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='sordid' value='{$sordid}'>\n\t\t\t<input type='hidden' name='letters' value='{$letters}'>\n\t\t\t<input type='hidden' name='stkerr' value='{$stkerr}'>\n\t\t\t<input type='hidden' name='chrgvat' value='{$chrgvat}' />\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\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'> Customer 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>Account No.</td>\n\t\t\t\t\t\t\t<td valign='center'>{$cust['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>Customer</td>\n\t\t\t\t\t\t\t<td valign='center'>{$customers}</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'>Customer Address</td>\n\t\t\t\t\t\t\t<td valign='center'>" . nl2br($cust['addr1']) . "</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'>Current Delivery Address</td>\n\t\t\t\t\t\t\t<td valign='center'>" . nl2br($cust_del_addr) . "</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'>Delivery Address</td>\n\t\t\t\t\t\t\t<td valign='center'>\n\t\t\t\t\t\t\t\t<input type='button' onClick=\"\n\t\t\t\t\t\t\t\t\tvar windowReference;\n\t\t\t\t\t\t\t\t\tfunction openPopup() {\n\t\t\t\t\t\t\t\t\t\twindowReference = window.open('sorder-new-deladdr.php?sordid={$sordid}','windowName','width=500,height=400,status=1');\n\t\t\t\t\t\t\t\t\t\tif (!windowReference.opener)\n\t\t\t\t\t\t\t\t\t\t\twindowReference.opener = self;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\topenPopup();\" value='Change Delivery Address'>\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 class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Customer Order number</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='cordno' value='{$sord['cordno']}'></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>Customer VAT Number</td>\n\t\t\t\t\t\t\t<td>{$cust['vatnum']}</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>Stock Code<input type='radio' name='sel_frm' value='stkcod' onChange='javascript:document.form.submit();' {$sel_frm_cod}><br>Stock Description<input type='radio' name='sel_frm' value='stkdes' onChange='javascript:document.form.submit();' {$sel_frm_des}></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() . "' " . ass("Type the first letters of the stock code you are looking for.") . ">\n\t\t\t\t\t\t\t<td>Stock Filter</td>\n\t\t\t\t\t\t\t<td nowrap><input type='text' size='13' name='ria' value='{$ria}'> <input type='submit' value='Search'> <input type='submit' name='ria' value='Show All'></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>\n\t\t\t\t\t\t\t<th colspan='2'> Sales 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>Sales Order No.</td>\n\t\t\t\t\t\t\t<td valign='center'>{$sord['sordid']}</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>Proforma Invoice</td>\n\t\t\t\t\t\t\t<td valign='center'>Yes <input type='radio' name='proforma' value='yes' {$psel1} onChange='javascript:document.form.submit();'> No <input type='radio' name='proforma' value='no' {$psel2} onChange='javascript:document.form.submit();'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t{$getpinvnum}\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>Display Costs</td>\n\t\t\t\t\t\t\t<td>Yes <input type='radio' name='costs' value='yes' {$dc_sel['yes']}> No <input type='radio' name='costs' value='no' {$dc_sel['no']}></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='5' name='ordno' value='{$sord['ordno']}'></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='chrgvat' value='inc' {$chin}> No<input type='radio' size='7' name='chrgvat' value='exc' {$chex}></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>Sales Person</td>\n\t\t\t\t\t\t\t<td valign='center'>{$salesps}</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>Sales Order Date</td>\n\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("sord", $sord_year, $sord_month, $sord_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>Delivery/Due Date</td>\n\t\t\t\t\t\t\t<td valign='center'>\n\t\t\t\t\t\t\t\t" . mkDateSelect("ddate", $ddate_year, $ddate_month, $ddate_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>Available Credit</td>\n\t\t\t\t\t\t\t<td>" . CUR . " " . sprint($avcred) . "</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>Trade Discount</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='traddisc' value='{$sord['traddisc']}'>%</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 Charge</td>\n\t\t\t\t\t\t\t<td valign='center'><input type='text' size='7' name='delchrg' value='{$sord['delchrg']}'>{$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'><table " . TMPL_tblDflts . ">{$products}</table></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<td rowspan='2'>" . mkQuickLinks(ql("sorder-view.php", "View Sales Orders"), ql("customers-new.php", "New Customer")) . "\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<th width='25%'>Comments</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() . "' rowspan='4' align='center' valign='top'><textarea name='comm' rows='4' cols='20'>{$sord['comm']}</textarea></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 . " <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>Trade Discount</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$sord['discount']}</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 Charge</td>\n\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$sord['delivery']}</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><b>VAT {$vat14}</b>\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='addprodBtn' type='submit' value='Add Product'>| <input name='addnon' type='submit' value='Add Non stock Product'> | <input type='submit' name='saveBtn' value='Save'> | <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;
}