function details($_POST, $error = "")
{
    # Get vars
    extract($_POST);
    $v = new validate();
    if (isset($invid)) {
        $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    } else {
        $client = "";
        $vatnum = "";
        $cordno = "";
        $deptid = 2;
        $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;
    }
    // Initial values
    if (!isset($invid)) {
        $invid = create_dummy($deptid);
        $stkerr = "0,0";
        $cusnum = 0;
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li class='err'>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    if (!isset($vatnum)) {
        $vatnum = $inv['vatnum'];
    }
    if (!isset($cordno)) {
        $cordno = $inv['cordno'];
    }
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    // 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";
    }
    # Get selected Customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' AND location != 'int' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    if (pg_numrows($custRslt) < 1) {
        db_connect();
        # Query server for customer info   AND lower(surname) LIKE lower('$letters%')
        $sql = "SELECT cusnum,cusname,surname FROM customers WHERE location != 'int' AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
        $custRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($custRslt) < 1) {
            $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
            $customers .= "<option value='0' selected>Select Customer</option>";
            while ($cust = pg_fetch_array($custRslt)) {
                $customers .= "<option value='{$cust['cusnum']}'>{$cust['cusname']} {$cust['surname']}</option>";
            }
            $customers .= "</select>";
        } else {
            $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
            $customers .= "<option value='0' 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'] = "";
        $cust["bustel"] = $inv["telno"];
        $cust["tel"] = "";
        $cust["cellno"] = "";
    } else {
        $cust = pg_fetch_array($custRslt);
        $sql = "SELECT cusnum, cusname, surname FROM customers WHERE deptid = '{$inv['deptid']}' AND location != 'int' AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
        $cusRslt = db_exec($sql) or errDie("Unable to view customers");
        # Moarn if customer account has been blocked   AND lower(surname) LIKE lower('$letters%')
        if ($cust['blocked'] == 'yes') {
            $error .= "<li class=err>Error : Selected customer account has been blocked.";
        }
        // $customers = "<input type=hidden name=cusnum value='$cust[cusnum]'>$cust[cusname]  $cust[surname]";
        $cusnum = $cust['cusnum'];
        $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
        $customers .= "<option value='0' selected>Select Customer</option>";
        // $customers .= "<option value='-S' selected>Select Customer</option>";
        while ($cus = pg_fetch_array($cusRslt)) {
            $sel = "";
            if ($cust['cusnum'] == $cus['cusnum']) {
                $sel = "selected";
            }
            $customers .= "<option value='{$cus['cusnum']}' {$sel}>{$cus['cusname']} {$cus['surname']}</option>";
        }
        $customers .= "</select>";
    }
    /* after first customer selection, set telno to customer's (if any) */
    if (isset($prev_cusnum) && $prev_cusnum != $cusnum) {
        if (trim($cust["bustel"]) != "") {
            $inv["telno"] = $cust["bustel"];
        } else {
            if (trim($cust["tel"]) != "") {
                $inv["telno"] = $cust["tel"];
            } else {
                $inv["telno"] = $cust["cellno"];
            }
        }
    }
    /* --- 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)) {
            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'] == $inv['salespn']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $salesps .= "<option value='{$salesp['salesp']}' {$sel}>{$salesp['salesp']}</option>";
        }
        $salesps .= "</select>";
    }
    # Keep the charge vat option stable
    if ($inv['chrgvat'] == "inc") {
        $chin = "checked=yes";
        $chex = "";
        $chno = "";
    } elseif ($inv['chrgvat'] == "exc") {
        $chin = "";
        $chex = "checked=yes";
        $chno = "";
    } else {
        $chin = "";
        $chex = "";
        $chno = "checked=yes";
    }
    /* we came as a correction from receive payment page */
    if (isset($_POST["key"]) && $_POST["key"] == "recvpayment_write") {
        $inv["odate"] == $_POST["date"];
        $inv["pcc"] = $_POST["pcc"];
        $inv["pcheque"] = $_POST["pcheque"];
        $inv["pcash"] = $_POST["pcash"];
    } else {
        list($pinv_year, $pinv_month, $pinv_day) = explode("-", $inv['odate']);
    }
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # select all products
    $products = "\n\t<table " . TMPL_tblDflts . " width='100%'>\n\t<tr>\n\t\t<th>STORE</th>\n\t\t<th>ITEM NUMBER</th>\n\t\t<th>VAT CODE</th>\n\t\t<th>SERIAL NO.</th>\n\t\t<th>DESCRIPTION</th>\n\t\t<th>QTY</th>\n\t\t<th>UNIT PRICE</th>\n\t\t<th>UNIT DISCOUNT</th>\n\t\t<th>AMOUNT</th>\n\t\t<th>Remove</th>\n\t<tr>";
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM pinv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $line_count = pg_num_rows($stkdRslt);
    $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++;
            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.");
            $Accounts = "<select name='accounts[]'>\n\t\t\t<option value='0'>Select Account</option>";
            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 = "\n\t\t\t\t<input type='hidden' name='sernos[]' value='{$stkd['serno']}'>\n\t\t\t\t<input type='hidden' name='sernos_ss[]' value='{$stkd['serno']}'>";
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'>";
            $viewcost = "<input type='text' size='8' name='unitcost[]' value='" . 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 = "<select name='vatcodes[]'>";
            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>";
            # Put in product
            $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='2'>{$Accounts}<input type='hidden' name='whids[]' value='{$stkd['whid']}'></td>\n\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'>{$Vatcodes}</td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$stkd['description']}'> {$sernos}</td>\n\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='hidden' name='disc[]' value='{$stkd['disc']}'>\n\t\t\t\t\t<input type='hidden' name='discp[]' value='{$stkd['discp']}'>\n\t\t\t\t</td>\n\t\t\t\t<td><input type='hidden' name='amt[]' value='" . sprint($stkd["amt"]) . "'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='checkbox' name='remprod[]' value='{$key}'>\n\t\t\t\t</td>\n\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);
            if ($stk['units'] <= $stk['minlvl']) {
                $error .= "<li class='err'>{$stk['stkcod']} is below minimum level, please notify stock controller.</li>";
            }
            # Serial number
            if ($stk['serd'] == 'yes' && ($inv['serd'] == 'n' || $stkd["serno"] == "")) {
                $sers = ext_getavserials($stkd['stkid']);
                $sernos = "<select name='sernos[]'>";
                foreach ($sers as $skey => $ser) {
                    $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
                }
                $sernos .= "</select>\n\t\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*' />";
            } else {
                $sernos = "\n\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='{$stkd['ss']}' />\n\t\t\t\t\t<input type='hidden' name='sernos[]' value='{$stkd['serno']}'>{$stkd['ss']}";
            }
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'>";
            if ($stk['serd'] == 'yes') {
                $qtyin = "<input type='hidden' size='3' name='qtys[]' value='{$stkd['qty']}'>{$stkd['qty']}";
            }
            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[]'>";
            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>";
            # check permissions
            if (perm("invoice-unitcost-edit.php")) {
                $viewcost = "<input type='text' size='8' name='unitcost[]' value='" . sprint($stkd["unitcost"]) . "'>";
            } else {
                $viewcost = "<input type='hidden' size='8' name='unitcost[]' value='" . sprint($stkd["unitcost"]) . "'>" . sprint($stkd["unitcost"]);
            }
            # put in product
            $products .= "\n\t\t\t<input type='hidden' name='accounts[]' value='0'>\n\t\t\t<input type='hidden' name='descriptions[]' value=''>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><input type='hidden' name='whids[]' value='{$stkd['whid']}'>{$wh['whname']}</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='hidden' name='stkids[]' value='{$stkd['stkid']}'>\n\t\t\t\t\t<a href='#bottom' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a>\n\t\t\t\t</td>\n\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t<td>{$sernos}</td>\n\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='text' size='4' name='disc[]' value='{$stkd['disc']}'><b> OR </b>\n\t\t\t\t\t<input type='text' size='4' name='discp[]' value='{$stkd['discp']}' maxlength='5'>%\n\t\t\t\t</td>\n\t\t\t\t<td><input type='hidden' name='amt[]' value='" . sprint($stkd["amt"]) . "'> " . CUR . sprint($stkd["amt"]) . "</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='checkbox' name='remprod[]' value='{$key}'>\n\t\t\t\t</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 = "";
    } else {
        $SCROLL = "yes";
    }
    # check if stock warehouse was selected
    if (isset($whidss)) {
        foreach ($whidss as $key => $whid) {
            if (isset($stkidss[$key]) && $stkidss[$key] != "-S" && strlen($stkidss[$key]) > 0) {
                # 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);
                if ($stk['serd'] == 'yes') {
                    $sers = ext_getavserials($stkidss[$key]);
                    $sernos = "<select name='sernos[]' onChange='javascript:document.form.submit();'>";
                    foreach ($sers as $skey => $ser) {
                        $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
                    }
                    $sernos .= "</select>\n\t\t\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*' />";
                } else {
                    $sernos = "\n\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value=''>\n\t\t\t\t\t\t<input type='hidden' name='sernos[]' value=''>";
                }
                /* -- 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]);
                # Input qty if not serialised
                $qtyin = "<input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'>";
                if ($stk['serd'] == 'yes') {
                    $qtyin = "<input type='hidden' size='3' name='qtys[]' value='{$qtyss[$key]}'>{$qtyss[$key]}";
                }
                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[]'>";
                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>";
                if (perm("invoice-unitcost-edit.php")) {
                    $viewcost = "<input type='text' size='8' name='unitcost[]' value='" . sprint($stk["selamt"]) . "'>";
                } else {
                    $viewcost = "<input type='hidden' size='8' name='unitcost[]' value='" . sprint($stk["selamt"]) . "'>" . sprint($stk["selamt"]);
                }
                # put in selected warehouse and stock
                $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='{$whid}'>{$wh['whname']}</td>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<input type='hidden' name='stkids[]' value='{$stk['stkid']}'>\n\t\t\t\t\t\t<a href='#bottom' 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>{$Vatcodes}</td>\n\t\t\t\t\t<td>{$sernos}</td>\n\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</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>\n\t\t\t\t\t\t<input type='text' size='4' name='disc[]' value='{$discs[$key]}'><b> OR </b>\n\t\t\t\t\t\t<input type='text' size='4' name='discp[]' value='{$discps[$key]}' maxlength='5'>%\n\t\t\t\t\t</td>\n\t\t\t\t\t<td><input type='hidden' name='amt[]' value='" . sprint($amt[$key]) . "'> " . CUR . sprint($amt[$key]) . "</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t</tr>";
                $line_count = 1;
                $keyy++;
            } else {
                if (isset($accountss[$key]) && $accountss[$key] != "0") {
                    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=qtemp value='$qtyss[$key]'>";
                    $qtyin = "<input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'>";
                    # Check permissions
                    $viewcost = "<input type='text' size='8' name='unitcost[]' value='" . sprint($unitcosts[$key]) . "'>";
                    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[]'>";
                    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>";
                    # Put in selected warehouse and stock
                    $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{$ad['accname']}<input type='hidden' name='accounts[]' value='{$accountss[$key]}'>\n\t\t\t\t\t\t<input type='hidden' name='whids[]' value='0'>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td>{$Vatcodes}<input type='hidden' name='stkids[]' value='0'></td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$descriptionss[$key]}'></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>\n\t\t\t\t\t\t<input type='hidden' name='disc[]' value='0'>\n\t\t\t\t\t\t<input type='hidden' name='discp[]' value='0'>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td><input type='hidden' name='amt[]' value='" . sprint($amt[$key]) . "'> " . CUR . sprint($amt[$key]) . "</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t</tr>";
                    $keyy++;
                } else {
                    if (!isset($diffwhBtn)) {
                        # skip if not selected
                        if ($whid == "-S") {
                            continue;
                        }
                        if (!isset($addnon)) {
                            # 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(substr(stkdes,1,'{$len}'))=lower('{$des}') OR lower(substr(stkcod,1,'{$len}'))=lower('{$des}'))";
                                }
                            } else {
                                $Wh = "AND FALSE";
                                $des = "";
                            }
                            # get stock on this warehouse
                            db_connect();
                            $sql = "SELECT * FROM stock WHERE whid = '{$whid}' AND blocked = 'n' AND div = '" . USER_DIV . "' {$Wh} ORDER BY {$sel_frm} 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.";
                                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);
                            						if($stk['serd'] == 'yes'){
                            							$sers = ext_getavserials($stkidss[$key]);
                            							$sernos = "<select class='width : 15'name='sernos[]' onChange='javascript:document.form.submit();'>";
                            							foreach($sers as $skey => $ser){
                            								$sernos .= "<option value='$ser[serno]'>$ser[serno]</option>";
                            							}
                            							$sernos .= "</select>";
                            						}else{
                            							$sernos = "<input type=hidden name=sernos[] value=''>";
                            						}
                            */
                            if (isset($sel_frm) && $sel_frm == "stkdes") {
                                $descs = "<select class='width : 15'name='stkidss[]' onChange=\"document.form.des.value=''; javascript:document.form.submit();\">";
                                $descs .= "<option value='-S' disabled selected>Select Description</option>";
                                $count = 0;
                                while ($stk = pg_fetch_array($stkRslt)) {
                                    // Check if this stock item has been blocked
                                    if (stock_is_blocked($stk["stkid"])) {
                                        continue;
                                    }
                                    if ($stk["units"] <= 0) {
                                        continue;
                                    }
                                    $descs .= "<option value='{$stk['stkid']}'>{$stk['stkdes']} (" . ($stk['units'] - $stk['alloc']) . ")</option>";
                                }
                                $descs .= "</select> ";
                                $cods = "";
                            } else {
                                $cods = "<select class='width : 15'name='stkidss[]' onChange=\"document.form.des.value=''; javascript:document.form.submit();\">";
                                $cods .= "<option value='-S' disabled selected>Select Number</option>";
                                $count = 0;
                                while ($stk = pg_fetch_array($stkRslt)) {
                                    // Check if this stock item has been blocked
                                    if (stock_is_blocked($stk["stkid"])) {
                                        continue;
                                    }
                                    if ($stk["units"] <= 0) {
                                        continue;
                                    }
                                    $cods .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . ($stk['units'] - $stk['alloc']) . ")</option>";
                                }
                                $cods .= "</select> ";
                                $descs = "";
                            }
                            # 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<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<input type='hidden' name='whidss[]' value='{$whid}'>\n\t\t\t\t\t\t\t\t{$wh['whname']}\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td>{$cods}</td>\n\t\t\t\t\t\t\t<td>&nbsp;</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>\n\t\t\t\t\t\t\t\t<input type='text' size='3' name='qtyss[]' value='1'>\n\t\t\t\t\t\t\t</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<input type='text' size='4' name='discs[] value='0'>\n\t\t\t\t\t\t\t\t<b> OR </b>\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>\n\t\t\t\t\t\t\t\t<input type='hidden' name='amts[]' value='0.00'>\n\t\t\t\t\t\t\t\t" . CUR . " 0.00\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t\t\t</tr>";
                        } else {
                            db_conn('core');
                            $Sl = "SELECT accid,topacc,accnum,accname FROM accounts\n\t\t\t\t\t\t\tWHERE acctype='I' ORDER BY accname";
                            $Ri = db_exec($Sl) or errDie("Unable to get accounts.");
                            $Accounts = "<select name='accountss[]' onChange='javascript:document.form.submit();'>\n\t\t\t\t\t\t<option value='0'>Select Account</option>";
                            while ($ad = pg_fetch_array($Ri)) {
                                if (isb($ad['accid'])) {
                                    continue;
                                }
                                $Accounts .= "\n\t\t\t\t\t\t\t<option value={$ad['accid']}>\n\t\t\t\t\t\t\t\t{$ad['accname']}\n\t\t\t\t\t\t\t</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 = "<select name='vatcodess[]'>";
                            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 colspan='2'>{$Accounts}<input type='hidden' name='whidss[]' value='{$FIRST_WH}'></td>\n\t\t\t\t\t\t\t<input type='hidden' name='stkidss[]' value=''>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td>&nbsp;</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>\n\t\t\t\t\t\t\t\t<input type='hidden' name='discs[]' value='0'>\n\t\t\t\t\t\t\t\t<input type='hidden' name='discps[]' value='0' >\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>";
                        }
                    }
                }
            }
        }
    } else {
        if (!(isset($diffwhBtn) || isset($addnon))) {
            # 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) && $wtd != 0) {
                    $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);
                if (isset($des) and $des != "") {
                    $len = strlen($des);
                    if ($des == "Show All") {
                        $Wh = "";
                        $des = "";
                    } else {
                        $Wh = "AND (lower(substr(stkdes,1,'{$len}'))=lower('{$des}') OR lower(substr(stkcod,1,'{$len}'))=lower('{$des}'))";
                    }
                } else {
                    $Wh = "AND FALSE";
                    $des = "";
                }
                # get stock on this warehouse
                db_connect();
                $sql = "SELECT * FROM stock WHERE whid = '{$whid}' AND blocked = 'n' 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 store.";
                }
                $stks = "<select name='stkidss[]' onChange=\"document.form.des.value=''; javascript:document.form.submit();\">";
                $stks .= "<option value='-S' disabled selected>Select Number</option>";
                $count = 0;
                while ($stk = pg_fetch_array($stkRslt)) {
                    // Check if this stock item has been blocked
                    if (stock_is_blocked($stk["stkid"])) {
                        continue;
                    }
                    if ($stk["units"] <= 0) {
                        continue;
                    }
                    $stks .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . ($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<td><input type='hidden' name='whidss[]' value='{$whid}'>{$wh['whname']}</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>&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'><b> OR </b>\n\t\t\t\t\t\t<input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td><td>" . CUR . " 0.00</td>\n\t\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t</tr>";
            } else {
                $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$whs}</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>&nbsp;</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>&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'><b> OR </b>\n\t\t\t\t\t\t<input type='text' size='4' name='discps[]' value='0' maxlength='5'>%\n\t\t\t\t\t</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)) {
                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.");
                $Accounts = "<select name='accountss[]' onChange='javascript:document.form.submit();'>\n\t\t\t<option value='0'>Select Account</option>";
                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 = "<select name='vatcodess[]'>";
                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>";
                //				<input type=hidden name='stkidss[]' value=''>
                $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan=2>\n\t\t\t\t\t{$Accounts}<input type='hidden' name='whidss[]' value='{$FIRST_WH}'>\n\t\t\t\t</td>\n\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t<td><input type='text' size='20' name='descriptionss[]'></td>\n\t\t\t\t<td><input type='text' size='3' name='qtyss[]' value='1'></td>\n\t\t\t\t<td><input type='text' name='unitcosts[]' size='7'></td>\n\t\t\t\t<td>&nbsp;</td>\n\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='hidden' name='discs[]' value='0'>\n\t\t\t\t\t<input type='hidden' name='discps[]' value='0' >\n\t\t\t\t</td>\n\t\t\t</tr>";
            }
        }
    }
    /* -- start Listeners -- */
    if (isset($diffwhBtn)) {
        $products .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>{$whs}</td>\n\t\t\t<td>&nbsp;</td>\n\t\t\t<td>&nbsp;</td>\n\t\t\t<td>&nbsp;</td>\n\t\t\t<td>&nbsp;</td>\n\t\t\t<td>&nbsp;</td>\n\t\t\t<td>\n\t\t\t\t<input type='text' size='4' name='discs[]' value='0'><b> OR </b>\n\t\t\t\t<input type='text' size='4' name='discps[]' value='0' maxlength='5'>%\n\t\t\t</td>\n\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t<td>&nbsp;</td>\n\t\t</tr>";
    }
    /* -- End Listeners -- */
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    if ($inv['traddisc'] > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * ($SUBTOT + $inv['delchrg']));
    } else {
        $traddiscm = "0.00";
    }
    $VATP = TAX_VAT;
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    if (!isset($done)) {
        $done = "";
    }
    /* --- End Some calculations --- */
    if ($inv['terms'] == 1) {
        $tc1 = "";
        $tc2 = "checked";
    } else {
        $tc1 = "checked";
        $tc2 = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='PSALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sc = "checked";
    } else {
        $sc = "";
    }
    $sales = "<td>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<td>{$salesps}</td>\n\t\t\t\t<td>Print</td>\n\t\t\t\t<td><input type='checkbox' name='printsales' {$sc}></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</td>";
    # Query server for depts
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE div = '" . USER_DIV . "' ORDER BY deptname ASC";
    $deptRslt = db_exec($sql) or errDie("Unable to view customers");
    if (pg_numrows($deptRslt) < 1) {
        return "<li class='err'>There are no Departments found in Cubit.</li>";
    } else {
        $depts = "<select name='deptid'>";
        while ($dept = pg_fetch_array($deptRslt)) {
            if ($dept['deptid'] == $inv['deptid']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $depts .= "<option value='{$dept['deptid']}' {$sel}>{$dept['deptname']}</option>";
        }
        $depts .= "</select>";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM users WHERE username='******'";
    $Ri = db_exec($Sl);
    $data = pg_fetch_array($Ri);
    if ($data['help'] != "S") {
        $save = "|<input type='submit' name='saveBtn' value='Save'>";
    } else {
        $save = "";
    }
    if ($inv['rounding'] > 0) {
        $due = sprint($inv['total'] - $inv['rounding']);
        $rd = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Rounding</td>\n\t\t\t\t\t<td align='right'>R {$inv['rounding']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<th>Amount Due</th>\n\t\t\t\t\t<td align='right'>R {$due}</td>\n\t\t\t\t</tr>";
    } else {
        $rd = "";
    }
    $inv['delvat'] += 0;
    if ($inv['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $inv['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'>";
    while ($vd = pg_fetch_array($Ri)) {
        if ($vd['id'] == $inv['delvat']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $Vatcodes .= "</select>";
    if (strlen($client) < 1) {
        $client = $inv['cusname'];
    }
    if ($inv['cusnum'] == 0) {
        $cd = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer</td>\n\t\t\t\t<td valign='center'><input type='text' size='20' name='client' value='{$client}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>VAT Number</td>\n\t\t\t\t<td valign='center'><input type='text' size='20' name='vatnum' value='{$vatnum}'></td>\n\t\t\t</tr>\n\t\t\t";
        $pc = "<input type='hidden' name='pcredit' value='0'>";
    } else {
        $cd = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td valign=top>Customer Address</td>\n\t\t\t\t<td valign=center>" . nl2br($cust['addr1']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer VAT Number</td>\n\t\t\t\t<td>{$cust['vatnum']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Customer Balance</td>\n\t\t\t\t<td nowrap='t'>\n\t\t\t\t\t" . CUR . " {$cust['balance']}\n\t\t\t\t\t<a href='javascript: printer(\"cust-stmnt.php?cusnum={$cusnum}&print=t\");'>Print Statement</a>\n\t\t\t\t</td>\n\t\t\t</tr>";
        $pc = "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Amount On Credit</td>\n\t\t\t<td nowrap='t'>\n\t\t\t\t<input size='12' type='text' name='pcredit' id='pcredit' value='{$inv['pcredit']}' onchange='ptot_update();'>\n\t\t\t\t<input type='button' value='&laquo Total' onclick='paytotal(\"pcredit\");' />\n\t\t\t</td>\n\t\t</tr>";
        if ($line_count > 0) {
            $recvpay = "";
        } else {
            $recvpay = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='2' align='center'><input type='submit' name='recvpay' id='recvpay' onclick='return ptot_recvpay();' value='Receive Payment: " . CUR . " " . sprint($inv["pcc"] + $inv["pcheque"] + $inv["pcash"]) . "' /></td>\n\t\t\t</tr>";
        }
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    if (!isset($des)) {
        $des = "";
    }
    if (isset($sel_frm) && $sel_frm == "stkdes") {
        $sel_frm_cod = "";
        $sel_frm_des = "checked";
    } else {
        $sel_frm_cod = "checked";
        $sel_frm_des = "";
    }
    if (!isset($recvpay)) {
        $recvpay = "";
    }
    if (empty($inv["comm"])) {
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_POS_COMMENTS'";
        $rslt = db_exec($sql) or errDie("Unable to retrieve default comments from Cubit.");
        $inv["comm"] = base64_decode(pg_fetch_result($rslt, 0));
    }
    /* -- Final Layout -- */
    $details = "\n\t<script language=\"JavaScript\"><!--\n\t\tvar windowReference;\n\n\tfunction openRFPopup() {\n\t\twindowReference = window.open('rfid_batch.php?invid={$invid}','windowName','height=500,width=700,toolbar=no,menubar=no,scrollbars=no');\n\t\tif (!windowReference.opener)\n\t\t\twindowReference.opener = self;\n\t\t}\n\t//--></script>\n\n\t<center><h3>New Point of Sale Invoice</h3>\n\t<form method='POST' name='formName'>\n\t<input type='hidden' name='key' value='update' />\n\t<input type='hidden' name='invid' value='{$invid}' />\n\t<input type='hidden' name='SCROLL' value='yes'>\n\t</form>\n\t<script>\n\tfunction ptot_recvpay() {\n\t\tif (ptot_amt() > 0) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\talert('Enter amounts received by customer above.');\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tfunction pfld_num(fn) {\n\t\ti = getObject(fn).value;\n\n\t\tif (i) {\n\t\t\treturn parseFloat(i);\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\tfunction ptot_amt(nocredit) {\n\t\ti = pfld_num('pcash');\n\t\ti += pfld_num('pcc');\n\t\ti += pfld_num('pcheque');\n\n\t\tif (!nocredit && getObject('pcredit')) {\n\t\t\ti += pfld_num('pcredit');\n\t\t}\n\n\t\treturn i.toFixed(2);\n\t}\n\n\tfunction ptot_update() {\n\t\tgetObject('ptot').innerHTML = '" . CUR . " ' + ptot_amt();\n\n\t\tif (o = getObject('recvpay')) {\n\t\t\to.value = 'Receive Payment: " . CUR . " ' + ptot_amt(true);\n\t\t}\n\t}\n\n\tfunction paytotal(id) {\n\t\tgetObject('pcash').value = '0.00';\n\t\tgetObject('pcc').value = '0.00';\n\t\tgetObject('pcheque').value = '0.00';\n\t\tif (getObject('pcredit')) getObject('pcredit').value = '0.00';\n\n\t\tgetObject(id).value = getObject('itotal').value;\n\n\t\tptot_update();\n\t}\n\t</script>\n\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t<input type='hidden' name='key' value='update'>\n\t\t<input type='hidden' name='invid' value='{$invid}'>\n\t\t<input type='hidden' name='stkerr' value='{$stkerr}'>\n\t\t<input type='hidden' id='itotal' value='{$TOTAL}' />\n\t\t<input type='hidden' name='prev_cusnum' value='{$cusnum}' />\n\t\t<input type='hidden' name='SCROLL' value='yes'>\n\t<table " . TMPL_tblDflts . " width='95%'>\n \t\t<tr>\n \t\t\t<td valign='top'>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Department</td>\n\t\t\t\t\t\t<td valign='center'>{$depts}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Customer</td>\n\t\t\t\t\t\t<td valign='center'>{$customers}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t{$cd}\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Customer Telephone Number</td>\n\t\t\t\t\t\t<td valign='center'><input type='text' size='20' name='telno' value='{$inv['telno']}'></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Customer Order number</td>\n\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='cordno' value='{$cordno}'></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th colspan='2'>Point of Sale</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Barcode</td>\n\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t<input type='text' size='13' name='bar' value=''>\n\t\t\t\t\t\t\t<input type='button' onClick='javascript:openRFPopup();' value='RFID Batch'>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th colspan='2'>Options</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Select Using</td>\n\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}> 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</tr>\n\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Stock Filter</td>\n\t\t\t\t\t\t<td><input type='text' size='13' name='des' value='{$des}'> <input type='submit' value='Search'> <input type='submit' name='des' value='Show All'></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t\t<td valign='top' align='right'>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th colspan='2'>Invoice Details</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Invoice No.</td>\n\t\t\t\t\t\t<td valign='center'>{$inv['invid']}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Sales Order No.</td>\n\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='ordno' value='{$inv['ordno']}'></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Invoice Date</td>\n\t\t\t\t\t\t<td valign='center' nowrap='t'>" . mkDateSelect("pinv", $pinv_year, $pinv_month, $pinv_day) . "</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td nowrap='t'>VAT Inclusive</td>\n\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</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Sales Person</td>\n\t\t\t\t\t\t{$sales}\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Trade Discount</td>\n\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='traddisc' value='{$inv['traddisc']}'>%</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Delivery Charge</td>\n\t\t\t\t\t\t<td valign='center'><input type='text' size='7' name='delchrg' value='{$inv['delchrg']}'>{$Vatcodes}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th colspan='2'>Payment Details </th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>User</td>\n\t\t\t\t\t\t<td><input type='hidden' name='user' value='" . USER_NAME . "'>" . USER_NAME . "</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td nowrap='t'>Amount Paid Cash</td>\n\t\t\t\t\t\t<td nowrap='t'>\n\t\t\t\t\t\t\t<input size='12' type='text' name='pcash' id='pcash' value='{$inv['pcash']}' onchange='ptot_update();'>\n\t\t\t\t\t\t\t<input type='button' value='&laquo Total' onclick='paytotal(\"pcash\");' />\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td nowrap='t'>Amount Paid Cheque</td>\n\t\t\t\t\t\t<td nowrap='t'>\n\t\t\t\t\t\t\t<input size='12' type='text' name='pcheque' id='pcheque' value='{$inv['pcheque']}' onchange='ptot_update();'>\n\t\t\t\t\t\t\t<input type='button' value='&laquo Total' onclick='paytotal(\"pcheque\");' />\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td nowrap='t'>Amount Paid Credit Card</td>\n\t\t\t\t\t\t<td nowrap='t'>\n\t\t\t\t\t\t\t<input size='12' type='text' name='pcc' id='pcc' value='{$inv['pcc']}' onchange='ptot_update();'>\n\t\t\t\t\t\t\t<input type='button' value='&laquo Total' onclick='paytotal(\"pcc\");' />\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t{$recvpay}\n\t\t\t\t\t{$pc}\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td nowrap='t'>Total Covered</td>\n\t\t\t\t\t\t<td nowrap='t' id='ptot'>" . CUR . " " . sprint($inv["pcash"] + $inv["pcheque"] + $inv["pcc"] + $inv["pcredit"]) . "</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr><td><br></td></tr>\n\t\t<tr>\n\t\t\t<td colspan='2'>{$products}</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td width='70%' valign='top'>\n\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td rowspan='2'>" . mkQuickLinks(ql("pos-invoice-new-no-neg.php", "New POS Invoice"), ql("pos-invoice-list.php", "View POS Invoices"), ql("customers-new.php", "New Customer")) . "\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<th width='30%'>Comments</th>\n\t\t\t\t\t\t<td rowspan='5' valign='top' width='40%'>{$error}</td></tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td rowspan='4' align='center' valign='top'><textarea name='comm' rows='4' cols='20'>{$inv['comm']}</textarea></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t\t<td align='right' valign='top' width='30%'>\n\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>SUBTOTAL</td>\n\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</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Trade Discount</td>\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$inv['discount']}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Delivery Charge</td>\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$inv['delivery']}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><b>VAT {$vat14}</b></td>\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$VAT}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t<td align='right'>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t{$rd}\n\t\t\t\t</table>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td align='right'><input name='diffwhBtn' type='submit' value='Different Store'> | <input name='addprodBtn' type='submit' value='Add Product'>| <input name='addnon' type='submit' value='Add Non stock Product'>{$save} </td>\n\t\t\t<td>| <input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t</tr>\n\t</table>\n\t<a name='bottom'>\n\t</form>\n\t</center>";
    return $details;
}
function details($_POST, $error = "")
{
    if (PRD_STATE == 'p') {
        return "<br><li class=err> - Error : You cannot acces this function when you are using a closed period.<br><br></li>";
    }
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($invid)) {
        $v->isOk($invid, "num", 1, 20, "Invalid invoice 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"];
        }
        $confirm .= "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    if (isset($deptid)) {
        db_connect();
        # Query server for customer info
        $sql = "SELECT cusnum,cusname,surname FROM customers WHERE deptid = '{$deptid}' AND location != 'int' AND lower(surname) LIKE lower('{$letters}%') AND blocked != 'yes' 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.";
            return view_err($_POST, $err);
        }
    }
    if (!isset($invid)) {
        $invid = create_dummy($deptid);
        $stkerr = "0,0";
    }
    if (!isset($done)) {
        $done = "";
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li class=err>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    # Check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class=err> Error : Invoice number <b>{$invid}</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 = '{$inv['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 Customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' AND location != 'int' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    if (pg_numrows($custRslt) < 1) {
        db_connect();
        # Query server for customer info
        $sql = "SELECT cusnum,cusname,surname FROM customers WHERE deptid = '{$inv['deptid']}' AND location != 'int' AND lower(surname) LIKE lower('{$letters}%') AND blocked != 'yes' 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.";
            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);
        $sql = "SELECT cusnum, cusname, surname FROM customers WHERE deptid = '{$inv['deptid']}' AND location != 'int' AND lower(surname) LIKE lower('{$letters}%') AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
        $cusRslt = db_exec($sql) or errDie("Unable to view customers");
        # Moarn if customer account has been blocked
        if ($cust['blocked'] == 'yes') {
            $error .= "<li class=err>Error : Selected customer account has been blocked.";
        }
        // $customers = "<input type=hidden name=cusnum value='$cust[cusnum]'>$cust[cusname]  $cust[surname]";
        $cusnum = $cust['cusnum'];
        $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
        // $customers .= "<option value='-S' selected>Select Customer</option>";
        while ($cus = pg_fetch_array($cusRslt)) {
            $sel = "";
            if ($cust['cusnum'] == $cus['cusnum']) {
                $sel = "selected";
            }
            $customers .= "<option value='{$cus['cusnum']}' {$sel}>{$cus['cusname']} {$cus['surname']}</option>";
        }
        $customers .= "</select>";
    }
    /* --- 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.";
    } 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>";
    # 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.";
    } else {
        $salesps = "<select name='salespn'>";
        while ($salesp = pg_fetch_array($salespRslt)) {
            if ($salesp['salesp'] == $inv['salespn']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $salesps .= "<option value='{$salesp['salesp']}' {$sel}>{$salesp['salesp']}</option>";
        }
        $salesps .= "</select>";
    }
    # Days drop downs
    $days = array("0" => "0", "30" => "30", "60" => "60", "90" => "90", "120" => "120");
    $termssel = extlib_cpsel("terms", $days, $inv['terms']);
    # Keep the charge vat option stable
    if ($inv['chrgvat'] == "inc") {
        $chin = "checked=yes";
        $chex = "";
        $chno = "";
    } elseif ($inv['chrgvat'] == "exc") {
        $chin = "";
        $chex = "checked=yes";
        $chno = "";
    } else {
        $chin = "";
        $chex = "";
        $chno = "checked=yes";
    }
    # Format date
    list($oyear, $omon, $oday) = explode("-", $inv['odate']);
    /* --- End Drop Downs --- */
    /* --- Start Products Display --- */
    # Select all products
    $products = "\n\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0 width=100%>\n\t<tr><th>STORE</th><th>ITEM NUMBER</th><th>SERIAL NO.</th><th>DESCRIPTION</th><th>QTY</th><th>UNIT PRICE</th><th>UNIT DISCOUNT</th><th>AMOUNT</th><th>Remove</th><tr>";
    # get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' 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);
        # Serial number
        if ($stk['serd'] == 'yes' && $inv['serd'] == 'n') {
            $sers = ext_getavserials($stkd['stkid']);
            $sernos = "<select class='width : 15' name='sernos[]'>";
            foreach ($sers as $skey => $ser) {
                $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
            }
            $sernos .= "</select>";
        } else {
            $sernos = "<input type=hidden name=sernos[] value='{$stkd['serno']}'>{$stkd['serno']}";
        }
        # Input qty if not serialised
        $qtyin = "<input type=text size=3 name=qtys[] value='{$stkd['qty']}'>";
        if ($stk['serd'] == 'yes') {
            $qtyin = "<input type=hidden size=3 name=qtys[] value='{$stkd['qty']}'>{$stkd['qty']}";
        }
        # check permissions
        if (perm("invoice-unitcost-edit.php")) {
            $viewcost = "<input type=text size=8 name=unitcost[] value='{$stkd['unitcost']}'>";
        } else {
            $viewcost = "<input type=hidden size=8 name=unitcost[] value='{$stkd['unitcost']}'>{$stkd['unitcost']}";
        }
        # 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=stkids[] value='{$stkd['stkid']}'><a href='#bottom' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td><td>{$sernos}</td><td>" . extlib_rstr($stk['stkdes'], 30) . "</td><td>{$qtyin}</td><td>{$viewcost}</td><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><td><input type=hidden name=amt[] value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td><td><input type=checkbox name=remprod[] value='{$key}'><input type=hidden name=SCROLL value=yes></td></tr>";
        $key++;
    }
    # Look above(remprod keys)
    $keyy = $key;
    # Look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    } else {
        $SCROLL = "yes";
    }
    # 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 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);
                if ($stk['serd'] == 'yes') {
                    $sers = ext_getavserials($stkidss[$key]);
                    $sernos = "<select class='width : 15'name='sernos[]' onChange='javascript:document.form.submit();'>";
                    foreach ($sers as $skey => $ser) {
                        $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
                    }
                    $sernos .= "</select>";
                } else {
                    $sernos = "<input type=hidden name=sernos[] value=''>";
                }
                # 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]);
                # Input qty if not serialised
                $qtyin = "<input type=text size=3 name=qtys[] value='{$qtyss[$key]}'>";
                if ($stk['serd'] == 'yes') {
                    $qtyin = "<input type=hidden size=3 name=qtys[] value='{$qtyss[$key]}'>{$qtyss[$key]}";
                }
                # Check permissions
                if (perm("invoice-unitcost-edit.php")) {
                    $viewcost = "<input type=text size=8 name=unitcost[] value='{$stk['selamt']}'>";
                } else {
                    $viewcost = "<input type=hidden size=8 name=unitcost[] value='{$stk['selamt']}'>{$stk['selamt']}";
                }
                # Put in selected warehouse and stock
                $products .= "<tr class='bg-odd'><td><input type=hidden name=whids[] value='{$whid}'>{$wh['whname']}</td><td><input type=hidden name=stkids[] value='{$stk['stkid']}'><a href='#bottom' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td><td>{$sernos}</td><td>" . extlib_rstr($stk['stkdes'], 30) . "</td><td>{$qtyin}</td><td>{$viewcost}</td><td><input type=text size=4 name=disc[] value='{$discs[$key]}'> OR <input type=text size=4 name=discp[] value='{$discps[$key]}' maxlength=5>%</td><td><input type=hidden name=amt[] value='{$amt[$key]}'> " . CUR . " {$amt[$key]}</td><td><input type=checkbox name=remprod[] value='{$keyy}'></td></tr>";
                $keyy++;
            } 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);
                    if (isset($ria) and $ria != "") {
                        $len = strlen($ria);
                        $Wh = "AND lower(substr(stkcod,1,'{$len}'))=lower('{$ria}')";
                    } else {
                        $Wh = "";
                        $ria = "";
                    }
                    # get stock on this warehouse
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE whid = '{$whid}' AND blocked = 'n' 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 warehouse.";
                        continue;
                    }
                    if (pg_numrows($stkRslt) == 1) {
                        $ex = "selected";
                    } else {
                        $ex = "";
                    }
                    $stks = "<select class='width : 15'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']} (" . ($stk['units'] - $stk['alloc']) . ")</option>";
                    }
                    $stks .= "</select> ";
                    # put in drop down and warehouse
                    $products .= "<tr class='bg-odd'><td><input type=hidden name=whidss[] value='{$whid}'>{$wh['whname']}</td><td>{$stks}</td><td> </td><td> </td><td><input type=hidden size=3 name='qtyss[]'  value='1'>1</td><td> </td><td><input type=text size=4 name=discs[] value='0'> OR <input type=text size=4 name=discps[] value='0' maxlength=5>%</td><td><input type=hidden name=amts[] value='0.00'>" . CUR . " 0.00</td><td></td></tr>";
                }
            }
        }
    } else {
        if (!isset($diffwhBtn)) {
            # 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);
                if (isset($ria) and $ria != "") {
                    $len = strlen($ria);
                    $Wh = "AND lower(substr(stkcod,1,'{$len}'))=lower('{$ria}')";
                } else {
                    $Wh = "";
                    $ria = "";
                }
                # get stock on this warehouse
                db_connect();
                $sql = "SELECT * FROM stock WHERE whid = '{$whid}' AND blocked = 'n' 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 store.";
                    //ontinue;
                }
                $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']} (" . ($stk['units'] - $stk['alloc']) . ")</option>";
                }
                $stks .= "</select> ";
                $products .= "<tr class='bg-odd'><td><input type=hidden name=whidss[] value='{$whid}'>{$wh['whname']}</td><td>{$stks}</td><td> </td><td></td><td><input type=hidden size=3 name=qtyss[] value='1'>1</td><td> </td><td><input type=text size=4 name=discs[] value='0'> OR <input type=text size=4 name=discps[] value='0' maxlength=5>%</td><td>" . CUR . " 0.00</td><td></td></tr>";
            } else {
                $products .= "<tr class='bg-odd'><td>{$whs}</td><td> </td><td></td><td> </td><td> </td><td> </td><td><input type=text size=4 name=discs[] value='0'> OR <input type=text size=4 name=discps[] value='0' maxlength=5>%</td><td>" . CUR . " 0.00</td><td></td></tr>";
            }
        }
    }
    /* -- start Listeners -- */
    if (isset($diffwhBtn)) {
        $products .= "<tr class='bg-odd'><td>{$whs}</td><td> </td><td></td><td> </td><td> </td><td> </td><td><input type=text size=4 name=discs[] value='0'> OR <input type=text size=4 name=discps[] value='0' maxlength=5>%</td><td>" . CUR . " 0.00</td><td></td></tr>";
    }
    /* -- End Listeners -- */
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    //print "<br>TOTAL:$inv[total]  VAT:$inv[vat]<br>";
    # Calculate tradediscm
    if ($inv['traddisc'] > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * $inv['total']);
    } else {
        $traddiscm = "0.00";
    }
    $VATP = TAX_VAT;
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    /* --- End Some calculations --- */
    /*--- Start checks --- */
    # check only if the customer is selected
    if (isset($cusnum) && $cusnum != "-S") {
        #check againg credit limit
        if ($TOTAL + $cust['balance'] > $cust['credlimit']) {
            $error .= "<li class=err>Warning : Customers Credit limit of <b>" . CUR . " {$cust['credlimit']}</b> has been exceeded";
            # Check permissions
            if (!perm("invoice-limit-override.php")) {
                $done = "";
            }
        }
        $avcred = $cust['credlimit'] - $cust['balance'];
    } else {
        $avcred = "0.00";
    }
    /*--- Start checks --- */
    /* -- Final Layout -- */
    $details = "<center><h3>New Invoice</h3>\n\t<form action='" . SELF . "' method=post name=form>\n\t<input type=hidden name=key value=update>\n\t<input type=hidden name=invid value='{$invid}'>\n\t<input type=hidden name=letters value='{$letters}'>\n\t<input type=hidden name=stkerr value='{$stkerr}'>\n\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0 width=95%>\n \t<tr><td valign=top width=50%>\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0>\n\t\t\t<tr><th colspan=2> Customer Details </th></tr>\n\t\t\t<tr class='bg-odd'><td>Department</td><td valign=center>{$dept['deptname']}</td></tr>\n\t\t\t<tr class='bg-even'><td>Account No.</td><td valign=center>{$cust['accno']}</td></tr>\n\t\t\t<tr class='bg-odd'><td>Customer</td><td valign=center>{$customers}</td></tr>\n\t\t\t<tr class='bg-even'><td valign=top>Customer Address</td><td valign=center>" . nl2br($cust['addr1']) . "</td></tr>\n\t\t\t<tr class='bg-odd'><td>Customer Order number</td><td valign=center><input type=text size=10 name=cordno value='{$inv['cordno']}'></td></tr>\n\t\t\t<tr class='bg-even'><td>Customer Vat Number</td><td>{$cust['vatnum']}</td></tr>\n\t\t\t<tr><th colspan=2>Point of Sale</th></tr>\n\t\t\t<tr class='bg-even'><td>Barcode</td><td><input type=text size=13 name=bar value=''></td></tr>\n\t\t\t<tr class='bg-odd' " . ass("Type the first letters of the stock code you are looking for.") . "><td>Stock Filter</td><td><input type=text size=13 name=ria value='{$ria}' onkeyup='javasript:predict()'></td></tr>\n\t\t</table>\n\t</td><td valign=top align=right width=50%>\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0>\n\t\t\t<tr><th colspan=2> Invoice Details </th></tr>\n\t\t\t<tr class='bg-odd'><td>Invoice No.</td><td valign=center>TI {$inv['invid']}</td></tr>\n\t\t\t<tr class='bg-even'><td>Proforma Inv No.</td><td valign=center><input type=text size=5 name=docref value='{$inv['docref']}'></td></tr>\n\t\t\t<tr class='bg-odd'><td>Sales Order No.</td><td valign=center><input type=text size=5 name=ordno value='{$inv['ordno']}'></td></tr>\n\t\t\t<tr class='bg-even'><td>VAT Inclusive</td><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}> Excempt From Vat<input type=radio size=7 name=chrgvat value='nov' {$chno}></td></tr>\n\t\t\t<tr class='bg-odd'><td>Terms</td><td valign=center>{$termssel} Days</td></tr>\n\t\t\t<tr class='bg-even'><td>Sales Person</td><td valign=center>{$salesps}</td></tr>\n\t\t\t<tr class='bg-odd'><td>Invoice Date</td><td valign=center><table><tr><td><input type=text size=2 name=oday maxlength=2 value='{$oday}'></td><td>-</td><td><input type=text size=2 name=omon maxlength=2 value='{$omon}'></td><td>-</td><td><input type=text size=4 name=oyear maxlength=4 value='{$oyear}'></td><td></tr></table></td></tr>\n\t\t\t<tr class='bg-even'><td>Available Credit</td><td>" . CUR . " {$avcred}</td></tr>\n\t\t\t<tr class='bg-odd'><td>Trade Discount</td><td valign=center><input type=text size=5 name=traddisc value='{$inv['traddisc']}'>%</td></tr>\n\t\t\t<tr class='bg-even'><td>Delivery Charge</td><td valign=center><input type=text size=7 name=delchrg value='{$inv['delchrg']}'></td></tr>\n\t\t</table>\n\t</td></tr>\n\t<tr><td><br></td></tr>\n\t<tr><td colspan=2>{$products}</td></tr>\n\t<tr><td>\n\t\t<p>\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=100%>\n\t\t\t<tr><th width=25%>Quick Links</th><th width=25%>Comments</th><td rowspan=5 valign=top width=50%>{$error}</td></tr>\n\t\t\t<tr><td class='bg-odd'><a href='cust-credit-stockinv.php'>New Invoice</a></td><td class='bg-odd' rowspan=4 align=center valign=top><textarea name=comm rows=4 cols=20>{$inv['comm']}</textarea></td></tr>\n\t\t\t<tr class='bg-odd'><td><a href='invoice-view.php'>View Invoices</a></td></tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t<tr class='bg-odd'><td><a href='main.php'>Main Menu</a></td></tr>\n\t\t</table>\n\t</td><td align=right valign=top>\n\t\t<table cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' border=0 width=50%>\n\t\t\t<tr class='bg-odd'><td>SUBTOTAL</td><td align=right>" . CUR . " <input type=hidden name=SUBTOT value='{$SUBTOT}'>{$SUBTOT}</td></tr>\n\t\t\t<tr class='bg-even'><td>Trade Discount</td><td align=right>" . CUR . " {$inv['discount']}</td></tr>\n\t\t\t<tr class='bg-odd'><td>Delivery Charge</td><td align=right>" . CUR . " {$inv['delivery']}</td></tr>\n\t\t\t<tr class='bg-even'><td><b>VAT @ {$VATP}%</b></td><td align=right>" . CUR . " {$VAT}</td></tr>\n\t\t\t<tr class='bg-odd'><th>GRAND TOTAL</th><td align=right>" . CUR . " {$TOTAL}</td></tr>\n\t\t</table>\n\t</td></tr>\n\t<tr><td align=right><input type=button value='&laquo Back' onClick='javascript:history.back()'> | <input name=diffwhBtn type=submit value='Different Store'> | <input name=addprodBtn type=submit value='Add Product'> | <input type=submit name='saveBtn' value='Save'> </td><td>| <input type=submit name='upBtn' value='Update'>{$done}</td></tr>\n\t</table><a name=bottom>\n\t</form></center>";
    return $details;
}
function confirm($_POST)
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($stkid, "num", 1, 50, "Invalid stock id.");
    $v->isOk($whid, "num", 1, 50, "Invalid stock id.");
    $v->isOk($tipo, "string", 1, 50, "Invalid type.");
    $v->isOk($det, "string", 0, 255, "Invalid Details.");
    $v->isOk($unitnum, "num", 1, 50, "Invalid number of units.");
    if ($tipo == 'Increase') {
        $v->isOk($cost, "float", 1, 50, "Invalid cost amount per unit.");
    } else {
        $v->isOk($cost, "float", 0, 50, "Invalid cost amount per unit.");
    }
    $v->isOk($cacc, "num", 1, 50, "Invalid contra account.");
    $date = $date_year . "-" . $date_month . "-" . $date_day;
    if (!checkdate($date_month, $date_day, $date_year)) {
        $v->isOk($date, "num", 1, 1, "Invalid date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li>";
        }
        return $confirm;
    }
    # Select Stock
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to access database.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.</li>";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    # Get stock vars
    extract($stk);
    if ($tipo == 'Decrease') {
        $cost = sprint($csprice);
    }
    # 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 ledger account name
    core_connect();
    $sql = "SELECT accname FROM accounts WHERE accid = '{$cacc}' AND div = '" . USER_DIV . "'";
    $caccRslt = db_exec($sql);
    $caccd = pg_fetch_array($caccRslt);
    $serials = "";
    if ($serd == 'yes' && $tipo == 'Decrease') {
        $sers = ext_getavserials($stkid);
        $serials = "<tr><th colspan='2'>Units Serial Numbers</th></tr>";
        $sernos = "<select name='sernos[]'>";
        foreach ($sers as $skey => $ser) {
            $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
        }
        $sernos .= "</select>";
        for ($i = 0; $i < $unitnum; $i++) {
            $serials .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td colspan='2' align='center'>{$sernos}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t";
        }
    }
    $totcost = sprint($cost * $unitnum);
    // Layout
    $confirm = "\n\t\t\t\t<h3>Stock Balance Transaction</h3>\n\t\t\t\t<h4>Confirm entry</h4>\n\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t\t<input type='hidden' name='key' value='write'>\n\t\t\t\t\t<input type='hidden' name='whid' value='{$whid}'>\n\t\t\t\t\t<input type='hidden' name='stkid' value='{$stkid}'>\n\t\t\t\t\t<input type='hidden' name='tipo' value='{$tipo}'>\n\t\t\t\t\t<input type='hidden' name='det' value='{$det}'>\n\t\t\t\t\t<input type='hidden' name='unitnum' value='{$unitnum}'>\n\t\t\t\t\t<input type='hidden' name='cost' value='{$cost}'>\n\t\t\t\t\t<input type='hidden' name='cacc' value='{$cacc}'>\n\t\t\t\t\t<input type='hidden' name='date' value='{$date}'>\n\t\t\t\t\t<input type='hidden' name='date_day' value='{$date_day}'>\n\t\t\t\t\t<input type='hidden' name='date_month' value='{$date_month}'>\n\t\t\t\t\t<input type='hidden' name='date_year' value='{$date_year}'>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th width='40%'>Field</th>\n\t\t\t\t\t\t<th width='60%'>Value</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Store</td>\n\t\t\t\t\t\t<td>{$wh['whname']}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Stock code</td>\n\t\t\t\t\t\t<td>{$stkcod}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Stock description</td>\n\t\t\t\t\t\t<td>" . nl2br($stkdes) . "</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Type</td>\n\t\t\t\t\t\t<td>{$tipo}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Date</td>\n\t\t\t\t\t\t<td>{$date}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td valign='top'>Details</td>\n\t\t\t\t\t\t<td>" . nl2br($det) . "</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Number of Units</td>\n\t\t\t\t\t\t<td>{$unitnum}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Cost Amount per Unit</td>\n\t\t\t\t\t\t<td>" . CUR . " {$cost}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Total Cost Amount</td>\n\t\t\t\t\t\t<td>" . CUR . " {$totcost}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Contra Account</td>\n\t\t\t\t\t\t<td>{$caccd['accname']}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t{$serials}\n\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><input type='submit' name='back' value='&laquo; Correction'></td>\n\t\t\t\t\t\t<td align='right'><input type='submit' value='Write &raquo'></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</form>\n\t\t\t\t</table>" . mkQuickLinks(ql("stock-add.php", "Add Stock"), ql("stock-view.php", "View Stock"));
    return $confirm;
}
function details($_POST, $error = "")
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($invid)) {
        $v->isOk($invid, "num", 1, 20, "Invalid invoice 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($deptid)) {
        db_connect();
        # Query server for customer info
        $sql = "SELECT cusnum,cusname,surname FROM customers WHERE deptid = '{$deptid}' AND location = 'int' AND lower(surname) LIKE lower('{$letters}%') AND blocked != 'yes' 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);
        }
    }
    if (!isset($invid)) {
        $invid = create_dummy($deptid);
        $stkerr = "0,0";
    }
    if (!isset($done)) {
        $done = "";
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li class='err'>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    # Check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</li>";
        $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    $currs = getSymbol($inv['fcid']);
    # Get department
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
    $deptRslt = db_exec($sql);
    if (pg_numrows($deptRslt) < 1) {
        $dept['deptname'] = "<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 = '{$inv['cusnum']}'  AND location = 'int' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    if (pg_numrows($custRslt) < 1) {
        db_connect();
        # Query server for customer info
        $sql = "SELECT cusnum,cusname,surname FROM customers WHERE deptid = '{$inv['deptid']}' AND location = 'int' AND lower(surname) LIKE lower('{$letters}%') AND blocked != 'yes' 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);
        $sql = "SELECT cusnum, cusname, surname FROM customers WHERE deptid = '{$inv['deptid']}' AND location = 'int' AND lower(surname) LIKE lower('{$letters}%') AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
        $cusRslt = db_exec($sql) or errDie("Unable to view customers");
        # Moarn if customer account has been blocked
        if ($cust['blocked'] == 'yes') {
            $error .= "<li class='err'>Error : Selected customer account has been blocked.";
        }
        // $customers = "<input type=hidden name=cusnum value='$cust[cusnum]'>$cust[cusname]  $cust[surname]";
        $cusnum = $cust['cusnum'];
        $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
        // $customers .= "<option value='-S' selected>Select Customer</option>";
        while ($cus = pg_fetch_array($cusRslt)) {
            $sel = "";
            if ($cust['cusnum'] == $cus['cusnum']) {
                $sel = "selected";
            }
            $customers .= "<option value='{$cus['cusnum']}' {$sel}>{$cus['cusname']} {$cus['surname']}</option>";
        }
        $customers .= "</select>";
    }
    /* --- 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>";
    # 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'] == $inv['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, $inv['terms']);
    # Keep the charge vat option stable
    if ($inv['chrgvat'] == "inc") {
        $chin = "checked=yes";
        $chex = "";
        $chno = "";
    } elseif ($inv['chrgvat'] == "exc") {
        $chin = "";
        $chex = "checked=yes";
        $chno = "";
    } else {
        $chin = "";
        $chex = "";
        $chno = "checked=yes";
    }
    # Format date
    list($o_year, $o_month, $o_day) = explode("-", $inv['odate']);
    /* --- 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>SERIAL NO.</th>\n\t\t\t\t<th>DESCRIPTION</th>\n\t\t\t\t<th>QTY</th>\n\t\t\t\t<th colspan='2'>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 invoice
    db_connect();
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' 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);
        # Serial number
        if ($stk['serd'] == 'yes' && $inv['serd'] == 'n') {
            $sers = ext_getavserials($stkd['stkid']);
            $sernos = "<select class='width : 15' name='sernos[]'>";
            foreach ($sers as $skey => $ser) {
                $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
            }
            $sernos .= "</select>";
        } else {
            $sernos = "<input type='hidden' name='sernos[]' value='{$stkd['serno']}'>{$stkd['serno']}";
        }
        # Input qty if not serialised
        $qtyin = "<input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'>";
        if ($stk['serd'] == 'yes') {
            $qtyin = "<input type='hidden' size='3' name='qtys[]' value='{$stkd['qty']}'>{$stkd['qty']}";
        }
        # check permissions
        if (perm("invoice-unitcost-edit.php")) {
            $viewcost = "<input type='text' size='8' name='unitcost[]' value='{$stkd['funitcost']}'>";
            $cunitcost = "<input type='text' size='8' name='cunitcost[]' value='{$stkd['unitcost']}'>";
        } else {
            $viewcost = "<input type='hidden' size='8' name='unitcost[]' value='{$stkd['funitcost']}'>{$stkd['funitcost']}";
            $cunitcost = "<input type='hidden' size='8' name='cunitcost[]' value='{$stkd['unitcost']}'>{$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<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>";
        # Put in product
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><input type='hidden' name='whids[]' value='{$stkd['whid']}'>{$wh['whname']}</td>\n\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'><a href='#bottom' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t<td>{$sernos}</td>\n\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t<td>" . CUR . " {$viewcost}</td>\n\t\t\t\t<td>{$inv['currency']} {$cunitcost}</td>\n\t\t\t\t<td>{$inv['currency']}<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<td><input type='hidden' name='amt[]' value='{$stkd['amt']}'> {$inv['currency']} {$stkd['amt']}</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 = "";
    } else {
        $SCROLL = "yes";
    }
    # 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 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);
                if ($stk['serd'] == 'yes') {
                    $sers = ext_getavserials($stkidss[$key]);
                    $sernos = "<select class='width : 15'name='sernos[]' onChange='javascript:document.form.submit();'>";
                    foreach ($sers as $skey => $ser) {
                        $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
                    }
                    $sernos .= "</select>";
                } else {
                    $sernos = "<input type='hidden' name='sernos[]' value=''>";
                }
                # 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]);
                $stk['cselamt'] = sprint($stk['selamt'] / $inv['xrate']);
                # Input qty if not serialised
                $qtyin = "<input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'>";
                if ($stk['serd'] == 'yes') {
                    $qtyin = "<input type='hidden' size='3' name='qtys[]' value='{$qtyss[$key]}'>{$qtyss[$key]}";
                }
                //				$stk['cselamt'] = sprint ($stk['cselamt']);
                $stk['selamt'] = sprint($stk['selamt']);
                # Check permissions
                if (perm("invoice-unitcost-edit.php")) {
                    $viewcost = "<input type='text' size='8' name='unitcost[]' value='{$stk['selamt']}'>";
                    $cunitcost = "<input type='text' size='8' name='cunitcost[]' value='{$stk['cselamt']}'>";
                } else {
                    $viewcost = "<input type='hidden' size='8' name='unitcost[]' value='{$stk['selamt']}'>{$stk['selamt']}";
                    $cunitcost = "<input type='hidden' size='8' name='cunitcost[]' value='{$stk['cselamt']}'>{$stk['cselamt']}";
                }
                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]);
                # Put in selected warehouse and stock
                $products .= "\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='#bottom' 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>{$sernos}</td>\n\t\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t\t<td>" . CUR . " {$viewcost}</td>\n\t\t\t\t\t\t<td>{$inv['currency']} {$cunitcost}</td>\n\t\t\t\t\t\t<td>{$inv['currency']}  <input type='text' size='4' name='disc[]' value='{$discs[$key]}'> OR <input type='text' size='4' name='discp[]' value='{$discps[$key]}' maxlength='5'>%</td>\n\t\t\t\t\t\t<td><input type='hidden' name='amt[]' value='{$amt[$key]}'> {$inv['currency']} {$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($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);
                    if (isset($ria) && $ria != "") {
                        $len = strlen($ria);
                        $Wh = "AND lower(substr(stkcod,1,'{$len}'))=lower('{$ria}')";
                    } else {
                        $Wh = "";
                        $ria = "";
                    }
                    # get stock on this warehouse
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE whid = '{$whid}' AND blocked = 'n' 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 warehouse.";
                        continue;
                    }
                    if (pg_numrows($stkRslt) == 1) {
                        $ex = "selected";
                    } else {
                        $ex = "";
                    }
                    $stks = "<select class='width : 15'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> ";
                    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<tr class='" . bg_class() . "'>\n\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<td>{$stks}</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='vatcodess' value='0'></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' size='3' name='qtyss[]'  value='1'>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>{$inv['currency']} <input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='amts[]' value='0.00'>{$inv['currency']} 0.00</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t</tr>";
                }
            }
        }
    } else {
        if (!isset($diffwhBtn)) {
            # 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);
                if (isset($ria) && $ria != "") {
                    $len = strlen($ria);
                    $Wh = "AND lower(substr(stkcod,1,'{$len}'))=lower('{$ria}')";
                } else {
                    $Wh = "";
                    $ria = "";
                }
                # get stock on this warehouse
                db_connect();
                $sql = "SELECT * FROM stock WHERE whid = '{$whid}' AND blocked = 'n' 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 store.</li>";
                    //ontinue;
                }
                $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\t<input type='hidden' name='vatcodess[]' value=''>\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td><input type='hidden' name='whidss[]' value='{$whid}'>{$wh['whname']}</td>\n\t\t\t\t\t\t<td>{$stks}</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><input type='hidden' size='3' name='qtyss[]' value='1'>1</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>{$inv['currency']} <input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>\n\t\t\t\t\t\t<td>{$inv['currency']} 0.00</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t</tr>";
            } else {
                $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> </td>\n\t\t\t\t\t\t<td>{$inv['currency']}<input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>\n\t\t\t\t\t\t<td>{$inv['currency']} 0.00</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t</tr>";
            }
        }
    }
    /* -- start Listeners -- */
    if (isset($diffwhBtn)) {
        $products .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$whs}</td>\n\t\t\t\t<td> </td>\n\t\t\t\t<td> </td>\n\t\t\t\t<td> </td>\n\t\t\t\t<td> </td>\n\t\t\t\t<td> </td>\n\t\t\t\t<td> </td>\n\t\t\t\t<td> </td>\n\t\t\t\t<td>{$inv['currency']}<input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>\n\t\t\t\t<td>{$inv['currency']} 0.00</td>\n\t\t\t\t<td></td>\n\t\t\t</tr>";
    }
    /* -- End Listeners -- */
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    if ($inv['traddisc'] > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * ($SUBTOT + $inv['delchrg']));
    } else {
        $traddiscm = "0.00";
    }
    $VATP = TAX_VAT;
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    /* --- End Some calculations --- */
    /*--- Start checks --- */
    # check only if the customer is selected
    if (isset($cusnum) && $cusnum != "-S") {
        db_connect();
        #check againg credit limit
        if ($TOTAL + $cust['balance'] > $cust['credlimit']) {
            $error .= "<li class='err'>Warning : Customers Credit limit of <b>{$inv['currency']} {$cust['credlimit']}</b> has been exceeded";
            # Check permissions
            if (!perm("invoice-limit-override.php")) {
                $done = "";
            }
        }
        $avcred = $cust['credlimit'] - $cust['balance'];
    } else {
        $avcred = "0.00";
    }
    /*--- Start checks --- */
    $inv['delvat'] += 0;
    if ($inv['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $inv['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'] == $inv['delvat']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $Vatcodes .= "</select>";
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $chp = "checked";
    } else {
        $chp = "";
    }
    if (!isset($showvat)) {
        $showvat = TRUE;
    }
    if ($showvat == TRUE) {
        $vat14 = AT14;
    } else {
        $vat14 = "";
    }
    if (!isset($stkerr)) {
        $stkerr = "";
    }
    $avcred = sprint($avcred);
    /* -- Final Layout -- */
    $details = "\n\t\t<center>\n\t\t<h3>New International Invoice</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='invid' value='{$invid}'>\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<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td valign='top' width='50%'>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Department</td>\n\t\t\t\t\t\t\t\t<td valign='center'>{$dept['deptname']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Account No.</td>\n\t\t\t\t\t\t\t\t<td valign='center'>{$cust['accno']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Customer</td>\n\t\t\t\t\t\t\t\t<td valign='center'>{$customers}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td valign='top'>Customer Address</td>\n\t\t\t\t\t\t\t\t<td valign='center'>" . nl2br($cust['addr1']) . "</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Customer Order number</td>\n\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='10' name='cordno' value='{$inv['cordno']}'></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Customer Vat Number</td>\n\t\t\t\t\t\t\t\t<td>{$cust['vatnum']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th colspan='2'>Point of Sale</th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Barcode</td>\n\t\t\t\t\t\t\t\t<td><input type='text' size='13' name='bar' value=''></td>\n\t\t\t\t\t\t\t</tr>\n\t\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\t<td>Stock Filter</td>\n\t\t\t\t\t\t\t\t<td><input type='text' size='13' name='ria' value='{$ria}' onkeyup='javasript:predict()'></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Print Delivery Note</td>\n\t\t\t\t\t\t\t\t<td><input type='checkbox' name='printdel' {$chp}></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td valign='top' align='right' width='50%'>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th colspan='2'> Invoice Details </th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Invoice No.</td>\n\t\t\t\t\t\t\t\t<td valign='center'>TI {$inv['invid']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Proforma Inv No.</td>\n\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='docref' value='{$inv['docref']}'></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Sales Order No.</td>\n\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='ordno' value='{$inv['ordno']}'></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Foreign Currency</td>\n\t\t\t\t\t\t\t\t<td valign='center'>{$currs['symbol']} - {$currs['name']} &nbsp;&nbsp;Exchange rate " . CUR . " <input type='text' size='7' name='xrate' value='{$inv['xrate']}'></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\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\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Sales Person</td>\n\t\t\t\t\t\t\t\t<td valign='center'>{$salesps}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Invoice Date</td>\n\t\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("o", $o_year, $o_month, $o_day) . "</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Available Credit</td>\n\t\t\t\t\t\t\t\t<td>{$inv['currency']} {$avcred}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Trade Discount</td>\n\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='traddisc' value='{$inv['traddisc']}'>%</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Delivery Charge</td>\n\t\t\t\t\t\t\t\t<td valign='center'>{$inv['currency']}<input type='text' size='7' name='delchrg' value='{$inv['delchrg']}'>{$Vatcodes}</td>\n\t\t\t\t\t\t\t</tr>\n\t\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 . " width='100%'>\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%'>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() . "'><a href='cust-credit-stockinv.php'>New Invoice</a></td>\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'>{$inv['comm']}</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='invoice-view.php'>View Invoices</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' valign='top'>\n\t\t\t\t\t<table " . TMPL_tblDflts . " width='50%'>\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'>{$inv['currency']} <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'>{$inv['currency']} {$inv['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'>{$inv['currency']} {$inv['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></td>\n\t\t\t\t\t\t\t<td align='right'>{$inv['currency']} {$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'>{$inv['currency']} {$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='button' value='&laquo Back' onClick='javascript:history.back()'> | <input name='diffwhBtn' type='submit' value='Different Store'> | <input name='addprodBtn' type='submit' value='Add Product'> | <input type='submit' name='saveBtn' value='Save'> </td>\n\t\t\t\t<td>| <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>";
    return $details;
}
function details($_POST, $error = "")
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($invid)) {
        $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    }
    if (isset($letter)) {
        $v->isOk($letters, "string", 0, 5, "Invalid First 3 Letters.");
    }
    if (isset($deptid)) {
        $v->isOk($deptid, "num", 1, 20, "Invalid department number.");
    }
    if (isset($sel_frm)) {
        $v->isOk($sel_frm, "string", 6, 6, "Invalid select from selection.");
    }
    # display errors, if any
    if ($v->isError()) {
        $error = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $error .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $error . view_err($_POST);
    }
    if (isset($deptid) && isset($letters)) {
        db_connect();
        if ($deptid == "0") {
            $searchdept = "";
        } else {
            $searchdept = "deptid = '{$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 blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
        $custRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($custRslt) < 1) {
            $ajax_err = "<li class='err'>No customer names starting with <b>{$letters}</b> in database.</li>";
            //return view_err($_POST, $err);
        }
    }
    if (!isset($deptid)) {
        $deptid = 2;
    } else {
        if (isset($invid)) {
            db_conn("cubit");
            $sql = "UPDATE invoices SET deptid='{$deptid}' WHERE invid='{$invid}' AND deptid<>'{$deptid}'";
            db_exec($sql) or errDie("Error updating invoice department.");
        }
    }
    if (!isset($invid)) {
        $invid = create_dummy($deptid);
    }
    if (!isset($stkerr)) {
        $stkerr = "0,0";
    }
    if (!isset($done)) {
        $done = "";
    }
    if (!isset($cust_del_addr)) {
        $cust_del_addr = "";
    }
    if (!isset($sel_frm)) {
        $sel_frm = "stkcod";
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li class='err'>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    if (!isset($branch)) {
        $branch = $inv['branch'];
    }
    # Check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has already been printed.</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 = '{$inv['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
    if (isset($letters)) {
        db_connect();
        $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' AND location != 'int' AND div = '" . USER_DIV . "'";
        $custRslt = db_exec($sql) or errDie("Unable to view customer");
        if (pg_numrows($custRslt) < 1) {
            if ($inv['deptid'] == 0) {
                $searchdept = "";
            } else {
                $searchdept = "deptid = '{$inv['deptid']}' AND ";
            }
            # Query server for customer info
            $sql = "SELECT cusnum, cusname, surname, accno FROM customers WHERE {$searchdept} location != 'int' AND lower(surname) LIKE lower('{$letters}%') AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
            $custRslt = db_exec($sql) or errDie("Unable to view customers");
            if (pg_numrows($custRslt) < 1) {
                $ajax_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();'>";
                if (pg_numrows($custRslt) == 1) {
                    $inv['cusnum'] = pg_fetch_result($custRslt, 0, 0);
                } else {
                    $customers .= "<option value='-S' selected>Select Customer</option>";
                }
                while ($cust = pg_fetch_array($custRslt)) {
                    $customers .= "<option value='{$cust['cusnum']}'>{$cust['cusname']} {$cust['surname']} ({$cust['accno']})</option>";
                }
                $customers .= "</select>";
            }
            # Take care of the unset vars
            $cust['addr1'] = "";
            $cust['cusnum'] = "";
            $cust['vatnum'] = "";
            $cust['accno'] = "";
            $cust_del_addr = "";
            $branchdrop = "<input type='hidden' name='branch' value='0'>";
        } else {
            $cust = pg_fetch_array($custRslt);
            #override address
            if ($branch != 0) {
                $get_addr = "SELECT branch_descrip FROM customer_branches WHERE id = '{$branch}' AND div = '" . USER_DIV . "' LIMIT 1";
                $run_addr = db_exec($get_addr);
                if (pg_numrows($run_addr) < 1) {
                    #address missing ... do nothing
                } else {
                    $arr = pg_fetch_array($run_addr);
                    $cust['addr1'] = $arr['branch_descrip'];
                    if ($inv['del_addr'] != $arr['branch_descrip']) {
                        $update_addr = "UPDATE invoices SET del_addr  = '{$arr['branch_descrip']}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                    }
                }
            }
            #if the del_addr of invoice if empty, add the customer's entry and display button so user can edit anyway
            if (strlen($inv['del_addr']) < 1) {
                $cust_del_addr = $cust['del_addr1'];
            } else {
                $cust_del_addr = $inv['del_addr'];
            }
            $sql = "SELECT cusnum, cusname, surname FROM customers WHERE deptid = '{$inv['deptid']}' AND location != 'int' AND lower(surname) LIKE lower('{$letters}%') AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
            $cusRslt = db_exec($sql) or errDie("Unable to view customers");
            # Moarn if customer account has been blocked
            if ($cust['blocked'] == 'yes') {
                $error .= "<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'];
            $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
            // $customers .= "<option value='-S' selected>Select Customer</option>";
            while ($cus = pg_fetch_array($cusRslt)) {
                $sel = "";
                if ($cust['cusnum'] == $cus['cusnum']) {
                    $sel = "selected";
                }
                $customers .= "<option value='{$cus['cusnum']}' {$sel}>{$cus['cusname']} {$cus['surname']}</option>";
            }
            $customers .= "</select>";
            #get list of branches
            $get_branches = "SELECT * FROM customer_branches WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
            $run_branches = db_exec($get_branches);
            if (pg_numrows($run_branches) < 1) {
                $branchdrop = "<input type='hidden' name='branch' value='0'>No Branches For This Customer";
            } else {
                $branchdrop = "<select name='branch' onChange='javascript:document.form.submit();'>";
                $branchdrop .= "<option value='0'>Head Office</option>";
                while ($barr = pg_fetch_array($run_branches)) {
                    $sel2 = "";
                    if ($barr['id'] == $branch) {
                        $sel2 = "selected";
                    }
                    $branchdrop .= "<option {$sel2} value='{$barr['id']}'>{$barr['branch_name']}</option>";
                }
                $branchdrop .= "</select>";
            }
        }
    }
    /* --- Start Drop Downs --- */
    # Select warehouse
    db_conn("exten");
    //old
    //$whs = "<select name='whidss[]' onChange='javascript:document.form.submit();'>";
    //fixes broken new store function
    //STORE1
    $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)) {
            $whs .= "<option value='{$wh['whid']}'>({$wh['whno']}) {$wh['whname']}</option>";
        }
    }
    $whs .= "</select>";
    // Is the customer linked to a sales rep
    if (!empty($cust["sales_rep"])) {
        db_conn("exten");
        $sql = "SELECT salesp FROM salespeople WHERE salespid='{$cust['sales_rep']}'";
        $sr_rslt = db_exec($sql) or errDie("Unable to retrieve sales rep from Cubit.");
        $salespname = pg_fetch_result($sr_rslt, 0);
        $salesps = "<input type='hidden' name='salespn' value='{$salespname}'><b>[{$salespname}]</b>";
    } else {
        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'] == $inv['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, $inv['terms']);
    # Keep the charge vat option stable
    if ($inv['chrgvat'] == "inc") {
        $chin = "checked=yes";
        $chex = "";
        $chno = "";
    } elseif ($inv['chrgvat'] == "exc") {
        $chin = "";
        $chex = "checked=yes";
        $chno = "";
    } else {
        $chin = "";
        $chex = "";
        $chno = "checked=yes";
    }
    # Format date
    list($inv_date_year, $inv_date_month, $inv_date_day) = explode("-", $inv['odate']);
    /* --- 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>SERIAL NO.</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 invoice
    db_connect();
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    $i = 0;
    $key = 0;
    $ai = 0;
    while ($stkd = pg_fetch_array($stkdRslt)) {
        $stkd['account'] += 0;
        if ($stkd['account'] != 0) {
            # Keep track of selected stock amounts
            $stkd["amt"] = sprint($stkd["amt"]);
            $amts[$i] = $stkd['amt'];
            $i++;
            $Accounts = "\n\t\t\t\t<select name='accounts[{$ai}]'>\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 ($ad['accid'] == $stkd['account']) {
                        $sel = "selected";
                    } else {
                        $sel = "";
                    }
                    if (isb($ad['accid'])) {
                        continue;
                    }
                    $Accounts .= "<option value='{$ad['accid']}' {$sel}>{$ad['accname']}</option>";
                }
            }
            $Accounts .= "</select>";
            $sernos = "\n\t\t\t\t<input type='hidden' name='sernos[{$ai}]' value='{$stkd['serno']}'>\n\t\t\t\t<input type='hidden' name='sernos_ss[{$ai}]' value='{$stkd['serno']}'>";
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[{$ai}]' value='{$stkd['qty']}'>";
            $viewcost = "<input type='text' size='8' name='unitcost[{$ai}]' 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[{$ai}]'>\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>";
            # 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[{$ai}]' value='{$stkd['whid']}'>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td><input type='hidden' name='stkids[{$ai}]' value='{$stkd['stkid']}'>{$Vatcodes}</td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptions[{$ai}]' 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[{$ai}]' value='{$stkd['disc']}'><input type='hidden' name='discp[{$ai}]' value='{$stkd['discp']}'></td>\n\t\t\t\t\t<td nowrap><input type='hidden' name='amt[{$ai}]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[{$ai}]' value='{$key}'></td>\n\t\t\t\t</tr>";
            $key++;
            ++$ai;
        } 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);
            # Serial number
            if ($stk['serd'] == 'yes' && ($inv['serd'] == 'n' || $stkd["serno"] == "")) {
                $sers = ext_getavserials($stkd['stkid']);
                $sernos = "<select name='sernos[{$ai}]'>";
                foreach ($sers as $skey => $ser) {
                    $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
                }
                $sernos .= "</select>\n\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*' />";
            } else {
                $sernos = "\n\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='{$stkd['ss']}' />\n\t\t\t\t\t<input type='hidden' name='sernos[{$ai}]' value='{$stkd['serno']}'>{$stkd['ss']}";
            }
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[{$ai}]' value='{$stkd['qty']}'>";
            if ($stk['serd'] == 'yes') {
                $qtyin = "<input type='hidden' size='3' name='qtys[{$ai}]' value='{$stkd['qty']}'>{$stkd['qty']}";
            }
            # check permissions
            if (perm("invoice-unitcost-edit.php")) {
                $viewcost = "<input type='text' size='8' name='unitcost[{$ai}]' value='{$stkd['unitcost']}'>";
            } else {
                $viewcost = "<input type='hidden' size='8' name='unitcost[{$ai}]' value='{$stkd['unitcost']}'>{$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[{$ai}]'>\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>";
            # Put in product
            $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<input type='hidden' name='accounts[{$ai}]' value='0'>\n\t\t\t\t\t\t<input type='hidden' name='descriptions[{$ai}]' value=''>\n\t\t\t\t\t\t<input type='hidden' name='whids[{$ai}]' value='{$stkd['whid']}'>{$wh['whname']}\n\t\t\t\t\t</td>\n\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'><a href='#bottom' 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>{$sernos}</td>\n\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</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='text' size='4' name='disc[{$ai}]' value='{$stkd['disc']}'> OR <input type='text' size='4' name='discp[{$ai}]' value='{$stkd['discp']}' maxlength='5'>%</td>\n\t\t\t\t\t<td nowrap><input type='hidden' name='amt[{$ai}]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\t\t\t\t<td><input type='checkbox' name='remprod[{$ai}]' value='{$key}'></td>\n\t\t\t\t</tr>";
            $key++;
            ++$ai;
        }
    }
    # Look above(remprod keys)
    $keyy = $key;
    # Look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    } else {
        $SCROLL = "yes";
    }
    # 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 whid, whname FROM warehouses WHERE whid = (select whid from cubit.stock where stkid = '{$stk['stkid']}' limit 1) AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                if ($stk['serd'] == 'yes') {
                    $sers = ext_getavserials($stkidss[$key]);
                    $sernos = "<select name='sernos[]' onChange='javascript:document.form.submit();'>";
                    foreach ($sers as $skey => $ser) {
                        $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
                    }
                    $sernos .= "</select>\n\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*' />";
                } else {
                    $sernos = "\n\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value=''>\n\t\t\t\t\t\t<input type='hidden' name='sernos[{$ai}]' value=''>";
                }
                # 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>";
                        }
                    }
                }
                if ($stk['units'] <= $stk['minlvl'] && $stk['minlvl'] != 0) {
                    $error .= "<li class='err'>{$stk['stkcod']} is below minimum level, please notify stock controller.</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]);
                # Input qty if not serialised
                $qtyin = "<input type='text' size='3' name='qtemp' value='{$qtyss[$key]}'>";
                if ($stk['serd'] == 'yes') {
                    $qtyin = "<input type='hidden' size='3' name='qtemp' value='{$qtyss[$key]}'>{$qtyss[$key]}";
                }
                #clean some vars
                $stk['selamt'] = sprint($stk['selamt']);
                $amt[$key] = sprint($amt[$key]);
                # Check permissions
                if (perm("invoice-unitcost-edit.php")) {
                    $viewcost = "<input type='text' size='8' name='unitcost[{$ai}]' value='{$stk['selamt']}'>";
                } else {
                    $viewcost = "<input type='hidden' size='8' name='unitcost[{$ai}]' value='{$stk['selamt']}'>{$stk['selamt']}";
                }
                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[{$ai}]'>\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>";
                # Put in selected warehouse and stock
                $products .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t<input type='hidden' name='accounts[{$ai}]' value='0'>\n\t\t\t\t\t\t\t<input type='hidden' name='descriptions[{$ai}]' value=''>\n\t\t\t\t\t\t\t<input type='hidden' name='whids[]' value='{$wh['whid']}'>{$wh['whname']}\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td><input type='hidden' name='stkids[{$ai}]' value='{$stk['stkid']}'><a href='#bottom' 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>{$sernos}</td>\n\t\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</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><input type='text' size='4' name='disc[{$ai}]' value='{$discs[$key]}'> OR <input type='text' size='4' name='discp[{$ai}]' value='{$discps[$key]}' maxlength='5'>%</td>\n\t\t\t\t\t\t<td nowrap><input type='hidden' name='amt[{$ai}]' value='{$amt[$key]}'> " . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td><input type='checkbox' name='remprod[{$ai}]' value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
                $keyy++;
                ++$ai;
            } elseif (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='qtemp' value='{$qtyss[$key]}'>";
                # Check permissions
                $viewcost = "<input type='text' size='8' name='unitcost[{$ai}]' 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[{$ai}]'>\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>";
                # Put in selected warehouse and stock
                $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{$ad['accname']}\n\t\t\t\t\t\t\t<input type='hidden' name='accounts[{$ai}]' value='{$accountss[$key]}'>\n\t\t\t\t\t\t\t<input type='hidden' name='whids[{$ai}]' value='0'>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td>{$Vatcodes}<input type='hidden' name='stkids[{$ai}]' value='0'></td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='descriptions[{$ai}]' 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><input type='hidden' name='disc[{$ai}]' value='0'><input type='hidden' name='discp[{$ai}]' value='0'></td>\n\t\t\t\t\t\t<td nowrap><input type='hidden' name='amt[{$ai}]' value='{$amt[$key]}'> " . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t<td><input type='checkbox' name='remprod[{$ai}]' value='{$keyy}'></td>\n\t\t\t\t\t</tr>";
                $keyy++;
                ++$ai;
            } else {
                # skip if not selected
                if ($whid == "-S") {
                    continue;
                }
                if (!isset($addnon)) {
                    if ($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);
                    }
                    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}'";
                    }
                    # get stock on this warehouse
                    db_connect();
                    $sql = "SELECT * FROM stock WHERE blocked = 'n' AND div = '" . USER_DIV . "' {$Wh} ORDER BY {$sel_frm} 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.";
                        continue;
                    }
                    if (pg_numrows($stkRslt) == 1) {
                        $ex = "selected";
                        $reload = TRUE;
                        $send_override = "<input type='hidden' name='stkidss[{$ai}]' value='" . pg_fetch_result($stkRslt, 0, 0) . "'><script>document.form.submit();</script>";
                    } else {
                        $ex = "";
                        $reload = FALSE;
                    }
                    if ($sel_frm == "stkcod") {
                        $cods = "<select name='stkidss[{$ai}]' onChange='javascript:document.form1.submit();'>";
                        $count = 0;
                        while ($stk = pg_fetch_array($stkRslt)) {
                            // Check if this stock item has been blocked
                            //pointless, as we only get non blocked stock ...
                            //if (stock_is_blocked($stk["stkid"])) {
                            //	continue;
                            //}
                            $cods .= "<option value='{$stk['stkid']}'>{$stk['stkcod']} (" . sprint3($stk['units'] - $stk['alloc']) . ")</option>";
                        }
                        $cods .= "</select> ";
                        $descs = "";
                    } else {
                        $descs = "<select style='width:250px'name='stkidss[{$ai}]' onChange='javascript:document.form.submit();'>";
                        $descs .= "<option value='-S' disabled selected>Select Description</option>";
                        $count = 0;
                        while ($stk = pg_fetch_array($stkRslt)) {
                            // Check if this stock item has been blocked
                            //pointless, as ge only get non blocked stock
                            //								if (stock_is_blocked($stk["stkid"])) {
                            //									continue;
                            //								}
                            $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[{$ai}]'>\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>\n\t\t\t\t\t\t\t\t<input type='hidden' name='accountss[{$ai}]' value='0'>\n\t\t\t\t\t\t\t\t<input type='hidden' name='descriptionss[{$ai}]' value=''>\n\t\t\t\t\t\t\t\t<input type='hidden' name='whidss[{$ai}]' value='{$filter_store}'>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<td>{$cods}</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='vatcodess' value='0'></td>\n\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t<td>{$descs}</td>\n\t\t\t\t\t\t\t<td><input type='hidden' size='3' name='qtyss[{$ai}]'  value='1'>1</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='discs[{$ai}]' value='0'> OR <input type='text' size='4' name='discps[{$ai}]' value='0' maxlength='5'>%</td>\n\t\t\t\t\t\t\t<td nowrap><input type='hidden' name='amts[{$ai}]' value='0.00'>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t</tr>";
                    ++$ai;
                } else {
                    $Accounts = "\n\t\t\t\t\t\t<select name='accountss[{$ai}]' onChange='javascript:document.form.submit();'>\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[{$ai}]'>\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 colspan='2'>\n\t\t\t\t\t\t\t\t{$Accounts}\n\t\t\t\t\t\t\t\t<input type='hidden' name='whidss[{$ai}]' value='1'>\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t<inpu type='hidden' name='stkidss[{$ai}]' value=''>\n\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[{$ai}]'></td>\n\t\t\t\t\t\t\t<td><input type='text' size='3' name='qtyss[{$ai}]' value='1'></td>\n\t\t\t\t\t\t\t<td><input type='text' name='unitcosts[{$ai}]' size='7'></td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t<td nowrap>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td><input type='hidden' name='discs[{$ai}]' value='0'><input type='hidden' name='discps[{$ai}]' value='0'></td>\n\t\t\t\t\t\t</tr>";
                    ++$ai;
                }
            }
        }
    } else {
        #HAX !
        if (!isset($addnon) && !isset($upBtn)) {
            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}'";
            }
            # get stock on this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE blocked = 'n' AND div = '" . USER_DIV . "' {$Wh} ORDER BY {$sel_frm} 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 store.</li>";
                //ontinue;
            }
            if (pg_numrows($stkRslt) == 1) {
                $reload = TRUE;
                $send_override = "<input type='hidden' name='stkidss[{$ai}]' value='" . pg_fetch_result($stkRslt, 0, 0) . "'>";
            } else {
                $reload = FALSE;
                $send_override = "";
            }
            if ($sel_frm == "stkcod") {
                $cods = "<select name='stkidss[{$ai}]' 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[{$ai}]' 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 = "";
            }
            $products .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<input type='hidden' name='accountss[{$ai}]' value='0'>\n\t\t\t\t\t\t<input type='hidden' name='descriptionss[{$ai}]' value=''>\n\t\t\t\t\t\t<input type='hidden' name='vatcodess[{$ai}]' value=''>\n\t\t\t\t\t\t<input type='hidden' name='whidss[{$ai}]' value='{$filter_store}'>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td>{$cods}</td>\n\t\t\t\t\t<td> </td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td>{$descs}</td>\n\t\t\t\t\t<td><input type='hidden' size='3' name='qtyss[{$ai}]' value='1'>1</td>\n\t\t\t\t\t<td> </td>\n\t\t\t\t\t<td><input type='text' size='4' name='discs[{$ai}]' value='0'> OR <input type='text' size='4' name='discps[{$ai}]' value='0' maxlength='5'>%</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</tr>";
            ++$ai;
        } elseif (isset($addnon)) {
            $Accounts = "\n\t\t\t\t<select name='accountss[{$ai}]'  onChange='javascript:document.form.submit();'>\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[{$ai}]'>\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<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2'>{$Accounts}<input type='hidden' name='whidss[{$ai}]' value='1'></td>\n\t\t\t\t\t<inpu type='hidden' name='stkidss[{$ai}]' value=''>\n\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[{$ai}]'></td>\n\t\t\t\t\t<td><input type='text' size='3' name='qtyss[{$ai}]' value='1'></td>\n\t\t\t\t\t<td><input type='text' name='unitcosts[{$ai}]' size='7'></td>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td nowrap>" . CUR . " 0.00</td>\n\t\t\t\t\t<td><input type='hidden' name='discs[{$ai}]' value='0'><input type='hidden' name='discps[{$ai}]' value='0' ></td>\n\t\t\t\t</tr>";
            ++$ai;
        }
    }
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    if ($inv['traddisc'] > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * $inv['total']);
    } else {
        $traddiscm = "0.00";
    }
    $VATP = TAX_VAT;
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    /* --- End Some calculations --- */
    /*--- Start checks --- */
    # check only if the customer is selected
    if (isset($cusnum) && $cusnum != "-S") {
        #check againg credit limit
        if ($TOTAL + $cust['balance'] > $cust['credlimit']) {
            $error .= "<li class='err'>Warning : Customers Credit limit of <b>" . CUR . " " . sprint($cust["credlimit"]) . "</b> has been exceeded";
            #limit reached ... check for warn/block
            db_conn("cubit");
            $get_check = "SELECT value FROM set WHERE label = 'CUST_INV_WARN' LIMIT 1";
            $run_check = db_exec($get_check) or errDie("Unable to get credit limit response setting");
            if (pg_numrows($run_check) < 1) {
                #no setting ? do nothing ....
            } else {
                $sarr = pg_fetch_array($run_check);
                if ($sarr['value'] == "block") {
                    #block account ...
                    $done = "";
                }
            }
            # Check permissions
            if (!perm("invoice-limit-override.php")) {
                $done = "";
            }
        }
        $avcred = $cust['credlimit'] - $cust['balance'];
    } else {
        $avcred = "0.00";
    }
    /*--- Start checks --- */
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='SALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sc = "checked";
    } else {
        $sc = "";
    }
    $sales = "\n\t\t<td>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$salesps}</td>\n\t\t\t\t\t<td>Print</td>\n\t\t\t\t\t<td><input type='checkbox' name='printsales' {$sc}></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t</td>";
    $inv['delvat'] += 0;
    if ($inv['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $inv['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'] == $inv['delvat']) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $Vatcodes .= "<option value='{$vd['id']}' {$sel}>{$vd['code']}</option>";
    }
    $Vatcodes .= "</select>";
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='Delivery Note'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $chp = "checked";
    } else {
        $chp = "";
    }
    if (empty($inv["comm"])) {
        db_conn("cubit");
        $sql = "SELECT value FROM settings WHERE constant='DEFAULT_COMMENTS'";
        $cmntRslt = db_exec($sql) or errDie("Unable to retrieve the default comment from Cubit.");
        $comm = base64_decode(pg_fetch_result($cmntRslt, 0));
    } else {
        $comm = $inv["comm"];
    }
    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 = "";
    }
    // Delivery Date
    if (!empty($inv["deldate"])) {
        $deldate = explode("-", $inv["deldate"]);
    } else {
        $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);
            $deldate[0] = $date_arr[0];
            $deldate[1] = $date_arr[1];
            $deldate[2] = $date_arr[2];
        } else {
            $deldate[0] = date("Y");
            $deldate[1] = date("m");
            $deldate[2] = date("d");
        }
    }
    $details_begin = "\n\t\t<center>\n\t\t<h3>New Invoice</h3>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='SCROLL' value='yes'>\n\t\t\t<input type='hidden' name='key' value='update'>\n\t\t\t<input type='hidden' name='invid' value='{$invid}'>\n\t\t\t<input type='hidden' name='stkerr' value='{$stkerr}'>\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t \t<tr>\n\t\t \t\t<td valign='top' width='50%'>\n\t\t \t\t\t<div id='cust_selection'>";
    if (empty($ajax_err) && (isset($cusnum) || AJAX)) {
        if (isset($cusnum)) {
            $OTS_OPT = onthespot_encode(SELF, "cust_selection", "deptid={$inv['deptid']}&letters={$letters}&cusnum={$cusnum}&invid={$invid}");
            $custedit = "\n\t\t\t\t<td nowrap>\n\t\t\t\t\t<a href='javascript: popupSized(\"customers-new.php?cusnum={$cusnum}&onthespot={$OTS_OPT}\", \"edit_cust\", 700, 630);'>Edit Customer Details</a>\n\t\t\t\t</td>";
        } else {
            $custedit = "";
        }
        $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\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Category</td>\n\t\t\t\t\t<td>{$cat_drop}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Classification</td>\n\t\t\t\t\t<td>{$class_drop}</td>\n\t\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 ($wh['whid'] == $filter_store) {
                    $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>";
        }
        $ajaxOut = "\n\t\t\t<input type='hidden' name='letters' value='{$letters}'>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'> Customer Details </th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Department</td>\n\t\t\t\t\t<td valign='center'>{$dept['deptname']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Account No.</td>\n\t\t\t\t\t<td valign='center'>{$cust['accno']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer</td>\n\t\t\t\t\t<td valign='center'>{$customers}</td>\n\t\t\t\t\t{$custedit}\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='top'>Customer Branch</td>\n\t\t\t\t\t<td valign='center'>{$branchdrop}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='top'>Customer Address</td>\n\t\t\t\t\t<td valign='center'>" . nl2br($cust['addr1']) . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='top'>Current Delivery Address</td>\n\t\t\t\t\t<td valign='center'>" . nl2br($cust_del_addr) . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='top'>Delivery Address</td>\n\t\t\t\t\t<td valign='center'>\n\t\t\t\t\t\t<input type='button' onClick=\"\n\t\t\t\t\t\t\tvar windowReference;\n\n\t\t\t\t\t\t\tfunction openPopup() {\n\t\t\t\t\t\t\t\twindowReference = window.open('cust-credit-stockinv-deladdr.php?invid={$invid}','windowName','width=500,height=400,status=1');\n\t\t\t\t\t\t\t\tif (!windowReference.opener)\n\t\t\t\t\t\t\t\t\twindowReference.opener = self;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\topenPopup();\" value='Change Delivery Address'>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer Order number</td>\n\t\t\t\t\t<td valign='center'><input type='text' size='10' name='cordno' value='{$inv['cordno']}'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer VAT Number</td>\n\t\t\t\t\t<td>{$cust['vatnum']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>Point of Sale</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Barcode</td>\n\t\t\t\t\t<td><input type='text' size='13' name='bar' value=''></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Print Delivery Note</td>\n\t\t\t\t\t<td><input type='checkbox' name='printdel' {$chp}></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Using</td>\n\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</tr>\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>Additional Filters</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Store</td>\n\t\t\t\t\t<td>{$store_drop}</td>\n\t\t\t\t</tr>\n\t\t\t\t{$display_optional_filters}\n\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<td>Stock Filter</td>\n\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</tr>\n\t\t\t</table>";
    } else {
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE div = '" . USER_DIV . "' ORDER BY deptname ASC";
        $deptRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($deptRslt) < 1) {
            return "<li class='err'>There are no Departments found in Cubit.</li>";
        } else {
            $depts = "<select name='deptid' id='deptid'>";
            $depts .= "<option value='0'>All Departments</option>";
            while ($dept = pg_fetch_array($deptRslt)) {
                $depts .= "<option value='{$dept['deptid']}'>{$dept['deptname']}</option>";
            }
            $depts .= "</select>";
        }
        if (!isset($ajax_err)) {
            $ajax_err = "";
        }
        $ajaxOut = "\n\t\t\t<script>\n\t\t\t\tfunction updateCustSelection() {\n\t\t\t\t\tdeptid = getObject('deptid').value;\n\t\t\t\t\tletters = getObject('letters').value;\n\t\t\t\t\tctyp = getObject('ctypintl').checked;\n\t\t\t\t\tif (ctyp) {\n\t\t\t\t\t\tdocument.location.href='intinvoice-new.php?' + 'letters=' + letters + '&deptid=' + deptid + '&ctyp=' + ctyp + '&invid={$invid}';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tajaxRequest('" . SELF . "', 'cust_selection', AJAX_SET, 'letters='+letters+'&deptid='+deptid+'&ctyp='+ctyp+'&invid={$invid}');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t</script>\n\t\t\t{$ajax_err}\n\t\t\t<form name='cusselfrm'>\n\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan='2'>Customer Selection</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Select Department</td>\n\t\t\t\t\t<td valign='center'>{$depts}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>First Letters of customer</td>\n\t\t\t\t\t<td valign='center'><input type='text' size='5' id='letters' maxlength='5'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer is International</td>\n\t\t\t\t\t<td valign='center'><input type='checkbox' id='ctypintl'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><br /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td></td>\n\t\t\t\t\t<td valign='center'><input type='button' value='Update &raquo' onClick='updateCustSelection();'></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</form>";
    }
    $avcred = sprint($avcred);
    if (isset($addprodBtn) or isset($addnon) or isset($saveBtn) or isset($upBtn) 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 = "";
    }
    $details_end = "\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td valign='top' align='right' width='50%'>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th colspan='2'> Invoice Details </th>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Invoice No.</td>\n\t\t\t\t\t\t\t\t<td valign='center'>TI {$inv['invid']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Proforma Inv No.</td>\n\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='docref' value='{$inv['docref']}'></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Sales Order No.</td>\n\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='ordno' value='{$inv['ordno']}'></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>VAT Inclusive</td>\n\t\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\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Terms</td>\n\t\t\t\t\t\t\t\t<td valign='center'>{$termssel} Days</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Sales Person</td>\n\t\t\t\t\t\t\t\t{$sales}\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Invoice Date</td>\n\t\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("inv_date", $inv_date_year, $inv_date_month, $inv_date_day) . "</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Available Credit</td>\n\t\t\t\t\t\t\t\t<td>" . CUR . " {$avcred}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Trade Discount</td>\n\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='5' name='traddisc' value='{$inv['traddisc']}'>%</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Delivery Charge</td>\n\t\t\t\t\t\t\t\t<td valign='center'><input type='text' size='7' name='delchrg' value='{$inv['delchrg']}'>{$Vatcodes}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Delivery Date</td>\n\t\t\t\t\t\t\t\t<td valign='center'>" . mkDateSelect("del_date", $deldate[0], $deldate[1], $deldate[2]) . "</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t" . TBL_BR . "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2'>{$products}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>\n\t\t\t\t\t\t<p>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th width='25%'>Quick Links</th>\n\t\t\t\t\t\t\t\t<th width='25%'>Comments</th>\n\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</tr>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='customers-new.php?re={$inv['invid']}'>New Customer</a></td>\n\t\t\t\t\t\t\t\t<td class='" . bg_class() . "' rowspan='5' align='center' valign='top'><textarea name='comm' rows='4' cols='20'>{$comm}</textarea></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td class='" . bg_class() . "'><a href='cust-credit-stockinv.php'>New Invoice</a></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><a href='invoice-view.php'>View Invoices</a></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><a href='settings/cust-credit-stockinv-newsetting.php?change=yes'>Change Invoice Complete Setting</a></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td align='right' valign='top'>\n\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='50%'>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>SUBTOTAL</td>\n\t\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\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Trade Discount</td>\n\t\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$inv['discount']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td>Delivery Charge</td>\n\t\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$inv['delivery']}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td><b>VAT {$vat14}</b></td>\n\t\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$VAT}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<th>GRAND TOTAL</th>\n\t\t\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$TOTAL}</td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='right'><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'> </td>\n\t\t\t\t\t<td nowrap>| <input type='submit' name='upBtn' value='Update'>{$done}</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t<a name='bottom'>\n\t\t\t</form>\n\t\t\t</center>\n\t\t\t{$jump_bot}";
    if (!isset($reload)) {
        $reload = FALSE;
        $send_override = "";
    }
    if ($reload) {
        $details_end .= "\n\t\t\t\t\t\t{$send_override}\n\t\t\t\t\t\t<script>\n\t\t\t\t\t\t\tonLoad=document.form.submit();\n\t\t\t\t\t\t</script>\n\t\t\t\t\t";
    }
    if (AJAX) {
        return $ajaxOut;
    } else {
        return "{$details_begin}{$ajaxOut}{$details_end}";
    }
}
function confirm($_POST)
{
    # Get stock vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($stkid, "num", 1, 50, "Invalid stock number.");
    $v->isOk($sdiv, "num", 1, 50, "Invalid branch number.");
    $v->isOk($whid, "num", 1, 50, "Invalid warehouse number.");
    $v->isOk($tunits, "num", 1, 50, "Invalid number of units.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li>";
        }
        return $confirm;
    }
    # Select Stock
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.</li>";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    db_conn("exten");
    # get warehouse
    $sql = "SELECT whname FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # get warehouse
    $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '{$sdiv}'";
    $swhRslt = db_exec($sql);
    $swh = pg_fetch_array($swhRslt);
    $serials = "";
    if ($stk['serd'] == 'yes') {
        $sers = ext_getavserials($stkid);
        $serials = "<tr><th colspan='2'>Units Serial Numbers</th></tr>";
        $sernos = "<select name='sernos[]'>";
        foreach ($sers as $skey => $ser) {
            $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
        }
        $sernos .= "</select>";
        for ($i = 0; $i < $tunits; $i++) {
            $serials .= "<tr class='" . bg_class() . "'><td colspan='2' align='center'>{$sernos}</td></tr>";
        }
    }
    db_connect();
    # Original Branch
    $sql = "SELECT * FROM branches WHERE div = '{$stk['div']}'";
    $branRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($branRslt) < 1) {
        return "<li> Invalid Branch ID.</li>";
    } else {
        $bran = pg_fetch_array($branRslt);
    }
    # Selected Branch
    $sql = "SELECT * FROM branches WHERE div = '{$sdiv}'";
    $sbranRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($sbranRslt) < 1) {
        return "<li> Invalid Branch ID.</li>";
    } else {
        $sbran = pg_fetch_array($sbranRslt);
    }
    /*
    # Get stock from selected warehouse
    db_connect();
    $sql = "SELECT * FROM stock WHERE whid = '$whid' AND lower(stkcod) = lower('$stk[stkcod]') AND div = '$sdiv'";
    $sstkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if(pg_numrows($sstkRslt) < 1){
    	$sstk = $stk;
    	$head = "New Stock";
    	$data = "<tr class='bg-odd'><td>Location</td><td>Shelf <input type=text size=5 name='shelf'> Row <input type=text size=5 name='row'></td></tr>
    	<tr class='bg-even'><td>Level</td><td>Minimum <input type=text size=5 name='minlvl' value='$stk[minlvl]'> Maximum <input type=text size=5 name='maxlvl' value='$stk[maxlvl]'></td></tr>
    	<tr class='bg-odd'><td>Selling price per unit</td><td>".CUR." <input type=hidden name='selamt' value='$stk[selamt]'>$stk[selamt]</td></tr>";
    }else{
    	$sstk = pg_fetch_array($sstkRslt);
    	$data = "";
    	$head = "";
    }
    */
    # available stock units
    $avstk = $stk['units'] - $stk['alloc'];
    // Layout
    $confirm = "\n\t\t<center>\n\t\t<h3>Transfer Stock</h3>\n\t\t<h4>Confirm Details</h4>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='write'>\n\t\t\t<input type='hidden' name='stkid' value='{$stkid}'>\n\t\t\t<input type='hidden' name='sdiv' value='{$sdiv}'>\n\t\t\t<input type='hidden' name='whid' value='{$whid}'>\n\t\t\t<input type='hidden' name='tunits' value='{$tunits}'>\n\t\t<table " . TMPL_tblDflts . " width='350'>\n\t\t\t<tr>\n\t\t\t\t<th width='40%'>Field</th>\n\t\t\t\t<th width='60%'>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Branch</td>\n\t\t\t\t<td>{$bran['branname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Warehouse</td>\n\t\t\t\t<td>{$wh['whname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Category</td>\n\t\t\t\t<td>{$stk['catname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock code</td>\n\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock description</td>\n\t\t\t\t<td>" . nl2br($stk['stkdes']) . "</pre></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>On Hand</td>\n\t\t\t\t<td>{$stk['units']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Allocated</td>\n\t\t\t\t<td>{$stk['alloc']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Available</td>\n\t\t\t\t<td>{$avstk}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>On Order</td>\n\t\t\t\t<td>{$stk['ordered']}</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t{$serials}\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Transfer to</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>To Branch</td>\n\t\t\t\t<td>{$sbran['branname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>To Store </td>\n\t\t\t\t<td>{$swh['whname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Number of units</td>\n\t\t\t\t<td>{$tunits}</td>\n\t\t\t</tr>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr>\n\t\t\t\t<td><input type='button' value='&laquo Cancel' onClick='javascript:history.back();'></td>\n\t\t\t\t<td valign='center'><input type='submit' value='transfer &raquo'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . " 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='" . bg_class() . "'>\n\t\t\t\t<td><a href='stock-transit-view.php'>View Stock in transit</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='stock-add.php'>Add Stock</a></td>\n\t\t\t</tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    return $confirm;
}
function printStk($_POST)
{
    # get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($whid, "num", 1, 50, "Invalid Warehouse.");
    if (isset($cat)) {
        $v->isOk($catid, "num", 1, 50, "Invalid Category.");
        $searchs = "SELECT * FROM stock WHERE whid = '{$whid}' AND catid = '{$catid}' AND div = '" . USER_DIV . "' ORDER BY stkcod ASC";
    } elseif (isset($class)) {
        $v->isOk($clasid, "num", 1, 50, "Invalid Classification.");
        $searchs = "SELECT * FROM stock WHERE whid = '{$whid}' AND prdcls = '{$clasid}' AND div = '" . USER_DIV . "' ORDER BY stkcod ASC";
    } elseif (isset($all)) {
        $searchs = "SELECT * FROM stock WHERE whid = '{$whid}' AND div = '" . USER_DIV . "' ORDER BY stkcod ASC";
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class=err>-" . $e["msg"] . "<br>";
        }
        return $confirm;
    }
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $stkRslt = db_exec($searchs) or errDie("Unable to retrieve stocks from database.");
    if (pg_numrows($stkRslt) < 1) {
        return "<li class=err> There are no stock items found.</li>\n\t\t<p>\n\t\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "' width=15%>\n\t\t\t<tr><td><br></td></tr>\n\t\t\t<tr><th>Quick Links</th></tr>\n\t\t\t<tr class='bg-even'><td><a href='stock-taking.php'>Back</a></td></tr>\n\t\t\t<tr class='bg-odd'><td><a href='stock-add.php'>Add Stock</a></td></tr>\n\t\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t\t</table>";
    }
    # Set up table to display in
    $printStk = "\n    <center><h3>Stock Taking</h3>\n    <table cellpadding='2' cellspacing='0' border=1 width=750 bordercolor='#000000'>\n    <tr><th width=100>CODE</th><th width=350>DESCRIPTION</th><th width=150>SERIAL No.</th><th width=50>UNITS</th><th width=100 colspan=2></th></tr>";
    while ($stk = pg_fetch_array($stkRslt)) {
        // $printStk .= "<tr valign=top><td>$stk[stkcod]</td><td>$stk[stkdes]</td><td><br></td><td>$stk[units]</td><td><br></td><td><br></td></tr>";
        if ($stk['serd'] == "yes") {
            # get serial numbers
            $sers = ext_getavserials($stk['stkid']);
            if (count($sers) < $stk['units']) {
                $noalloc = $stk['units'] - count($sers);
                $printStk .= "<tr valign=top><td>{$stk['stkcod']}</td><td>{$stk['stkdes']}</td><td>Not Allocated</td><td align=right><br></td><td><br></td><td><br></td></tr>";
            }
            foreach ($sers as $skey => $ser) {
                $printStk .= "<tr valign=top><td>{$stk['stkcod']}</td><td>{$stk['stkdes']}</td><td>{$ser['serno']}</td><td align=right><br></td><td><br></td><td><br></td></tr>";
            }
        } else {
            $printStk .= "<tr valign=top><td>{$stk['stkcod']}</td><td>{$stk['stkdes']}</td><td>Not Serialized</td><td align=right><br></td><td><br></td><td><br></td></tr>";
        }
    }
    $printStk .= "</table>";
    $OUTPUT = $printStk;
    require "tmpl-print.php";
}
function confirm($_POST)
{
    # get stock vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($stkid, "num", 1, 50, "Invalid stock number.");
    $v->isOk($whid, "num", 1, 50, "Invalid warehouse number.");
    $v->isOk($tunits, "float", 1, 15, "Invalid number of units.");
    $date = mkdate($d_year, $d_month, $d_day);
    $v->isOk($date, "date", 1, 1, "Invalid transfer date.");
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li>";
        }
        return $confirm;
    }
    # Select Stock
    db_connect();
    $sql = "SELECT * FROM stock WHERE stkid = '{$stkid}' AND div = '" . USER_DIV . "'";
    $stkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($stkRslt) < 1) {
        return "<li> Invalid Stock ID.</li>";
    } else {
        $stk = pg_fetch_array($stkRslt);
    }
    db_conn("exten");
    # get warehouse
    $sql = "SELECT whname FROM warehouses WHERE whid = '{$stk['whid']}' AND div = '" . USER_DIV . "'";
    $whRslt = db_exec($sql);
    $wh = pg_fetch_array($whRslt);
    # get warehouse
    $sql = "SELECT whname FROM warehouses WHERE whid = '{$whid}' AND div = '" . USER_DIV . "'";
    $swhRslt = db_exec($sql);
    $swh = pg_fetch_array($swhRslt);
    $serials = "";
    if ($stk['serd'] == 'yes') {
        $sers = ext_getavserials($stkid);
        $serials = "<tr><th colspan='2'>Units Serial Numbers</th></tr>";
        $sernos = "<select name='sernos[]'>";
        foreach ($sers as $skey => $ser) {
            $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
        }
        $sernos .= "</select>";
        for ($i = 0; $i < $tunits; $i++) {
            $serials .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='2' align='center'>{$sernos}</td>\n\t\t\t\t</tr>";
        }
    }
    # Get stock from selected warehouse
    db_connect();
    $sql = "SELECT * FROM stock WHERE whid = '{$whid}' AND lower(stkcod) = lower('{$stk['stkcod']}') AND div = '" . USER_DIV . "'";
    $sstkRslt = db_exec($sql) or errDie("Unable to access databse.", SELF);
    if (pg_numrows($sstkRslt) < 1) {
        $sstk = $stk;
        $head = "New Stock";
        $data = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Location</td>\n\t\t\t\t<td>Shelf <input type='text' size='5' name='shelf'> Row <input type='text' size='5' name='row'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Level</td>\n\t\t\t\t<td>Minimum <input type='text' size='5' name='minlvl' value='{$stk['minlvl']}'> Maximum <input type='text' size='5' name='maxlvl' value='{$stk['maxlvl']}'></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Selling price per unit</td>\n\t\t\t\t<td>" . CUR . " <input type='hidden' name='selamt' value='{$stk['selamt']}'>{$stk['selamt']}</td>\n\t\t\t</tr>";
    } else {
        $sstk = pg_fetch_array($sstkRslt);
        $data = "";
        $head = "";
    }
    # available stock units
    $avstk = $stk['units'] - $stk['alloc'];
    // Layout
    $confirm = "\n\t\t<center>\n\t\t<h3>Transfer Stock</h3>\n\t\t<h4>Confirm Details</h4>\n\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t<input type='hidden' name='key' value='write'>\n\t\t\t<input type='hidden' name='stkid' value='{$stkid}'>\n\t\t\t<input type='hidden' name='sstkid' value='{$sstk['stkid']}'>\n\t\t\t<input type='hidden' name='whid' value='{$whid}'>\n\t\t\t<input type='hidden' name='tunits' value='{$tunits}'>\n\t\t\t<input type='hidden' name='d_year' value='{$d_year}' />\n\t\t\t<input type='hidden' name='d_month' value='{$d_month}' />\n\t\t\t<input type='hidden' name='d_day' value='{$d_day}' />\n\t\t\t<input type='hidden' name='remark' value='{$remark}' />\n\t\t<table " . TMPL_tblDflts . " width='350'>\n\t\t\t<tr>\n\t\t\t\t<th width='40%'>Field</th>\n\t\t\t\t<th width='60%'>Value</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Warehouse</td>\n\t\t\t\t<td>{$wh['whname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Category</td>\n\t\t\t\t<td>{$stk['catname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock code</td>\n\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock description</td>\n\t\t\t\t<td>" . nl2br($stk['stkdes']) . "</pre></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>On Hand</td>\n\t\t\t\t<td>" . sprint3($stk['units']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Allocated</td>\n\t\t\t\t<td>" . sprint3($stk['alloc']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Available</td>\n\t\t\t\t<td>" . sprint3($avstk) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>On Order</td>\n\t\t\t\t<td>" . sprint3($stk['ordered']) . "</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t{$serials}\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Transfer to {$head}</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Date</td>\n\t\t\t\t<td>{$date}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>To Store </td>\n\t\t\t\t<td>{$swh['whname']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock code</td>\n\t\t\t\t<td>{$sstk['stkcod']}</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Stock description</td>\n\t\t\t\t<td>" . nl2br($sstk['stkdes']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Number of units</td>\n\t\t\t\t<td>" . sprint3($tunits) . "</td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Remark</td>\n\t\t\t\t<td>{$remark}</td>\n\t\t\t</tr>\n\t\t\t{$data}\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td><input type='button' value='&laquo Cancel' onClick='javascript:history.back();'></td>\n\t\t\t\t<td valign='center'><input type='submit' value='Transfer &raquo'></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>\n\t\t<p>\n\t\t<table " . TMPL_tblDflts . " width='15%'>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<th>Quick Links</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='stock-transfer.php'>New Stock Transfer</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='stock-add.php'>Add Stock</a></td>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t</tr>\n\t\t</table>";
    return $confirm;
}
function details($_POST, $error = "")
{
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    if (isset($invid)) {
        $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    } else {
        $client = "";
        $deptid = 2;
        $v->isOk($deptid, "num", 1, 20, "Invalid department number.");
    }
    $fil = "";
    if (!isset($fcode)) {
        $fcode = "";
    }
    if (!isset($fdes)) {
        $fdes = "";
    }
    if ($fcode != "") {
        $fil .= "AND lower(stkcod) LIKE lower('%{$fcode}%')";
    }
    if ($fdes != "") {
        $fil .= "AND lower(stkdes) LIKE lower('%{$fdes}%')";
    }
    # 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($invid)) {
        $invid = create_dummy($deptid);
        $stkerr = "0,0";
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM pinvoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<li class='err'>Invoice Not Found</li>";
    }
    $inv = pg_fetch_array($invRslt);
    if (!isset($pass)) {
        $pass = "";
    } else {
        $pass = remval($pass);
        db_conn('cubit');
        $Sl = "SELECT * FROM users WHERE password=md5('{$pass}') AND abo=1000";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) > 0) {
            $ped = true;
        } else {
            $ped = false;
        }
    }
    # check if invoice has been printed
    if ($inv['printed'] == "y") {
        $error = "<li class=err> Error : Invoice number <b>{$invid}</b> has already been printed.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    # Get selected Customer info
    db_connect();
    $sql = "SELECT * FROM customers WHERE cusnum = '{$inv['cusnum']}' AND location != 'int' AND div = '" . USER_DIV . "'";
    $custRslt = db_exec($sql) or errDie("Unable to view customer");
    if (pg_numrows($custRslt) < 1) {
        db_connect();
        # Query server for customer info   AND lower(surname) LIKE lower('$letters%')
        $sql = "SELECT cusnum,cusname,surname FROM customers WHERE location != 'int' AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
        $custRslt = db_exec($sql) or errDie("Unable to view customers");
        if (pg_numrows($custRslt) < 1) {
            $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
            $customers .= "<option value='0' selected>Select Customer</option>";
            while ($cust = pg_fetch_array($custRslt)) {
                $customers .= "<option value='{$cust['cusnum']}'>{$cust['cusname']} {$cust['surname']}</option>";
            }
            $customers .= "</select>";
        } else {
            $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
            $customers .= "<option value='0' 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);
        $sql = "SELECT cusnum, cusname, surname FROM customers WHERE deptid = '{$inv['deptid']}' AND location != 'int' AND blocked != 'yes' AND div = '" . USER_DIV . "' ORDER BY surname";
        $cusRslt = db_exec($sql) or errDie("Unable to view customers");
        # Moarn if customer account has been blocked   AND lower(surname) LIKE lower('$letters%')
        if ($cust['blocked'] == 'yes') {
            $error .= "<li class=err>Error : Selected customer account has been blocked.";
        }
        // $customers = "<input type=hidden name=cusnum value='$cust[cusnum]'>$cust[cusname]  $cust[surname]";
        $cusnum = $cust['cusnum'];
        $customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
        $customers .= "<option value='0' selected>Select Customer</option>";
        // $customers .= "<option value='-S' selected>Select Customer</option>";
        while ($cus = pg_fetch_array($cusRslt)) {
            $sel = "";
            if ($cust['cusnum'] == $cus['cusnum']) {
                $sel = "selected";
            }
            $customers .= "<option value='{$cus['cusnum']}' {$sel}>{$cus['cusname']} {$cus['surname']}</option>";
        }
        $customers .= "</select>";
    }
    /* --- 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.";
    } 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>";
    # 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.";
    } else {
        $salesps = "<select name='salespn'>";
        while ($salesp = pg_fetch_array($salespRslt)) {
            if ($salesp['salesp'] == $inv['salespn']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $salesps .= "<option value='{$salesp['salesp']}' {$sel}>{$salesp['salesp']}</option>";
        }
        $salesps .= "</select>";
    }
    # Keep the charge vat option stable
    if ($inv['chrgvat'] == "inc") {
        $chin = "checked=yes";
        $chex = "";
        $chno = "";
    } elseif ($inv['chrgvat'] == "exc") {
        $chin = "";
        $chex = "checked=yes";
        $chno = "";
    } else {
        $chin = "";
        $chex = "";
        $chno = "checked=yes";
    }
    # format date
    list($oyear, $omon, $oday) = explode("-", $inv['odate']);
    /* --- 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>SERIAL NO.</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>AMOUNT</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 invoice
    db_connect();
    $sql = "SELECT * FROM pinv_items  WHERE invid = '{$invid}' 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++;
            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.");
            $Accounts = "\n\t\t\t\t\t\t\t<select name='accounts[]'>\n\t\t\t\t\t\t\t\t<option value='0'>Select Account</option>";
            while ($ad = pg_fetch_array($Ri)) {
                if ($ad['accid'] == $stkd['account']) {
                    $sel = "selected";
                } else {
                    $sel = "";
                }
                $Accounts .= "<option value='{$ad['accid']}' {$sel}>{$ad['accname']}</option>";
            }
            $Accounts .= "</select>";
            $sernos = "\n\t\t\t\t<input type='hidden' name='sernos_ss[]' value='{$stkd['ss']}'>\n\t\t\t\t<input type='hidden' name='sernos[]' value='{$stkd['serno']}'>";
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'>";
            $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\t\t\t<select name='vatcodes[]'>\n\t\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>";
            //print "fo";
            # Put in product
            $products .= "\n\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t<td colspan='2'>{$Accounts}<input type='hidden' name='whids[]' value='{$stkd['whid']}'></td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'>{$Vatcodes}</td>\n\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t\t<td><input type='text' size='20' name='descriptions[]' value='{$stkd['description']}'> {$sernos}</td>\n\t\t\t\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t\t\t\t<input type='hidden' name='disc[]' value='{$stkd['disc']}'>\n\t\t\t\t\t\t\t\t<input type='hidden' name='discp[]' value='{$stkd['discp']}'>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\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\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);
            if ($stk['units'] <= $stk['minlvl'] && $stk['minlvl'] != 0) {
                $error .= "<li class=err>{$stk['stkcod']} is below minimum level, please notify stock controller.</li>";
            }
            # Serial number
            if ($stk['serd'] == 'yes' && ($inv['serd'] == 'n' || $stkd["serno"] == "")) {
                $sers = ext_getavserials($stkd['stkid']);
                $sernos = "<select class='width : 15' name='sernos[]'>";
                foreach ($sers as $skey => $ser) {
                    $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
                }
                $sernos .= "</select>\n\t\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*' />";
            } else {
                $sernos = "\n\t\t\t\t\t<input type='hidden' name='sernos_ss[{$key}]' value='{$stkd['ss']}' />\n\t\t\t\t\t<input type='hidden' name='sernos[]' value='{$stkd['serno']}'>{$stkd['ss']}";
            }
            # Input qty if not serialised
            $qtyin = "<input type='text' size='3' name='qtys[]' value='{$stkd['qty']}'>";
            if ($stk['serd'] == 'yes') {
                $qtyin = "<input type='hidden' size='3' name='qtys[]' value='{$stkd['qty']}'>{$stkd['qty']}";
            }
            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\t<select name='vatcodes[]'>\n\t\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>";
            if ($ped) {
                $editp = "<input type='text' size='8' name='unitcost[]' value='{$stkd['unitcost']}'>";
            } else {
                $editp = "<input type='hidden' size='8' name='unitcost[]' value='{$stkd['unitcost']}'>{$stkd['unitcost']}";
            }
            # put in product
            $products .= "\n\t\t\t\t\t\t\t<input type='hidden' name='accounts[]' value='0'>\n\t\t\t\t\t\t\t<input type='hidden' name='descriptions[]' value=''>\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[]' value='{$stkd['whid']}'>{$wh['whname']}</td>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='stkids[]' value='{$stkd['stkid']}'><a href='#bottom' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>{$stk['stkcod']}</a></td>\n\t\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t\t<td>{$sernos}</td>\n\t\t\t\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t\t\t\t<td>{$editp}</td>\n\t\t\t\t\t\t\t\t<input type='hidden' size='4' name='disc[]' value='{$stkd['disc']}'>\n\t\t\t\t\t\t\t\t<input type='hidden' size='4' name='discp[]' value='{$stkd['discp']}' maxlength=5>\n\t\t\t\t\t\t\t\t<td><input type='hidden' name='amt[]' value='{$stkd['amt']}'> " . CUR . " {$stkd['amt']}</td>\n\t\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\t</tr>";
            $key++;
        }
    }
    # Look above(remprod keys)
    $keyy = $key;
    # Look above(if i = 0 then there are no products)
    if ($i == 0) {
        $done = "";
    } else {
        $SCROLL = "yes";
    }
    # 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);
                if ($stk['serd'] == 'yes') {
                    $sers = ext_getavserials($stkidss[$key]);
                    $sernos = "<select class='width : 15'name='sernos[]' onChange='javascript:document.form.submit();'>";
                    foreach ($sers as $skey => $ser) {
                        $sernos .= "<option value='{$ser['serno']}'>{$ser['serno']}</option>";
                    }
                    $sernos .= "</select>\n\t\t\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value='*_*_*CUBIT_SERIAL_SELECT_BOX*_*_*' />";
                } else {
                    $sernos = "\n\t\t\t\t\t\t\t<input type='hidden' name='sernos[]' value=''>\n\t\t\t\t\t\t\t<input type='hidden' name='sernos_ss[]' value=''>";
                }
                /* -- 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]);
                # Input qty if not serialised
                $qtyin = "<input type=text size=3 name=qtys[] value='{$qtyss[$key]}'>";
                if ($stk['serd'] == 'yes') {
                    $qtyin = "<input type=hidden size=3 name=qtys[] value='{$qtyss[$key]}'>{$qtyss[$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\t\t\t<select name='vatcodes[]'>\n\t\t\t\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\t\t\t<input type='hidden' name='accounts[]' value='0'>\n\t\t\t\t\t\t\t\t<input type='hidden' name='descriptions[]' value=''>\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='#bottom' 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>{$sernos}</td>\n\t\t\t\t\t\t\t\t\t<td>" . extlib_rstr($stk['stkdes'], 30) . "</td>\n\t\t\t\t\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t\t\t\t\t<td><input type='hidden' size='8' name='unitcost[]'  value='{$stk['selamt']}'>{$stk['selamt']}</td>\n\t\t\t\t\t\t\t\t\t<input type='hidden' size='4' name='disc[]' value='{$discs[$key]}'>\n\t\t\t\t\t\t\t\t\t<input type='hidden' size='4' name='discp[]' value='{$discps[$key]}' maxlength='5'>\n\t\t\t\t\t\t\t\t\t<td><input type='hidden' name='amt[]' value='{$amt[$key]}'> " . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t\t\t\t\t</tr>";
                $keyy++;
            } elseif (isset($accountss[$key]) && $accountss[$key] != "0") {
                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=qtemp value='$qtyss[$key]'>";
                $qtyin = "<input type='text' size='3' name='qtys[]' value='{$qtyss[$key]}'>";
                # Check permissions
                $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\t\t\t<select name='vatcodes[]'>\n\t\t\t\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>";
                $viewcost = sprint($viewcost);
                $amt[$key] = sprint($amt[$key]);
                # 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 colspan='2'>{$ad['accname']}<input type='hidden' name='accounts[]' value='{$accountss[$key]}'><input type='hidden' name='whids[]' value='0'></td>\n\t\t\t\t\t\t\t\t\t<td>{$Vatcodes}<input type='hidden' name='stkids[]' value='0'></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='20' name='descriptions[]' value='{$descriptionss[$key]}'></td>\n\t\t\t\t\t\t\t\t\t<td>{$qtyin}</td>\n\t\t\t\t\t\t\t\t\t<td>{$viewcost}</td>\n\t\t\t\t\t\t\t\t\t<input type='hidden' name='disc[]' value='0'><input type='hidden' name='discp[]' value='0'>\n\t\t\t\t\t\t\t\t\t<td><input type='hidden' name='amt[]' value='{$amt[$key]}'> " . CUR . " {$amt[$key]}</td>\n\t\t\t\t\t\t\t\t\t<td><input type='checkbox' name='remprod[]' value='{$keyy}'></td>\n\t\t\t\t\t\t\t\t</tr>";
                $keyy++;
            } else {
                if (!isset($diffwhBtn)) {
                    # skip if not selected
                    if ($whid == "-S") {
                        continue;
                    }
                    if (!isset($addnon)) {
                        # 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 blocked = 'n' AND div = '" . USER_DIV . "' {$fil} 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.";
                            continue;
                        }
                        $stks = "<select class='width : 15'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']} (" . ($stk['units'] - $stk['alloc']) . ")</option>";
                        }
                        $stks .= "</select> ";
                        # put in drop down and warehouse
                        $products .= "\n\t\t\t\t\t\t\t\t\t\t<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t\t\t\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>\n\t\t\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\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\t<td>{$stks}</td>\n\t\t\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t\t\t<td> </td>\n\t\t\t\t\t\t\t\t\t\t\t<td> </td>\n\t\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\t<td> </td>\n\t\t\t\t\t\t\t\t\t\t\t<input type='hidden' size='4' name='discs[]' value='0'>\n\t\t\t\t\t\t\t\t\t\t\t<input type='hidden' size='4' name='discps[]' value='0' maxlength='5'>\n\t\t\t\t\t\t\t\t\t\t\t<td><input type='hidden' name='amts[]' value='0.00'>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t\t\t\t</tr>";
                    } 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.");
                        $Accounts = "\n\t\t\t\t\t\t\t\t\t\t<select name='accountss[]' onChange='javascript:document.form.submit();'>\n\t\t\t\t\t\t\t\t\t\t\t<option value='0'>Select Account</option>";
                        while ($ad = pg_fetch_array($Ri)) {
                            $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 = "<select name=vatcodess[]>\n\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\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t\t\t<td colspan='2'>{$Accounts}<input type='hidden' name='whidss[]' value='1'></td>\n\t\t\t\t\t\t\t\t\t\t\t<inpu type='hidden' name='stkidss[]' value=''>\n\t\t\t\t\t\t\t\t\t\t\t<td>{$Vatcodes}</td>\n\t\t\t\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t\t\t\t\t<td><input type='text' size='20' name='descriptionss[]'></td>\n\t\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\t<td><input type='text' name='unitcosts[]' size='7'></td>\n\t\t\t\t\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t\t\t\t\t<input type='hidden' name='discs[]' value='0'>\n\t\t\t\t\t\t\t\t\t\t\t<input type='hidden' name='discps[]' value='0' >\n\t\t\t\t\t\t\t\t\t\t</tr>";
                    }
                }
            }
        }
    } else {
        if (!isset($diffwhBtn)) {
            # 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) && $wtd != 0) {
                    $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 blocked = 'n' 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 store.</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']} (" . ($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<input type='hidden' name='accountss[]' value='0'>\n\t\t\t\t\t\t\t\t\t<input type='hidden' name='descriptionss[]' value=''>\n\t\t\t\t\t\t\t\t\t<input type='hidden' name='vatcodess[]' value=''>\n\t\t\t\t\t \t\t\t\t<td>\n\t\t\t\t\t \t\t\t\t\t<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> </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<input type='hidden' size='4' name='discs[]' value='0'>\n\t\t\t\t\t \t\t\t\t\t<input type='hidden' size='4' name='discps[]' value='0' maxlength='5'>\n\t\t\t\t\t \t\t\t\t\t<td>" . 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</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> </td>\n\t\t\t\t\t\t\t\t\t<input type='hidden' size='4' name='discs[]' value='0'>\n\t\t\t\t\t\t\t\t\t<input type='hidden' size='4' name='discps[]' value='0' maxlength='5'>\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</tr>";
            }
        }
    }
    /* -- start Listeners -- */
    if (isset($diffwhBtn)) {
        $products .= "\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>{$whs}</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<input type='hidden' size='4' name='discs[]' value='0'>\n\t\t\t\t\t\t\t<input type='hidden' size='4' name='discps[]' value='0' maxlength='5'>\n\t\t\t\t\t\t\t<td>" . CUR . " 0.00</td>\n\t\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t</tr>";
    }
    /* -- End Listeners -- */
    $products .= "</table>";
    /* --- End Products Display --- */
    /* --- Start Some calculations --- */
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    if ($inv['traddisc'] > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * ($SUBTOT + $inv['delchrg']));
    } else {
        $traddiscm = "0.00";
    }
    $VATP = TAX_VAT;
    # Calculate subtotal
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    if (!isset($done)) {
        $done = "";
    }
    /* --- End Some calculations --- */
    if ($inv['terms'] == 1) {
        $tc1 = "";
        $tc2 = "checked";
    } else {
        $tc1 = "checked";
        $tc2 = "";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM settings WHERE constant='PSALES'";
    $Ri = db_exec($Sl) or errDie("Unable to get settings.");
    $data = pg_fetch_array($Ri);
    if ($data['value'] == "Yes") {
        $sc = "checked";
    } else {
        $sc = "";
    }
    $sales = "<td>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<td>{$salesps}</td>\n\t\t\t\t<td>Print</td>\n\t\t\t\t<td><input type='checkbox' name='printsales' {$sc}></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</td>";
    # Query server for depts
    db_conn("exten");
    $sql = "SELECT * FROM departments WHERE div = '" . USER_DIV . "' ORDER BY deptname ASC";
    $deptRslt = db_exec($sql) or errDie("Unable to view customers");
    if (pg_numrows($deptRslt) < 1) {
        return "<li class='err'>There are no Departments found in Cubit.</li>";
    } else {
        $depts = "<select name='deptid'>";
        while ($dept = pg_fetch_array($deptRslt)) {
            if ($dept['deptid'] == $inv['deptid']) {
                $sel = "selected";
            } else {
                $sel = "";
            }
            $depts .= "<option value='{$dept['deptid']}' {$sel}>{$dept['deptname']}</option>";
        }
        $depts .= "</select>";
    }
    db_conn('cubit');
    $Sl = "SELECT * FROM users WHERE username='******'";
    $Ri = db_exec($Sl);
    $data = pg_fetch_array($Ri);
    if ($data['help'] != "S") {
        $save = "|<input type=submit name='saveBtn' value='Save'>";
    } else {
        $save = "";
    }
    if ($inv['rounding'] > 0) {
        $due = sprint($inv['total'] - $inv['rounding']);
        $rd = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Rounding</td>\n\t\t\t\t\t<td align='right'>R {$inv['rounding']}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<th>Amount Due</th>\n\t\t\t\t\t<td align='right'>R {$due}</td>\n\t\t\t\t</tr>";
    } else {
        $rd = "";
    }
    $inv['delvat'] += 0;
    if ($inv['delvat'] == 0) {
        $Sl = "SELECT * FROM vatcodes WHERE del='Yes'";
        $Ri = db_exec($Sl) or errDie("Unable to get data.");
        $vd = pg_fetch_array($Ri);
        $inv['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 = "<input type=hidden name=delvat value=0>";
    // 	while($vd=pg_fetch_array($Ri)) {
    // 		if($vd['id']==$inv['delvat']) {
    // 			$sel="selected";
    // 		} else {
    // 			$sel="";
    // 		}
    // 		$Vatcodes.="<option value='$vd[id]' $sel>$vd[code]</option>";
    // 	}
    //
    // 	$Vatcodes.="</select>";
    if ($inv['cusnum'] == 0) {
        $cd = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer</td>\n\t\t\t\t\t<td valign='center'><input type='text' size='20' name='client' value='{$client}'></td>\n\t\t\t\t</tr>";
        $pc = "<input type='hidden' name='pcredit' value='0'>";
    } else {
        $cd = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td valign='top'>Customer Address</td>\n\t\t\t\t\t<td valign='center'>" . nl2br($cust['addr1']) . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Customer VAT Number</td>\n\t\t\t\t\t<td>{$cust['vatnum']}</td>\n\t\t\t\t</tr>";
        $pc = "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Amount On Credit</td>\n\t\t\t\t\t<td><input size='12' type='text' name='pcredit' value='{$inv['pcredit']}'></td>\n\t\t\t\t</tr>";
    }
    $sales = USER_NAME;
    if ($inv['pcash'] == 0) {
        $inv['pcash'] = "";
    }
    if ($inv['pcheque'] == 0) {
        $inv['pcheque'] = "";
    }
    if ($inv['pcc'] == 0) {
        $inv['pcc'] = "";
    }
    /* -- Final Layout -- */
    $details = "\n\t\t\t\t\t<center>\n\t\t\t\t\t<h3>Speed POS</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='invid' value='{$invid}'>\n\t\t\t\t\t\t<input type='hidden' name='stkerr' value='{$stkerr}'>\n\t\t\t\t\t\t<input type='hidden' name='user' value='" . USER_NAME . "'>\n\t\t\t\t\t\t<input type='hidden' name='salespn' value='" . USER_ID . "'>\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'> Customer 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'>{$depts}</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>Customer</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$customers}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t{$cd}\n\t\t\t\t\t\t\t\t\t<input type='hidden' size='10' name='cordno' value='{$inv['cordno']}'>\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'>Point of Sale</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>Barcode</td>\n\t\t\t\t\t\t\t\t\t\t<td><input type='text' size='13' name='bar' value=''></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<th colspan='2'>Search</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>By Stock Code</td>\n\t\t\t\t\t\t\t\t\t\t<td><input type='text' size='13' name='fcode' value='{$fcode}'><input type='submit' name='upBtn' value='Search'></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>By Stock Description</td>\n\t\t\t\t\t\t\t\t\t\t<td><input type='text' size='13' name='fdes' value='{$fdes}'><input type='submit' name='upBtn' value='Search'></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'> Invoice 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>Invoice No.</td>\n\t\t\t\t\t\t\t\t\t\t<td valign='center'>{$inv['invid']}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<input type='hidden' size='5' name='ordno' value='{$inv['ordno']}'>\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>Invoice Date</td>\n\t\t\t\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t\t\t\t<input type='hidden' size='2' name='oday' maxlength='2' value='{$oday}'>{$oday}-\n\t\t\t\t\t\t\t\t\t\t\t<input type='hidden' size='2' name='omon' maxlength='2' value='{$omon}'>{$omon}-\n\t\t\t\t\t\t\t\t\t\t\t<input type='hidden' size='4' name='oyear' maxlength='4' value='{$oyear}'>{$oyear}\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<input type='hidden' size='7' name='chrgvat' value='inc'>\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>Sales Person</td>\n\t\t\t\t\t\t\t\t\t\t<td>{$sales}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t<input type='hidden' size='5' name='traddisc' value='{$inv['traddisc']}'>\n\t\t\t\t\t\t\t\t\t<input type='hidden' size='7' name='delchrg' value='{$inv['delchrg']}'>{$Vatcodes}\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'>Payment 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>Amount Paid Cash</td>\n\t\t\t\t\t\t\t\t\t\t<td><input size='12' type='text' name='pcash' value='{$inv['pcash']}'></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>Amount Paid Cheque</td>\n\t\t\t\t\t\t\t\t\t\t<td><input size='12' type='text' name='pcheque' value='{$inv['pcheque']}'></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>Amount Paid Credit Card</td>\n\t\t\t\t\t\t\t\t\t\t<td><input size='12' type='text' name='pcc' value='{$inv['pcc']}'></td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t{$pc}\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>POS Manager Password</td>\n\t\t\t\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t\t\t\t<input type='password' size='10' name='pass' value='{$pass}'>\n\t\t\t\t\t\t\t\t\t\t\t<input type='submit' value='Continue'>\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><td colspan=2>{$done}</td></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 width='70%' valign='top'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t\t\t\t\t\t<input type='hidden' name='comm' value='{$inv['comm']}'>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t\t<td>{$error}</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 align='right' valign='top' width='30%'>\n\t\t\t\t\t\t\t\t<table " . TMPL_tblDflts . " width='100%'>\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><b>VAT @ {$VATP}%</b>\n\t\t\t\t\t\t\t\t\t</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 . " {$TOTAL}</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t\t{$rd}\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'></td>\n\t\t\t\t\t\t\t<td><input type='submit' name='upBtn' value='Update'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</table>\n\t\t\t\t\t<a name='bottom'>\n\t\t\t\t\t</form>\n\t\t\t\t\t</center>";
    return $details;
}