function view($frm)
{
    extract($_REQUEST);
    if ($msg = cForm::validateValue($supid, "num", 1, 10)) {
        return "<li class='err'>The supplier ID is invalid. {$msg}</li>\n\t\t\t<input type='button' onclick='window.history.back();' value='&laquo; Correction' />";
    }
    /* @var frm cForm */
    $frm->settitle("Supplier Pricelist");
    $frm->setkey("import");
    $frm->add_heading("Import New Pricelist");
    $frm->add_message("\n\t\t\t<li class='err'>Pricelists has to be in CSV format and to import them\n\t\t\t\tyou have to specify the order and format of the fields<br />\n\t\t\t\tby selecting what each of them are in the same order as they appear\n\t\t\t\tin the file. Only the stock code<br />\n\t\t\t\tand the price is needed, so for the other fields you simply\n\t\t\t\tselect the '-' options.\n\t\t\t</li>", "inst");
    $frm->add_message("\n\t\t\t<li class='err'>Note that the stock codes of the supplier should be added\n\t\t\t\tby editing the stock item and selecting the<br />\n\t\t\t\t'Add/Edit/Remove' button below the stock code input field.\n\t\t\t</li>", "suppstkcod");
    $frm->add_hidden("supid", $supid, "num");
    $frm->add_file("Pricelist", "supplist");
    $frm->add_checkbox("VAT Inclusive", "vatinc", true, true);
    $frm->add_heading("Comma Seperated Volume (CSV) Fields");
    $frm->add_layout("\n\t<tr %bgc>\n\t\t<td colspan='2' nowrap='t'>\n\t\t\t<strong>\n\t\t\t\t%fldonly ,\n\t\t\t\t%fldonly ,\n\t\t\t\t%fldonly ,\n\t\t\t\t%fldonly ,\n\t\t\t\t%fldonly ,\n\t\t\t\t%fldonly\n\t\t\t</strong>\n\t\t</td>\n\t</tr>");
    // field types
    $ft = array("ignore" => "-", "stkcod" => "Stock Code", "price" => "Price");
    $frm->add_select("", "fld[0]", "stkcod", $ft, "string", "5:6");
    $frm->add_select("", "fld[1]", "price", $ft, "string", "5:6");
    $frm->add_select("", "fld[2]", "ignore", $ft, "string", "5:6");
    $frm->add_select("", "fld[3]", "ignore", $ft, "string", "5:6");
    $frm->add_select("", "fld[4]", "ignore", $ft, "string", "5:6");
    $frm->add_select("", "fld[5]", "ignore", $ft, "string", "5:6");
    $frm->add_ctrlbtn("Import", "submit", "btn_import");
    $OUT = $frm->getfrm_input();
    /* supplier info */
    $suppinfo = qrySupplier($supid);
    $supcur = qryCurrency($suppinfo["fcid"]);
    $supcur = $supcur["symbol"];
    /* list current pricelist */
    $OUT .= "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<th>Stock Code</td>\n\t\t<th>Supplier Stock Code</th>\n\t\t<th>Current Supplier Price</th>\n\t\t<th>Current Selling Price</th>\n\t</tr>";
    $sql = "SELECT pli.*\n\t\t\tFROM exten.spricelist pl INNER JOIN exten.splist_prices pli\n\t\t\t\tON pl.listid=pli.listid\n\t\t\tWHERE pl.suppid='{$supid}'";
    $qry = new dbSql($sql);
    $qry->run();
    if ($qry->num_rows() <= 0) {
        $OUT .= "\n\t\t<tr bgcolor='" . bgcolorc(0) . "'>\n\t\t\t<td colspan='4'>No pricelist.</td>\n\t\t</tr>";
    }
    $i = 0;
    while ($row = $qry->fetch_array()) {
        if (empty($row["supstkcod"])) {
            $our_stkcod = "No supplier stock code";
            $our_price = "";
        } else {
            if (($stkid = suppStkid($supid, $row["supstkcod"])) === false) {
                $our_stkcod = "<li class='err'>No such stock item.\n\t\t\t\t<a href='stock-add.php?stkcod={$row['supstkcod']}&supid={$supid}&supstkcod={$row['supstkcod']}'>Add Stock</a> /\n\t\t\t\t<a href='stock-view.php'>Edit Stock</li>";
                $our_price = "";
            } else {
                $stkrow = qryStock($stkid, "stkcod, selamt");
                $our_stkcod = "<strong>{$stkrow['stkcod']}</strong>";
                $our_price = CUR . " " . sprint($stkrow["selamt"]);
            }
        }
        $OUT .= "\n\t\t<tr bgcolor='" . bgcolor($i) . "'>\n\t\t\t<td>{$our_stkcod}</td>\n\t\t\t<td>{$row['supstkcod']}</td>\n\t\t\t<td align='right'>{$supcur} " . sprint($row["price"]) . "</td>\n\t\t\t<td align='right'>{$our_price}</td>\n\t\t</tr>";
    }
    $OUT .= "\n\t</table>";
    return $OUT;
}
function approve()
{
    extract($_REQUEST);
    if (!isset($approve) || $approve != "i" && $approve != "a") {
        invalid_use("<li class='err'>Invalid action.<li>");
    }
    /* order info */
    $qry = new dbSelect("recvpurch", "trh", grp(m("where", wgrp(m("id", $id)))));
    $qry->run();
    if ($qry->num_rows() <= 0) {
        invalid_use("<li class='err'>Invalid Sales Order Id (TRHAPP).</li>");
    }
    $soi = $qry->fetch_array();
    /* customer info */
    $ci = qryCustomer($soi["custid"]);
    /* sales person name */
    if (empty($ci["sales_rep"])) {
        $speoples = qrySalesPerson();
        if ($speoples->num_rows() <= 0) {
            $salespn = "General";
        } else {
            $speoples->fetch_array();
            $salespn = $speoples->d["salesp"];
            $speoples->free();
        }
    } else {
        $m = qrySalesPerson($ci["sales_rep"]);
        $salespn = $m["salesp"];
    }
    /* currency info */
    $curinfo = qryCurrency($ci["fcid"]);
    $cols = grp(m("deptid", "{$ci['deptid']}"), m("cusnum", "{$ci['cusnum']}"), m("cordno", ""), m("ordno", ""), m("chrgvat", $soi["vatinc"] == "yes" ? "inc" : "no"), m("terms", "{$ci['credterm']}"), m("salespn", $salespn), m("odate", "{$soi['pdate']}"), m("accepted", "n"), m("comm", ""), m("done", "y"), m("username", USER_NAME), m("deptname", "{$ci['deptname']}"), m("cusacc", "{$ci['accno']}"), m("cusname", "{$ci['cusname']}"), m("surname", "{$ci['surname']}"), m("cusaddr", "{$ci['addr1']}"), m("cusordno", "{$soi['purnum']}"), m("cusvatno", "{$ci['vatnum']}"), m("prd", "0"), m("div", USER_DIV), m("disc", "0.00"), m("discp", "0.00"), m("delchrg", "{$soi['shipchrg']}"), m("subtot", "{$soi['subtot']}"), m("traddisc", "0.00"), m("balance", "{$soi['balance']}"), m("vat", "{$soi['vat']}"), m("total", "{$soi['total']}"), m("jobid", "0"), m("jobnum", "0"), m("dir", ""), m("location", ""), m("fcid", "{$ci['fcid']}"), m("currency", "{$curinfo['symbol']}"), m("xrate", "{$curinfo['rate']}"), m("fbalance", "0.00"), m("fsubtot", "0.00"), m("discount", "0.00"), m("delivery", "{$soi['shipchrg']}"), m("delvat", "{$soi['delvat']}"), m("display_costs", "yes"), m("proforma", "no"), m("pinvnum", "0"));
    $upd = new dbUpdate("sorders", "cubit", $cols);
    $upd->run(DB_INSERT);
    $sordid = $upd->lastvalue("sordid");
    /* items */
    $qry->reset();
    $qry->setTable("recvpurch_items");
    $qry->setOpt(grp(m("where", wgrp(m("recvpurch_id", $id)))));
    $qry->run();
    $upd->setTable("sorders_items");
    while ($row = $qry->fetch_array()) {
        if (empty($row["sup_stkcod"])) {
            invalid_use("Supplier stock codes not setup for customer. Order ignored.");
        }
        $stkinfo = qryStockC($row["sup_stkcod"]);
        $cols = grp(m("sordid", "{$sordid}"), m("whid", "{$stkinfo['whid']}"), m("stkid", "{$stkinfo['stkid']}"), m("qty", "{$row['qty']}"), m("div", USER_DIV), m("amt", "{$row['amt']}"), m("discp", "0.00"), m("disc", "0.00"), m("unitcost", "{$row['unitcost']}"), m("hidden", ""), m("funitcost", "0.00"), m("famt", "0.00"), m("pinv", "0.00"), m("vatcode", "{$stkinfo['vatcode']}"), m("description", "{$stkinfo['stkdes']}"), m("account", "0"));
        $upd->setOpt($cols);
        $upd->run(DB_INSERT);
    }
    /* set approve status */
    $upd->reset();
    $upd->setTable("recvpurch", "trh");
    $upd->setOpt(grp(m("approved", "{$approve}")), "id='{$id}'");
    $upd->run(DB_UPDATE);
    /* get customer trh config */
    $keyinfo = trhKeyCust($soi["custid"]);
    $email = $keyinfo["email"];
    /* send trh response message */
    $purinfo = array("purid" => $soi["purid"], "status" => $approve);
    $ret = send_trhmsg("cust", $soi["custid"], $email, "rsppur", $purinfo);
    if ($approve == "i") {
        header("Location: ../sorder-accept.php?sordid={$sordid}");
        exit;
    } else {
        $OUT = listorders("<li class='err'>Successfully approved sales order.</li>");
    }
    return $OUT;
}
function enter($err = "")
{
    extract($_REQUEST);
    $fields = grp(m("deptid", 0), m("accno", false), m("surname", ""), m("title", ""), m("location", ""), m("fcid", ""), m("category", 0), m("class", 0), m("init", ""), m("sales_rep", 0), m("paddr1", ""), m("addr1", ""), m("del_addr1", ""), m("comments", ""), m("vatnum", ""), m("contname", ""), m("bustel", ""), m("tel", ""), m("cellno", ""), m("fax", ""), m("email", ""), m("url", ""), m("pricelist", 0), m("traddisc", 0), m("setdisc", 0), m("chrgint", 0), m("overdue", 0), m("intrate", 0), m("o_year", date("Y")), m("o_month", date("m")), m("o_day", date("d")), m("credterm", 0), m("credlimit", ""), m("lead_source", 0), m("bankname", ""), m("branname", ""), m("brancode", ""), m("bankaccname", ""), m("bankaccno", ""), m("bankacctype", ""), m("team_id", 0), m("registration", ""));
    if (isset($cusnum)) {
        if ($cusnum == "-S") {
            return "<li class='err'>Invalid Customer</li><br><input type='button' value='[X] Close' onClick=\"window.close();\">";
        }
        $qry = new dbSelect("customers", "cubit", grp(m("where", "cusnum='{$cusnum}'")));
        $qry->run();
        if ($qry->num_rows() <= 0) {
            $OUT = "<li class='err'>Customer not found.</li>";
            return $OUT;
        }
        $c = $qry->fetch_array();
        $qry->free();
        /* split the date into the fields */
        list($c["o_year"], $c["o_month"], $c["o_day"]) = explode("-", $c["odate"]);
        foreach ($fields as $k => $v) {
            if (isset($c[$k])) {
                $fields[$k] = $c[$k];
            }
        }
        $cusid = "<input type='hidden' name='cusnum' value='{$cusnum}' />";
    } else {
        $cusid = "";
    }
    extract($fields, EXTR_SKIP);
    /* get next available account number */
    if ($accno === false) {
        $lastid = pglib_lastid("cubit.customers", "cusnum");
        $sql = "SELECT accno FROM cubit.customers WHERE cusnum = '{$lastid}' AND div = '" . USER_DIV . "'";
        $accRslt = db_exec($sql);
        if (pg_numrows($accRslt) < 1) {
            do {
                $lastid--;
                # get last account number
                $sql = "SELECT accno FROM cubit.customers WHERE cusnum = '{$lastid}' AND div = '" . USER_DIV . "'";
                $accRslt = db_exec($sql);
                if (pg_numrows($accRslt) < 1) {
                    $accno = "";
                    $naccno = "";
                } else {
                    $acc = pg_fetch_array($accRslt);
                    $accno = $acc['accno'];
                }
            } while (strlen($accno) < 1 && $lastid > 1);
        } else {
            $acc = pg_fetch_array($accRslt);
            $accno = $acc['accno'];
        }
        if (strlen($accno) > 0) {
            $num = preg_replace("/[^\\d]+/", "", $accno);
            $num++;
            $chars = preg_replace("/[\\d]/", "", $accno);
            $naccno = $chars . $num;
        } else {
            $naccno = 1;
        }
        $accno = $naccno;
    }
    /* customer categories */
    $qry = qryCategory();
    $cats = db_mksel($qry, "category", $category, "#catid", "#category");
    /* customer class */
    $qry = qryClass();
    $classlist = db_mksel($qry, "class", $class, "#clasid", "#classname");
    /* pricelists */
    $qry = qryPricelist();
    $pricelists = db_mksel($qry, "pricelist", $pricelist, "#listid", "#listname");
    /* customer departments */
    $qry = qryDepartment();
    $depts = db_mksel($qry, "deptid", $deptid, "#deptid", "#deptname");
    /* customer title */
    $get_titles = "SELECT title FROM titles ORDER BY title";
    $run_titles = db_exec($get_titles) or errDie("Unable to get title information.");
    if (pg_numrows($run_titles) < 1) {
        $titles = array("Mr" => "Mr", "Mrs" => "Mrs", "Miss" => "Miss");
    } else {
        $titles = array();
        while ($tarr = pg_fetch_array($run_titles)) {
            $titles[$tarr['title']] = $tarr['title'];
        }
    }
    $titles = extlib_cpsel("title", $titles, $title);
    /* credit terms */
    $qry = new dbSelect("ct", "exten", grp(m("where", "div='" . USER_DIV . "'")));
    $qry->run();
    while ($cd = $qry->fetch_array()) {
        $days[$cd['days']] = $cd['days'];
    }
    $credterms = extlib_cpsel("credterm", $days, $credterm);
    // unset so we can use same array
    unset($days);
    /* overdue periods */
    $qry = new dbSelect("od", "exten", grp(m("where", "div='" . USER_DIV . "'")));
    $qry->run();
    while ($cd = $qry->fetch_array()) {
        $days[$cd['days']] = $cd['days'];
    }
    $overdues = extlib_cpsel("overdue", $days, $overdue);
    /* customer is local/international */
    $locs = grp(m("loc", "Local"), m("int", "International"));
    $locsel = extlib_cpsel("location", $locs, $location);
    /* currency */
    $qry = qryCurrency();
    $currsel = db_mksel($qry, "fcid", $fcid, "#fcid", "#descrip");
    /* lead sources */
    $select_source = extlib_cpsel("lead_source", crm_get_leadsrc(-1), $lead_source);
    /* something from crm */
    if (isset($_GET["crm"])) {
        $ex = "<input type='hidden' name='crm' value='' />";
    } else {
        $ex = "";
    }
    /* sales rep selection */
    $qry = qrySalesPerson();
    $sales_reps = db_mksel($qry, "sales_rep", $sales_rep, "#salespid", "#salesp", "0:None");
    if (!isset($re)) {
        $re = "not";
    } else {
        $re = remval($re);
    }
    if (isset($cusnum)) {
        $bran = "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Branches</td>\n\t\t\t<td><input type='button' onClick=\"window.open('cust-branch-add.php?cusnum={$cusnum}','','width=380,height=300,status=1')\" value='Add Branch'><input type=button onClick=\"window.open('cust-branch-view.php?cusnum={$cusnum}','','width=500,height=400,status=1')\" value='View Branch'></td>\n\t\t</tr>";
    } else {
        $bran = "";
    }
    // Retrieve teams
    $sql = "SELECT * FROM crm.teams ORDER BY name ASC";
    $team_rslt = db_exec($sql) or errDie("Unable to retrieve teams.");
    $team_sel = "<select name='team_id'>";
    $team_sel .= "<option value='0'>[None]</option>";
    while ($team_data = pg_fetch_array($team_rslt)) {
        if ($team_id == $team_data["id"]) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $team_sel .= "<option value='{$team_data['id']}' {$sel}>{$team_data['name']}</option>";
    }
    $team_sel .= "</select>";
    // Layout
    $OUT = "\n\t<form action='" . SELF . "' method='post'>\n\t\t{$err}\n\t\t<input type='hidden' name='key' value='confirm' />\n\t\t<input type='hidden' name='re' value='{$re}' />\n\t\t{$ex}\n\t\t{$cusid}\n\t\t" . onthespot_passon() . "\n\t<table cellpadding='0' cellspacing='0'>\n\t\t<tr>\n\t\t\t<th colspan='2'>Add Customer : Customer Details</th>\n\t\t</tr>\n\t\t<tr valign='top'>\n\t\t\t<td>\n\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>" . REQ . "Department</td>\n\t\t\t\t\t<td>{$depts}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>" . REQ . "Acc No</td>\n\t\t\t\t\t<td><input type='text' size='20' name='accno' value='{$accno}' /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>" . REQ . "Company/Name</td>\n\t\t\t\t\t<td><input type='text' size='20' name='surname' value='{$surname}' /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>" . REQ . "Registration/ID</td>\n\t\t\t\t\t<td><input type='text' size='20' name='registration' value='{$registration}'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>" . REQ . "Title {$titles}</td>\n\t\t\t\t\t<td>Initials <input type='text' size='15' name='init' value='{$init}' /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>" . REQ . "Type</td>\n\t\t\t\t\t<td>{$locsel}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>" . REQ . "Currency</td>\n\t\t\t\t\t<td>{$currsel}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "' " . ass("Categories are used to group customers. For example: PTA,JHB,CT") . ">\n\t\t\t\t\t<td>" . REQ . "Category</td>\n\t\t\t\t\t<td>{$cats}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "' " . ass("Classifications are used to group customers. For example: Wholesale,Retail") . ">\n\t\t\t\t\t<td>" . REQ . "Classification</td>\n\t\t\t\t\t<td>{$classlist}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Link to Sales rep</td>\n\t\t\t\t\t<td>{$sales_reps}</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'>" . REQ . "Postal Address</td>\n\t\t\t\t\t<td valign='center'><textarea rows='4' cols='19' name='paddr1'>{$paddr1}</textarea></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'>\n\t\t\t\t\t\t" . REQ . "Physical Address<br>\n\t\t\t\t\t\t<font size='-2'>\n\t\t\t\t\t\t\t<input style='width: 11px; height: 11px;' type='checkbox' name='addr_same' " . (isset($addr_same) ? "checked='t'" : "") . " />\n\t\t\t\t\t\t\tSame As Postal Address\n\t\t\t\t\t\t</font>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td valign='center'><textarea rows='4' cols='19' name='addr1'>{$addr1}</textarea></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'><textarea rows='4' cols='19' name='del_addr1'>{$del_addr1}</textarea></td>\n\t\t\t\t</tr>\n\t\t\t\t{$bran}\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Team Permissions</td>\n\t\t\t\t\t<td>{$team_sel}</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'>Comments</td>\n\t\t\t\t\t<td valign='center'><textarea rows='4' cols='19' name='comments'>{$comments}</textarea></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</td>\n\t\t\t<td>\n\t\t\t<table " . TMPL_tblDflts . " width='100%'>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>" . REQ . "VAT Number</td>\n\t\t\t\t\t<td><input type='text' size='21' name='vatnum' value='{$vatnum}' /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>" . REQ . "Business Tel.</td>\n\t\t\t\t\t<td><input type='text' size='21' name='bustel' value='{$bustel}' /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Contact Name</td>\n\t\t\t\t\t<td><input type='text' size='21' name='contname' value='{$contname}' /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Home Tel.</td>\n\t\t\t\t\t<td><input type='text' size='21' name='tel' value='{$tel}' /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Cell No.</td>\n\t\t\t\t\t<td><input type='text' size='21' name='cellno' value='{$cellno}' /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Fax No.</td>\n\t\t\t\t\t<td><input type='text' size='21' name='fax' value='{$fax}' /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>E-mail</td>\n\t\t\t\t\t<td><input type='text' size='21' name='email' value='{$email}' /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Web Address</td>\n\t\t\t\t\t<td>http://<input type='text' size='30' name='url' value='{$url}' /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "' " . ass("When invoicing prices comes from the pricelist. Add more at stock settings.") . ">\n\t\t\t\t\t<td>" . REQ . "Price List</td>\n\t\t\t\t\t<td>{$pricelists}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td " . ass("This is the default discount on invoices, but can be changed per invoice") . ">Trade Discount &nbsp;<input type='text' size='6' name='traddisc' value='{$traddisc}' />%</td>\n\t\t\t\t\t<td>Settlement Discount <input type='text' size='7' name='setdisc' value='{$setdisc}' />%</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>" . REQ . "Charge Interest : Yes <input type='radio' name='chrgint' value='yes' " . ($chrgint == "yes" ? "checked='t'" : "") . " /> No<input type='radio' name='chrgint' value='no' " . ($chrgint != "yes" ? "checked='t'" : "") . " /></td>\n\t\t\t\t\t<td " . ass("Depending on interest settings, invoices older than this will get interest.") . ">Overdue &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{$overdues}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "' " . ass("Depending on interest settings, this is the interest this client will be charged.") . ">\n\t\t\t\t\t<td>Interest Rate</td>\n\t\t\t\t\t<td><input type='text' size='7' name='intrate' value='{$intrate}' />%</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Account Open Date</td>\n\t\t\t\t\t<td>" . mkDateSelect("o", $o_year, $o_month, $o_day) . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Credit Term &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{$credterms}</td>\n\t\t\t\t\t<td>Credit Limit: 0<input type='hidden' name='credlimit' value='0'/></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Lead Source</td>\n\t\t\t\t\t<td>{$select_source}</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr><Td><br></td></tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<th colspan='2'> Bank Details</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Bank </td>\n\t\t\t\t\t<td><input type='text' size='20' name='bankname' value='{$bankname}'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Branch</td>\n\t\t\t\t\t<td><input type='text' size='20' name='branname' value='{$branname}'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Branch Code</td>\n\t\t\t\t\t<td><input type='text' size='20' name='brancode' value='{$brancode}'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Account Name</td>\n\t\t\t\t\t<td><input type='text' size='20' name='bankaccname' value='{$bankaccname}'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Account Number</td>\n\t\t\t\t\t<td><input type='text' size='20' name='bankaccno' value='{$bankaccno}'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>Account Type</td>\n\t\t\t\t\t<td><input type='text' size='20' name='bankacctype' value='{$bankacctype}'></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='2' align='right'><input type='submit' value='Confirm &raquo;' /></td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t\t</form>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td align='center'>\n\t\t\t\t</table>" . mkQuickLinks(ql("customers-view.php", "View Customers"));
    return $OUT;
}
function enter($err = "")
{
    extract($_REQUEST);
    $fields = grp(m("deptid", 0), m("accno", false), m("surname", ""), m("title", ""), m("location", ""), m("fcid", ""), m("category", 0), m("class", 0), m("init", ""), m("sales_rep", 0), m("paddr1", ""), m("addr1", ""), m("del_addr1", ""), m("comments", ""), m("vatnum", ""), m("contname", ""), m("bustel", ""), m("tel", ""), m("cellno", ""), m("fax", ""), m("email", ""), m("url", ""), m("pricelist", 0), m("traddisc", 0), m("setdisc", 0), m("setdays", 1), m("chrgint", 0), m("overdue", 0), m("intrate", 0), m("o_year", date("Y")), m("o_month", date("m")), m("o_day", date("d")), m("credterm", 0), m("credlimit", ""), m("lead_source", 0), m("bankname", ""), m("branname", ""), m("brancode", ""), m("bankaccname", ""), m("bankaccno", ""), m("bankacctype", ""), m("team_id", 0), m("registration", ""), m("bankacct", ""), m("bankid", 0), m("blocked", "no"));
    if (isset($cusnum)) {
        if ($cusnum == "-S") {
            return "<li class='err'>Invalid Customer</li><br><input type='button' value='[X] Close' onClick=\"window.close();\">";
        }
        $qry = new dbSelect("customers", "cubit", grp(m("where", "cusnum='{$cusnum}'")));
        $qry->run();
        if ($qry->num_rows() <= 0) {
            $OUT = "<li class='err'>Customer not found.</li>";
            return $OUT;
        }
        $c = $qry->fetch_array();
        $qry->free();
        /* split the date into the fields */
        list($c["o_year"], $c["o_month"], $c["o_day"]) = explode("-", $c["odate"]);
        foreach ($fields as $k => $v) {
            if (isset($c[$k])) {
                $fields[$k] = $c[$k];
            }
        }
        $cusid = "<input type='hidden' name='cusnum' value='{$cusnum}' />";
    } else {
        $cusid = "";
    }
    extract($fields, EXTR_SKIP);
    /* get next available account number */
    if ($accno === false) {
        $lastid = pglib_lastid("cubit.customers", "cusnum");
        $sql = "SELECT accno FROM cubit.customers WHERE cusnum = '{$lastid}' AND div = '" . USER_DIV . "'";
        $accRslt = db_exec($sql);
        if (pg_numrows($accRslt) < 1) {
            do {
                $lastid--;
                # get last account number
                $sql = "SELECT accno FROM cubit.customers WHERE cusnum = '{$lastid}' AND div = '" . USER_DIV . "'";
                $accRslt = db_exec($sql);
                if (pg_numrows($accRslt) < 1) {
                    $accno = "";
                    $naccno = "";
                } else {
                    $acc = pg_fetch_array($accRslt);
                    $accno = $acc['accno'];
                }
            } while (strlen($accno) < 1 && $lastid > 1);
        } else {
            $acc = pg_fetch_array($accRslt);
            $accno = $acc['accno'];
        }
        if (strlen($accno) > 0) {
            $num = preg_replace("/[^\\d]+/", "", $accno);
            $num++;
            $chars = preg_replace("/[\\d]/", "", $accno);
            $naccno = $chars . $num;
        } else {
            $naccno = 1;
        }
        $accno = $naccno;
    }
    /* customer categories */
    $qry = qryCategory();
    $cats = db_mksel($qry, "category", $category, "#catid", "#category");
    /* customer class */
    $qry = qryClass();
    $classlist = db_mksel($qry, "class", $class, "#clasid", "#classname");
    /* pricelists */
    $qry = qryPricelist();
    $pricelists = db_mksel($qry, "pricelist", $pricelist, "#listid", "#listname");
    /* customer departments */
    $qry = qryDepartment();
    $depts = db_mksel($qry, "deptid", $deptid, "#deptid", "#deptname");
    /* customer title */
    $get_titles = "SELECT title FROM titles ORDER BY title";
    $run_titles = db_exec($get_titles) or errDie("Unable to get title information.");
    if (pg_numrows($run_titles) < 1) {
        $titles = array("Mr" => "Mr", "Mrs" => "Mrs", "Miss" => "Miss");
    } else {
        $titles = array();
        while ($tarr = pg_fetch_array($run_titles)) {
            $titles[$tarr['title']] = $tarr['title'];
        }
    }
    $titles = extlib_cpsel("title", $titles, $title);
    /* credit terms */
    $qry = new dbSelect("ct", "exten", grp(m("where", "div='" . USER_DIV . "'")));
    $qry->run();
    while ($cd = $qry->fetch_array()) {
        $days[$cd['days']] = $cd['days'];
    }
    $cred_days = array("0" => "0", "30" => "30", "60" => "60");
    $credterms = extlib_cpsel("credterm", $cred_days, $credterm);
    // unset so we can use same array
    unset($days);
    /* overdue periods */
    //	$qry = new dbSelect("od", "exten", grp(
    //		m("where", "div='".USER_DIV."'")
    //	));
    //	$qry->run();
    //	while ($cd = $qry->fetch_array()) {
    //		$days[$cd['days']] = $cd['days'];
    //	}
    //	$overdues = extlib_cpsel("overdue", $days, $overdue);
    /* customer is local/international */
    $locs = grp(m("loc", "Local"), m("int", "International"));
    $locsel = extlib_cpsel("location", $locs, $location);
    /* currency */
    $qry = qryCurrency();
    $currsel = db_mksel($qry, "fcid", $fcid, "#fcid", "#descrip");
    /* lead sources */
    $select_source = extlib_cpsel("lead_source", crm_get_leadsrc(-1), $lead_source);
    /* something from crm */
    if (isset($_GET["crm"])) {
        $ex = "<input type='hidden' name='crm' value='' />";
    } else {
        $ex = "";
    }
    /* sales rep selection */
    $qry = qrySalesPerson();
    $sales_reps = db_mksel($qry, "sales_rep", $sales_rep, "#salespid", "#salesp", "0:None");
    if (!isset($re)) {
        $re = "not";
    } else {
        $re = remval($re);
    }
    if (isset($cusnum)) {
        $bran = "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>Branches</td>\n\t\t\t\t<td><input type='button' onClick=\"window.open('cust-branch-add.php?cusnum={$cusnum}','','width=380,height=300,status=1')\" value='Add Branch'><input type=button onClick=\"window.open('cust-branch-view.php?cusnum={$cusnum}','','width=500,height=400,status=1')\" value='View Branch'></td>\n\t\t\t</tr>";
    } else {
        $bran = "";
    }
    // Retrieve teams
    $sql = "SELECT * FROM crm.teams ORDER BY name ASC";
    $team_rslt = db_exec($sql) or errDie("Unable to retrieve teams.");
    $team_sel = "<select name='team_id'>";
    $team_sel .= "<option value='0'>[None]</option>";
    while ($team_data = pg_fetch_array($team_rslt)) {
        if ($team_id == $team_data["id"]) {
            $sel = "selected";
        } else {
            $sel = "";
        }
        $team_sel .= "<option value='{$team_data['id']}' {$sel}>{$team_data['name']}</option>";
    }
    $team_sel .= "</select>";
    $get_accts = "SELECT * FROM bankacct ORDER BY accname";
    $run_accts = db_exec($get_accts) or errDie("Unable to get bank account information.");
    if (pg_numrows($run_accts) < 1) {
        $bankacct_drop = "";
    } else {
        $bankacct_drop = "<select name='bankid'>";
        while ($barr = pg_fetch_array($run_accts)) {
            if ($bankid == $barr['bankid']) {
                $bankacct_drop .= "<option value='{$barr['bankid']}' selected>({$barr['acctype']}) {$barr['accname']}</option>";
            } else {
                $bankacct_drop .= "<option value='{$barr['bankid']}'>({$barr['acctype']}) {$barr['accname']}</option>";
            }
        }
        $bankacct_drop .= "</select>";
    }
    $setdayssel1 = "";
    $setdayssel2 = "";
    $setdayssel3 = "";
    $setdayssel4 = "";
    $setdayssel5 = "";
    if (isset($setdays) and $setdays == "0") {
        $setdayssel1 = "selected";
    }
    if (isset($setdays) and $setdays == "1") {
        $setdayssel2 = "selected";
    }
    if (isset($setdays) and $setdays == "7") {
        $setdayssel3 = "selected";
    }
    if (isset($setdays) and $setdays == "15") {
        $setdayssel4 = "selected";
    }
    if (isset($setdays) and $setdays == "25") {
        $setdayssel5 = "selected";
    }
    //			<option $setdayssel1 value='0'>Last Day Of The Month</option>
    $setdays_drop = "\n\t\t<select name='setdays'>\n\t\t\t<option {$setdayssel2} value='1'>1st Day Of The Month</option>\n\t\t\t<option {$setdayssel3} value='7'>7th Of The Month</option>\n\t\t\t<option {$setdayssel4} value='15'>15th Of The Month</option>\n\t\t\t<option {$setdayssel5} value='25'>25th Of The Month</option>\n\t\t</select>";
    //Overdue &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$overdues
    $display_piclist = "";
    $display_iframe = "";
    #check if this cust has any pics ...
    if (isset($cusnum) and strlen($cusnum) > 0) {
        #editing customer ... show frame if we have pics
        $get_pics = "SELECT * FROM display_images WHERE type = 'customer' AND ident_id = '{$cusnum}' LIMIT 1";
        $run_pics = db_exec($get_pics) or errDie("Unable to get customer images information.");
        if (pg_numrows($run_pics) < 1) {
            #no pics for this customer
            $display_iframe = "";
        } else {
            #compile listing for customer
            $get_piclist = "SELECT * FROM display_images WHERE type = 'customer' AND ident_id = '{$cusnum}'";
            $run_piclist = db_exec($get_piclist) or errDie("Unable to get customer images information.");
            if (pg_numrows($run_piclist) < 1) {
                #wth .. pic went missing somewhere ...
                #so nothing
            } else {
                $display_piclist = "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='2'>\n\t\t\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<th>Picture Name</th>\n\t\t\t\t\t\t\t\t\t<th>View</th>\n\t\t\t\t\t\t\t\t\t<th>Remove</th>\n\t\t\t\t\t\t\t\t</tr>";
                while ($arr = pg_fetch_array($run_piclist)) {
                    $display_piclist .= "\n\t\t\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t\t\t<td>{$arr['image_name']}</td>\n\t\t\t\t\t\t\t\t\t<td><a target='iframe1' href='view_image.php?picid={$arr['id']}'>View</a></td>\n\t\t\t\t\t\t\t\t\t<td><input type='checkbox' name='rempicid[{$arr['id']}]' value='yes'></td>\n\t\t\t\t\t\t\t\t</tr>";
                    #at least 1 picture for this customer
                    $display_iframe = "<tr><td colspan='2'><iframe name='iframe1' width='200' height='260' scrolling='false' marginwidth='0' marginheight='0' frameborder='0' src='view_image.php?picid={$arr['id']}'></iframe></td></tr>";
                }
                $display_piclist .= "\n\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>";
            }
        }
    }
    $show_back_button = "";
    $show_next_button = "";
    $showbuttons = "";
    if (isset($cusnum) and strlen($cusnum) > 0 and $cusnum != 0) {
        db_connect();
        #get 1 lower cusnum
        $get_prev = "SELECT cusnum FROM customers WHERE cusnum < '{$cusnum}' ORDER BY cusnum DESC LIMIT 1";
        $run_prev = db_exec($get_prev) or errDie("Unable to get previous customer information.");
        if (pg_numrows($run_prev) > 0) {
            $back_cusnum = pg_fetch_result($run_prev, 0, 0);
            $show_back_button = "<input type='button' onClick=\"document.location='customers-new.php?cusnum={$back_cusnum}';\" value='View Previous Customer'>";
        }
        $get_next = "SELECT cusnum FROM customers WHERE cusnum > '{$cusnum}' ORDER BY cusnum ASC LIMIT 1";
        $run_next = db_exec($get_next) or errDie("Unable to get next customer information.");
        if (pg_numrows($run_next) > 0) {
            $next_cusnum = pg_fetch_result($run_next, 0, 0);
            $show_next_button = "<input type='button' onClick=\"document.location='customers-new.php?cusnum={$next_cusnum}';\" value='View Next Customer'>";
        }
        $showbuttons = "{$show_back_button} {$show_next_button} <br><br>";
        $showcontact = "<input type='button' onClick=\"popupSized('conper-add.php?type=cust&id={$cusnum}','Add Additional Contact','880','580')\" value='Add Additional Contact'>";
    }
    //http://127.0.0.1/cubit3.33/conper-add.php?type=cust&id=2
    // Layout
    $OUT = "\n\t\t{$showbuttons}\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t{$err}\n\t\t\t<input type='hidden' name='key' value='confirm' />\n\t\t\t<input type='hidden' name='re' value='{$re}' />\n\t\t\t<input type='hidden' name='blocked' value='{$blocked}' />\n\t\t\t{$ex}\n\t\t\t{$cusid}\n\t\t\t" . onthespot_passon() . "\n\t\t<table cellpadding='0' cellspacing='0'>\n\t\t\t<tr>\n\t\t\t\t<th colspan='2'>Add Customer : Customer Details</th>\n\t\t\t</tr>\n\t\t\t<tr valign='top'>\n\t\t\t\t<td>\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>" . REQ . "Department</td>\n\t\t\t\t\t\t<td>{$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>" . REQ . "Acc No</td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='accno' value='{$accno}' /></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>" . REQ . "Company/Name</td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='surname' value='{$surname}' /></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>" . REQ . "Registration/ID</td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='registration' value='{$registration}'></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>" . REQ . "Title {$titles}</td>\n\t\t\t\t\t\t<td>Initials <input type='text' size='15' name='init' value='{$init}' /></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>" . REQ . "Type</td>\n\t\t\t\t\t\t<td>{$locsel}</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>" . REQ . "Currency</td>\n\t\t\t\t\t\t<td>{$currsel}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "' " . ass("Categories are used to group customers. For example: PTA,JHB,CT") . ">\n\t\t\t\t\t\t<td>" . REQ . "Category</td>\n\t\t\t\t\t\t<td>{$cats}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "' " . ass("Classifications are used to group customers. For example: Wholesale,Retail") . ">\n\t\t\t\t\t\t<td>" . REQ . "Classification</td>\n\t\t\t\t\t\t<td>{$classlist}</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>Link to Sales rep</td>\n\t\t\t\t\t\t<td>{$sales_reps}</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'>" . REQ . " Postal Address</td>\n\t\t\t\t\t\t<td valign='center'><textarea rows='4' cols='19' name='paddr1'>{$paddr1}</textarea></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'>\n\t\t\t\t\t\t\t" . REQ . " Physical Address<br>\n\t\t\t\t\t\t\t<font size='-2'>\n\t\t\t\t\t\t\t\t<input style='width: 11px; height: 11px;' type='checkbox' name='addr_same' " . (isset($addr_same) ? "checked='t'" : "") . " />\n\t\t\t\t\t\t\t\tSame As Postal Address\n\t\t\t\t\t\t\t</font>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td valign='center'><textarea rows='4' cols='19' name='addr1'>{$addr1}</textarea></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'>Delivery Address</td>\n\t\t\t\t\t\t<td valign='center'><textarea rows='4' cols='19' name='del_addr1'>{$del_addr1}</textarea></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t{$bran}\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>Team Permissions</td>\n\t\t\t\t\t\t<td>{$team_sel}</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'>Comments</td>\n\t\t\t\t\t\t<td valign='center'><textarea rows='4' cols='19' name='comments'>{$comments}</textarea></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<th colspan='2'> Bank 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>Bank </td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='bankname' value='{$bankname}'></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>Branch</td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='branname' value='{$branname}'></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>Branch Code</td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='brancode' value='{$brancode}'></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>Account Name</td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='bankaccname' value='{$bankaccname}'></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>Account Number</td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='bankaccno' value='{$bankaccno}'></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>Account Type</td>\n\t\t\t\t\t\t<td><input type='text' size='20' name='bankacctype' value='{$bankacctype}'></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>Bank Account To Use</td>\n\t\t\t\t\t\t<td>{$bankacct_drop}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t\t<td>\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>" . REQ . "VAT Number</td>\n\t\t\t\t\t\t<td><input type='text' size='21' name='vatnum' value='{$vatnum}' /></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>" . REQ . "Business Tel.</td>\n\t\t\t\t\t\t<td><input type='text' size='21' name='bustel' value='{$bustel}' /></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>Contact Name</td>\n\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t<input type='text' size='21' name='contname' value='{$contname}' />\n\t\t\t\t\t\t\t{$showcontact}\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>Home Tel.</td>\n\t\t\t\t\t\t<td><input type='text' size='21' name='tel' value='{$tel}' /></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>Cell No.</td>\n\t\t\t\t\t\t<td><input type='text' size='21' name='cellno' value='{$cellno}' /></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>Fax No.</td>\n\t\t\t\t\t\t<td><input type='text' size='21' name='fax' value='{$fax}' /></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>E-mail</td>\n\t\t\t\t\t\t<td><input type='text' size='21' name='email' value='{$email}' /></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>Web Address</td>\n\t\t\t\t\t\t<td>http://<input type='text' size='30' name='url' value='{$url}' /></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr class='" . bg_class() . "' " . ass("When invoicing prices comes from the pricelist. Add more at stock settings.") . ">\n\t\t\t\t\t\t<td>" . REQ . "Price List</td>\n\t\t\t\t\t\t<td>{$pricelists}</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 " . ass("This is the default discount on invoices, but can be changed per invoice") . ">Trade Discount &nbsp;<input type='text' size='6' name='traddisc' value='{$traddisc}' />%</td>\n\t\t\t\t\t\t<td>Settlement Discount <input type='text' size='7' name='setdisc' value='{$setdisc}' />%</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>" . REQ . "Charge Interest : Yes <input type='radio' name='chrgint' value='yes' " . ($chrgint == "yes" ? "checked='t'" : "") . " /> No<input type='radio' name='chrgint' value='no' " . ($chrgint != "yes" ? "checked='t'" : "") . " /></td>\n\t\t\t\t\t\t<td>Statement Day {$setdays_drop}</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 " . ass("Depending on interest settings, invoices older than this will get interest.") . ">Interest Rate <input type='text' size='7' name='intrate' value='{$intrate}' />%</td>\n\t\t\t\t\t\t<td></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>Account Open Date</td>\n\t\t\t\t\t\t<td>" . mkDateSelect("o", $o_year, $o_month, $o_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>Default Credit Term &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{$credterms}</td>\n\t\t\t\t\t\t<td>Credit Limit <input type='text' size='7' name='credlimit' value='{$credlimit}'/></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>Lead Source</td>\n\t\t\t\t\t\t<td>{$select_source}</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{$display_iframe}\n\t\t\t\t\t{$display_piclist}\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td colspan='2' align='right'><input type='submit' value='Confirm &raquo;' /></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t</form>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align='center'>\n\t\t\t\t\t</table>" . mkQuickLinks(ql("customers-view.php", "View Customers"));
    return $OUT;
}
function printCust()
{
    global $_SESSION;
    extract($_REQUEST);
    if (!isset($action)) {
        $action = "listcust";
    }
    /* session var prefix */
    $SPRE = "custview_";
    /* max number of customers in list */
    if (isset($viewall_cust)) {
        $offset = 0;
        define("ACT_SHOW_LIMIT", 2147483647);
    } else {
        define("ACT_SHOW_LIMIT", SHOW_LIMIT);
    }
    if (!isset($fval) && isset($_SESSION["{$SPRE}fval"])) {
        $fval = $_SESSION["{$SPRE}fval"];
    }
    if (!isset($filter) && isset($_SESSION["{$SPRE}filter"])) {
        $filter = $_SESSION["{$SPRE}filter"];
    }
    if (!isset($all) && isset($_SESSION["{$SPRE}all"]) && !isset($filter) && !isset($fval)) {
        $all = $_SESSION["{$SPRE}all"];
    }
    if (isset($filter) && isset($fval) && !isset($all)) {
        if (strlen($filter) > 0) {
            if ($filter == "all") {
                $sqlfilter = " AND (lower(accno) LIKE lower('%{$fval}%') OR lower(surname) LIKE lower('%{$fval}%') OR lower(paddr1) LIKE lower('%{$fval}%') OR lower(addr1) LIKE lower('%{$fval}%') OR lower(del_addr1) LIKE lower('%{$fval}%') OR lower(bustel) LIKE lower('%{$fval}%') OR lower(email) LIKE lower('%{$fval}%') OR lower(vatnum) LIKE lower('%{$fval}%') OR lower(contname) LIKE lower('%{$fval}%') OR lower(tel) LIKE lower('%{$fval}%') OR lower(cellno) LIKE lower('%{$fval}%') OR lower(fax) LIKE lower('%{$fval}%') OR lower(url) LIKE lower('%{$fval}%') OR lower(comments) LIKE lower('%{$fval}%') OR lower(bankname) LIKE lower('%{$fval}%') OR lower(branname) LIKE lower('%{$fval}%') OR lower(brancode) LIKE lower('%{$fval}%') OR lower(bankaccno) LIKE lower('%{$fval}%') OR lower(bankaccname) LIKE lower('%{$fval}%') OR lower(bankacctype) LIKE lower('%{$fval}%'))";
            } else {
                $sqlfilter = " AND lower({$filter}) LIKE lower('%{$fval}%')";
            }
        } else {
            $sqlfilter = "";
        }
        if (isset($_SESSION["{$SPRE}all"])) {
            unset($_SESSION["{$SPRE}all"]);
        }
        $_SESSION["{$SPRE}fval"] = $fval;
        $_SESSION["{$SPRE}filter"] = $filter;
    } else {
        if (isset($_SESSION["{$SPRE}fval"])) {
            unset($_SESSION["{$SPRE}fval"]);
        }
        if (isset($_SESSION["{$SPRE}filter"])) {
            unset($_SESSION["{$SPRE}filter"]);
        }
        $filter = "";
        $fval = "";
        $_SESSION["{$SPRE}all"] = "true";
        $sqlfilter = "";
    }
    $filterarr = array("all" => "Detailed", "surname" => "Company/Name", "init" => "Initials", "accno" => "Account Number", "deptname" => "Department", "category" => "Category", "class" => "Classification");
    $filtersel = extlib_cpsel("filter", $filterarr, $filter, "onChange='applyFilter();'");
    if (isset($export)) {
        $pure = true;
    } else {
        $pure = false;
    }
    if (!$pure) {
        # Set up table to display in
        $printCust_begin = "\n\t    <h3>" . (isset($findcust) ? "Find" : "Current") . " Customers</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<input type='hidden' name='action' value='{$action}' />\n\t\t<tr>\n\t\t\t<th>.: Filter :.</th>\n\t\t\t<th colspan='2'>.: Search :.</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>{$filtersel}</td>\n\t\t\t<td><input type='text' size='20' id='fval' value='{$fval}'></td>\n\t\t\t<td align='center'><input type='button' value='Search' onClick='applyFilter();' /></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td align='center'><input type='button' name='all' value='View All' onClick='viewAll();' /></td>\n\t\t</tr>\n\t\t</table>\n\t\t<script>\n\t\t\t/* CRM CODE */\n\t\t\tfunction updateAccountInfo(id, name) {\n\t\t\t\twindow.opener.document.frm_con.accountname.value=name;\n\t\t\t\twindow.opener.document.frm_con.account_id.value=id;\n\t\t\t\twindow.opener.document.frm_con.account_type.value='Customer';\n\t\t\t\twindow.close();\n\t\t\t}\n\n\t\t\t/* AJAX filter code */\n\t\t\tfunction viewAll() {\n\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'all=t');\n\t\t\t}\n\n\t\t\tfunction applyFilter() {\n\t\t\t\tfilter = getObject('filter').value;\n\t\t\t\tfval = getObject('fval').value;\n\n\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'filter=' + filter + '&fval=' + fval);\n\t\t\t}\n\n\t\t\tfunction updateOffset(noffset, viewall) {\n\t\t\t\tif (viewall && !noffset) {\n\t\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'viewall_cust=t');\n\t\t\t\t} else {\n\t\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'offset=' + noffset);\n\t\t\t\t}\n\t\t\t}\n\t\t</script>\n\t\t<p>\n\t\t<div id='cust_list'>";
    } else {
        $printCust_begin = "";
    }
    /* FIND CUSTOMER START */
    if (!isset($findcust)) {
        $ajaxCust = "";
        if (!$pure) {
            $ajaxCust .= "\n\t\t<form action='statements-email.php' method='get'>\n\t\t<input type='hidden' name='key' value='confirm' />";
        }
        if (!isset($offset) && isset($_SESSION["{$SPRE}offset"])) {
            $offset = $_SESSION["{$SPRE}offset"];
        } else {
            if (!isset($offset)) {
                $offset = 0;
            }
        }
        $_SESSION["{$SPRE}offset"] = $offset;
        # connect to database
        db_connect();
        # counting the number of possible entries
        $sql = "SELECT * FROM customers\n    \t\tWHERE (div = '" . USER_DIV . "' OR  ddiv = '" . USER_DIV . "') {$sqlfilter}\n    \t\tORDER BY surname ASC";
        $rslt = db_exec($sql) or errDie("Error counting matching customers.");
        $custcount = pg_num_rows($rslt);
        # Query server
        $tot = 0;
        $totoverd = 0;
        $i = 0;
        if (!isset($ajaxCust)) {
            $ajaxCust = "";
        }
        /* view offsets */
        if ($offset > 0) {
            $poffset = $offset >= ACT_SHOW_LIMIT ? $offset - ACT_SHOW_LIMIT : 0;
            $os_prev = "<a class='nav' href='javascript: updateOffset(\"{$poffset}\");'>Previous</a>";
        } else {
            $os_prev = "&nbsp;";
        }
        if ($offset + ACT_SHOW_LIMIT > $custcount) {
            $os_next = "&nbsp;";
        } else {
            $noffset = $offset + ACT_SHOW_LIMIT;
            $os_next = "<a class='nav' href='javascript: updateOffset(\"{$noffset}\");'>Next</a>";
        }
        if ($os_next != "&nbsp;" || $os_prev != "&nbsp;") {
            $os_viewall = "| <a class='nav' href='javascript: updateOffset(false, true);'>View All</a>";
        } else {
            $os_viewall = "";
        }
        $ajaxCust .= "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<td colspan='20'>\n\t\t<table width='100%' border='0'>\n\t\t<tr>\n\t\t\t<td align='right' width='50%'>{$os_prev}</td>\n\t\t\t<td align='left' width='50%'>{$os_next} {$os_viewall}</td>\n\t\t</tr>\n\t\t</table>\n\t\t</td>\n\t</tr>\n\t<tr>\n\t\t<th>Acc no.</th>\n\t\t<th>Company/Name</th>\n\t\t<th>Tel</th>\n\t\t<th>Category</th>\n\t\t<th>Class</th>\n\t\t<th colspan='2'>Balance</th>\n\t\t<th>Overdue</th>\n\t\t" . ($pure ? "" : "<th colspan='11'>Options</th>") . "\n\t</tr>";
        /* query object for cashbook */
        $cashbook = new dbSelect("cashbook", "cubit");
        $custRslt = new dbSelect("customers", "cubit", grp(m("where", "(div ='" . USER_DIV . "' or ddiv='" . USER_DIV . "') {$sqlfilter}"), m("order", "surname ASC"), m("offset", $offset), m("limit", ACT_SHOW_LIMIT)));
        $custRslt->run();
        if ($custRslt->num_rows() < 1) {
            $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='20'><li>There are no Customers matching the criteria entered.</li></td>\n\t\t</tr>";
        } else {
            while ($cust = $custRslt->fetch_array()) {
                if (!user_in_team($cust["team_id"], USER_ID)) {
                    continue;
                }
                # Check type of age analisys
                if (div_isset("DEBT_AGE", "mon")) {
                    $overd = ageage($cust['cusnum'], $cust['overdue'] / 30 - 1, $cust['location']);
                } else {
                    $overd = age($cust['cusnum'], $cust['overdue'] - 1, $cust['location']);
                }
                if ($overd < 0) {
                    $overd = 0;
                }
                if ($overd > $cust['balance']) {
                    $overd = $cust['balance'];
                }
                if ($cust["location"] == "int") {
                    $cur = qryCurrency($cust["fcid"], "rate");
                    $rate = $cur["rate"];
                    if ($rate != 0) {
                        $totoverd += $overd * $rate;
                    } else {
                        $totoverd += $overd;
                    }
                } else {
                    $totoverd += $overd;
                }
                if (!$pure) {
                    /* check if customer may be removed */
                    $cashbook->setOpt(grp(m("where", "cusnum='{$cust['cusnum']}' AND banked='no' AND div='" . USER_DIV . "'")));
                    $cashbook->run();
                    if ($cashbook->num_rows() <= 0 && $cust['balance'] == 0) {
                        $rm = "<td><a href='cust-rem.php?cusnum={$cust['cusnum']}'>Remove</a></td>";
                    } else {
                        $rm = "<td></td>";
                    }
                }
                if (strlen(trim($cust['bustel'])) < 1) {
                    $cust['bustel'] = $cust['tel'];
                }
                $cust['balance'] = sprint($cust['balance']);
                if ($cust["location"] == "int") {
                    if ($rate != 0.0) {
                        $tot = $tot + $cust['fbalance'] * $rate;
                    } else {
                        $tot = $tot + $cust['balance'];
                    }
                } else {
                    $tot = $tot + $cust['balance'];
                }
                /* determine which template to use when printing customer invoices */
                if (templateScript("invoices") != "pdf/cust-pdf-print-invoices.php") {
                    $template = "pdf/pdf-tax-invoice.php?type=cusprintinvoices";
                } else {
                    $template = "pdf/pdf-tax-invoice.php?type=cusprintinvoices";
                }
                $inv = "";
                $inv = "\n\t\t\t<td>\n\t\t\t\t<a href='{$template}&cusnum={$cust['cusnum']}' target='_blank'>Print Invoices</a>\n\t\t\t</td>";
                # Locations drop down
                $locs = array("loc" => "Local", "int" => "International", "" => "");
                $loc = $locs[$cust['location']];
                $fbal = "--";
                $ocurr = CUR;
                $trans = "\n\t\t\t<td>\n\t\t\t\t<a href='core/cust-trans.php?cusnum={$cust['cusnum']}'>Transaction</a>\n\t\t\t</td>";
                if ($cust['location'] == 'int') {
                    $fbal = "{$cust['currency']} {$cust['fbalance']}";
                    $ocurr = CUR;
                    $trans = "\n\t\t\t\t<td>\n\t\t\t\t\t<a href='core/intcust-trans.php?cusnum={$cust['cusnum']}'>Transaction</a>\n\t\t\t\t</td>";
                    $receipt = "<a href='bank/bank-recpt-inv-int.php?cusid={$cust['cusnum']}&amp;cash=yes'>Add Receipt</a>";
                } else {
                    $receipt = "<a href='bank/bank-recpt-inv.php?cusnum={$cust['cusnum']}&amp;cash=yes'>Add Receipt</a>";
                }
                # alternate bgcolor
                $bgColor = bgcolor($i);
                $ajaxCust .= "<tr class='" . bg_class() . "'>";
                if ($action == "contact_acc") {
                    $updatelink = "javascript: updateAccountInfo(\"{$cust['cusnum']}\", \"{$cust['accno']}\");";
                    $ajaxCust .= "\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['surname']}</a></td>";
                } else {
                    if ($action == "select") {
                        $ajaxCust .= "\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['surname']}</a></td>";
                    } else {
                        $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['accno']}</td>\n\t\t\t\t\t<td>{$cust['surname']}</td>";
                    }
                }
                $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['bustel']}</td>\n\t\t\t\t\t<td>{$cust['catname']}</td>\n\t\t\t\t\t<td>{$cust['classname']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$cust['balance']}</td>\n\t\t\t\t\t<td align='center' nowrap>{$fbal}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$overd}</td>";
                if (!$pure) {
                    if ($action == "listcust") {
                        $ajaxCust .= "\n\t\t\t\t\t\t<td>{$receipt}</td>\n\t\t\t\t\t\t<td><a href='delnote-report.php?cusnum={$cust['cusnum']}'>Outstanding Stock</a></td>\n\t\t\t\t\t\t<td><a href='cust-det.php?cusnum={$cust['cusnum']}'>Details</a></td>\n\t\t\t\t\t\t<td><a href='customers-new.php?cusnum={$cust['cusnum']}'>Edit</a></td>\n\t\t\t\t\t\t<td><a href='#' onClick='openPrintWin(\"cust-stmnt.php?cusnum={$cust['cusnum']}\");'>Statement</a></td>\n\t\t\t\t\t\t{$trans} {$inv}";
                        if ($cust['blocked'] == 'yes') {
                            $ajaxCust .= "<td><a href='cust-unblock.php?cusnum={$cust['cusnum']}'>Unblock</a></td>";
                        } else {
                            $ajaxCust .= "<td><a href='cust-block.php?cusnum={$cust['cusnum']}'>Block</a></td>";
                        }
                        $ajaxCust .= "<td><a href='transheks/pricelist_send.php?cusnum={$cust['cusnum']}'>Send Pricelist</a></td>";
                        $ajaxCust .= "{$rm} <td><a href='conper-add.php?type=cust&amp;id={$cust['cusnum']}'>Add Contact</a></td>\n\t\t\t\t\t<td><input type='checkbox' name='cids[]' value='{$cust['cusnum']}' /></td>";
                    } else {
                        $ajaxCust .= "\n\t\t\t\t\t\t<td align=center>\n\t\t\t\t\t\t\t<a href='javascript: popupSized(\"cust-det.php?cusnum={$cust['cusnum']}\", \"custdetails\", 550, 400, \"\");'>Details</a>\n\t\t\t\t\t\t</td>";
                    }
                }
                $ajaxCust .= "</tr>";
            }
            $bgColor = bgcolor($i);
            $tot = sprint($tot);
            $totoverd = sprint($totoverd);
            $i--;
            $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='5'>Total Amount Outstanding, from {$i} " . ($i > 1 ? "clients" : "client") . "</td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$tot}</td>\n\t\t\t<td></td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$totoverd}</td>\n\t\t\t" . ($pure ? "" : "<td colspan='11' align='right'><input type='submit' value='Email Statements' /></td>") . "\n\t\t</tr>";
            if (!$pure) {
                $ajaxCust .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='20'>\n\t\t\t\t<table width='100%' border='0'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='right' width='50%'>{$os_prev}</td>\n\t\t\t\t\t<td align='left' width='50%'>{$os_next} {$os_viewall}</td>\n\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>";
            }
        }
        if ($pure) {
            $ajaxCust .= "</table>";
        } else {
            $ajaxCust .= "\n\t\t" . TBL_BR . "\n\t\t</table>\n\t\t</form>\n\t\t<form action='" . SELF . "' method='post'>\n\t\t<table>\n\t\t\t<input type='hidden' name='export' value='yes' />\n\t\t\t<input type='hidden' name='filter' value='{$filter}' />\n\t\t\t<input type='hidden' name='fval' value='{$fval}' />\n\t\t\t<tr>\n\t\t\t\t<td colspan='3'><input type='submit' value='Export to Spreadsheet' /></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>";
        }
        /* FIND CUSTOMER END */
    } else {
        $ajaxCust = "";
    }
    $printCust_end = "\n\t</div>";
    if (!$pure) {
        $printCust_end .= mkQuickLinks(ql("customers-new.php", "Add New Customer"));
    }
    if (AJAX) {
        return $ajaxCust;
    } else {
        return "{$printCust_begin}{$ajaxCust}{$printCust_end}";
    }
}
function printCust()
{
    global $_SESSION;
    extract($_REQUEST);
    if (!isset($action)) {
        $action = "listcust";
    }
    $sqlfilter = "";
    $printCust_begin = "<h2>View Customers</h2>";
    $ajaxCust = "";
    $ajaxCust .= "\n\t<form action='statements-email.php' method='get'>\n\t<input type='hidden' name='key' value='confirm' />";
    if (!isset($offset) && isset($_SESSION["offset"])) {
        $offset = $_SESSION["offset"];
    } else {
        if (!isset($offset)) {
            $offset = 0;
        }
    }
    $_SESSION["offset"] = $offset;
    # connect to database
    db_connect();
    # counting the number of possible entries
    $sql = "SELECT * FROM customers\n    \t\tWHERE (div = '" . USER_DIV . "' OR  ddiv = '" . USER_DIV . "') {$sqlfilter}\n    \t\tORDER BY surname ASC";
    $rslt = db_exec($sql) or errDie("Error counting matching customers.");
    $custcount = pg_num_rows($rslt);
    # Query server
    $tot = 0;
    $totoverd = 0;
    $i = 0;
    $ajaxCust .= "\n\t<table " . TMPL_tblDflts . ">\n\n\t<tr>\n\t\t<th>Acc no.</th>\n\t\t<th>Company/Name</th>\n\t\t<th>Tel</th>\n\t\t<th>Category</th>\n\t\t<th>Class</th>\n\t\t<th colspan='2'>Balance</th>\n\t\t<th>Overdue</th>\n\t</tr>";
    /* query object for cashbook */
    $cashbook = new dbSelect("cashbook", "cubit");
    $custRslt = new dbSelect("customers", "cubit", grp(m("where", "(div ='" . USER_DIV . "' or ddiv='" . USER_DIV . "') {$sqlfilter}"), m("order", "surname ASC"), m("offset", $offset), m("limit", 100)));
    $custRslt->run();
    if ($custRslt->num_rows() < 1) {
        $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='20'><li>There are no Customers matching the criteria entered.</li></td>\n\t\t</tr>";
    } else {
        while ($cust = $custRslt->fetch_array()) {
            if (!user_in_team($cust["team_id"], USER_ID)) {
                continue;
            }
            # Check type of age analisys
            if (div_isset("DEBT_AGE", "mon")) {
                $overd = ageage($cust['cusnum'], $cust['overdue'] / 30 - 1, $cust['location']);
            } else {
                $overd = age($cust['cusnum'], $cust['overdue'] - 1, $cust['location']);
            }
            if ($overd < 0) {
                $overd = 0;
            }
            if ($overd > $cust['balance']) {
                $overd = $cust['balance'];
            }
            if ($cust["location"] == "int") {
                $cur = qryCurrency($cust["fcid"], "rate");
                $rate = $cur["rate"];
                if ($rate != 0) {
                    $totoverd += $overd * $rate;
                } else {
                    $totoverd += $overd;
                }
            } else {
                $totoverd += $overd;
            }
            /* check if customer may be removed */
            $cashbook->setOpt(grp(m("where", "cusnum='{$cust['cusnum']}' AND banked='no' AND div='" . USER_DIV . "'")));
            $cashbook->run();
            if (strlen(trim($cust['bustel'])) < 1) {
                $cust['bustel'] = $cust['tel'];
            }
            $cust['balance'] = sprint($cust['balance']);
            if ($cust["location"] == "int") {
                if ($rate != 0.0) {
                    $tot = $tot + $cust['fbalance'] * $rate;
                } else {
                    $tot = $tot + $cust['balance'];
                }
            } else {
                $tot = $tot + $cust['balance'];
            }
            # Locations drop down
            $locs = array("loc" => "Local", "int" => "International", "" => "");
            $loc = $locs[$cust['location']];
            $fbal = "--";
            $ocurr = CUR;
            # alternate bgcolor
            $bgColor = bgcolor($i);
            $ajaxCust .= "<tr class='" . bg_class() . "'>";
            if ($action == "contact_acc") {
                $updatelink = "javascript: updateAccountInfo(\"{$cust['cusnum']}\", \"{$cust['accno']}\");";
                $ajaxCust .= "\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['surname']}</a></td>";
            } else {
                if ($action == "select") {
                    $ajaxCust .= "\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['surname']}</a></td>";
                } else {
                    $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['accno']}</td>\n\t\t\t\t\t<td>{$cust['surname']}</td>";
                }
            }
            $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['bustel']}</td>\n\t\t\t\t\t<td>{$cust['catname']}</td>\n\t\t\t\t\t<td>{$cust['classname']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$cust['balance']}</td>\n\t\t\t\t\t<td align='center' nowrap>{$fbal}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$overd}</td>";
            $ajaxCust .= "</tr>";
        }
        $bgColor = bgcolor($i);
        $tot = sprint($tot);
        $totoverd = sprint($totoverd);
        $i--;
        $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='5'>Total Amount Outstanding, from {$i} " . ($i > 1 ? "clients" : "client") . "</td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$tot}</td>\n\t\t\t<td></td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$totoverd}</td>\n\t\t</tr>";
    }
    $ajaxCust .= "\n\t\t" . TBL_BR . "\n\t\t</table>\n\t\t</form>";
    $printCust_end = "\n\t</div>";
    if (AJAX) {
        return $ajaxCust;
    } else {
        return "{$printCust_begin}{$ajaxCust}{$printCust_end}";
    }
}
function viewcash($_POST)
{
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($bankid, "num", 1, 30, "Invalid Bank Account.");
    $v->isOk($f_day, "num", 1, 2, "Invalid Day for the 'From' date.");
    $v->isOk($f_month, "num", 1, 2, "Invalid month for the 'From' date..");
    $v->isOk($f_year, "num", 1, 4, "Invalid year for the 'From' date..");
    $v->isOk($l_day, "num", 1, 2, "Invalid Day for the 'To' date.");
    $v->isOk($l_month, "num", 1, 2, "Invalid month for the 'To' date..");
    $v->isOk($l_year, "num", 1, 4, "Invalid year for the 'To' date..");
    # lets mix the date
    $from = mkdate($f_year, $f_month, $f_day);
    $to = mkdate($l_year, $l_month, $l_day);
    if ($v->isError()) {
        $err = $v->genErrors();
        return $err;
    }
    if (isset($export)) {
        $pure = true;
    } else {
        $pure = false;
    }
    $bank = qryBankAcct($bankid);
    $curdata = qryCurrency($bank["fcid"]);
    $fc = $curdata['symbol'];
    $s1 = "";
    $s2 = "";
    $s3 = "";
    $s4 = "";
    $s5 = "";
    if (isset($order)) {
        if ($order == "ORDER BY date ASC, cheqnum ASC") {
            $s2 = "selected";
        } elseif ($order == "ORDER BY date DESC, cheqnum DESC") {
            $s3 = "selected";
        } elseif ($order == "ORDER BY cheqnum ASC") {
            $s4 = "selected";
        } elseif ($order == "ORDER BY cheqnum DESC") {
            $s5 = "selected";
        } else {
            $s1 = "selected";
        }
    } else {
        $order = "ORDER BY date DESC, cheqnum ASC";
        $s1 = "selected";
    }
    // Set up table to display in
    # Receipts
    $OUTPUT = "\n\t\t<center>\n\t\t<table " . TMPL_tblDflts . " width='95%'>\n\t\t\t<tr>\n\t\t\t\t<td colspan='8' align='center'><h3>Cash Book<br><br>Account : {$bank['accname']} - {$bank['bankname']}<br>Period : {$from} to {$to}</h3></td>\n\t\t\t</tr>";
    if (!$pure) {
        $OUTPUT .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='8' align='center'>\n\t\t\t\t\t<form action='" . SELF . "' method='POST' name='form'>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t<input type='hidden' name='key' value='viewcash'>\n\t\t\t\t\t\t<input type='hidden' name='bankid' value='{$bankid}'>\n\t\t\t\t\t\t<input type='hidden' name='f_day' value='{$f_day}'>\n\t\t\t\t\t\t<input type='hidden' name='f_month' value='{$f_month}'>\n\t\t\t\t\t\t<input type='hidden' name='f_year' value='{$f_year}'>\n\t\t\t\t\t\t<input type='hidden' name='l_day' value='{$l_day}'>\n\t\t\t\t\t\t<input type='hidden' name='l_month' value='{$l_month}'>\n\t\t\t\t\t\t<input type='hidden' name='l_year' value='{$l_year}'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<th>Order By</th>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t<select name='order' onChange='javascript:document.form.submit();'>\n\t\t\t\t\t\t\t\t\t<option value='' disabled {$s1} >Select</option>\n\t\t\t\t\t\t\t\t\t<option value='ORDER BY date ASC, cheqnum ASC' {$s2}>Date, Cheque No. Ascending</option>\n\t\t\t\t\t\t\t\t\t<option value='ORDER BY date DESC, cheqnum DESC' {$s3}>Date, Cheque No. Descending</option>\n\t\t\t\t\t\t\t\t\t<option value='ORDER BY cheqnum ASC' {$s4}>Cheque No. Ascending</option>\n\t\t\t\t\t\t\t\t\t<option value='ORDER BY cheqnum DESC' {$s5}>Cheque No. Descending</option>\n\t\t\t\t\t\t\t\t</select>\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='center'><input type='submit' name='export' value='Export to Spreadsheet'></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t</form>\n\t\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>";
    }
    $OUTPUT .= "\n\t\t<tr>\n\t\t\t<td colspan='7'><h4>Receipts</h4></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th>Date</th>\n\t\t\t<th width='20%'>Bank Account Name</th>\n\t\t\t<th width='5%'>Cheque Number</th>\n\t\t\t<th width='15%'>Received From : </th>\n\t\t\t<th width='20%'>Description</th>\n\t\t\t<th>Reference</th>\n\t\t\t<th width='21%'>Ledger Account</th>\n\t\t\t<th width='23%'>Amount</th>\n\t\t</tr>";
    $rtotal = 0;
    // Received total amount
    // Connect to database
    db_Connect();
    $sql = "SELECT * FROM cashbook WHERE date >= '{$from}' AND date <= '{$to}' AND trantype='deposit' AND bankid='{$bankid}' AND div = '" . USER_DIV . "' {$order}";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank deposits details from database.", SELF);
    $numrows = pg_numrows($accntRslt);
    if ($numrows < 1) {
        $OUTPUT .= "<tr><td colspan='7' align='center'><li class='err'>There are no Payments/cheques received on the selected period.</td></tr>";
    } else {
        # display all bank Deposits
        for ($i = 0; $i < $numrows; $i++) {
            $accnt = pg_fetch_array($accntRslt, $i);
            if (strlen($accnt['accids']) > 0) {
                $acc['accname'] = "<a href=\"javascript: openSmallWindow('multi-acc-popup.php?cashid={$accnt['cashid']}&type=cash')\">Multiple Accounts</a>";
                $acc['accno'] = "";
            } else {
                # Get account name for the account involved
                $AccRslt = get("core", "accname, topacc, accnum", "accounts", "accid", $accnt['accinv']);
                $acc = pg_fetch_array($AccRslt);
                $acc['accno'] = "{$acc['topacc']}/{$acc['accnum']}";
            }
            # Get account name for bank account
            db_connect();
            $sql = "SELECT accname,btype FROM bankacct WHERE bankid= '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
            $bnameRslt = db_exec($sql);
            $bname = pg_fetch_array($bnameRslt);
            $rtotal += $accnt['amount'];
            // add to rtotal
            $accnt['amount'] = sprint($accnt['amount']);
            $accnt['date'] = ext_rdate($accnt['date']);
            if ($bname['btype'] != "loc") {
                $ex = "/ {$fc} {$accnt['famount']}";
            } else {
                $ex = "";
            }
            if (empty($accnt["multicusnum"])) {
                $from_disp = "{$accnt['name']}";
            } else {
                $from_disp = "<a href=\"javascript: openSmallWindow('multi-debtor-popup.php?cashid={$accnt['cashid']}&type=cash')\">Multiple Debtors</a>";
            }
            $OUTPUT .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$accnt['date']}</td>\n\t\t\t\t\t<td align='center'>{$bname['accname']}</td>\n\t\t\t\t\t<td align='center'>{$accnt['cheqnum']}</td>\n\t\t\t\t\t<td align='center'>{$from_disp}</td>\n\t\t\t\t\t<td>{$accnt['descript']}</td>\n\t\t\t\t\t<td>{$accnt['reference']}</td>\n\t\t\t\t\t<td>{$acc['accno']}  {$acc['accname']}</td>\n\t\t\t\t\t<td>" . CUR . " {$accnt['amount']} {$ex}</td>\n\t\t\t\t\t<td><a href='#' onClick=\"printer ('bank/bank-recpt-inv-print.php?recid={$accnt['cashid']}');\">Print</a></td>";
            if (!$pure && $accnt['banked'] == "no" && $accnt['opt'] != 'n') {
                $OUTPUT .= "<td><a href='../bank/cheq-return.php?cashid={$accnt['cashid']}'>Returned/Unpaid</td>";
                // $OUTPUT .= "<td><a href='../bank/cheq-cancel.php?cashid=$accnt[cashid]'>Cancel</td>";
            }
            $OUTPUT .= "</tr>";
        }
        # print the total
        $OUTPUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td colspan='6'><b>Total Receipts</b></td>\n\t\t\t\t<td><b>" . CUR . " " . sprintf("%01.2f", $rtotal) . "</b></td>\n\t\t\t</tr>";
    }
    # Seperate the tables with two rows
    $OUTPUT .= "<tr><td colspan='7'><br></td></tr><tr><td colspan='7'><br></td></tr>";
    # Payments
    $OUTPUT .= "\n\t\t<tr>\n\t\t\t<td colspan='7'><h4>Payments</h4></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<th>Date</th>\n\t\t\t<th>Bank Account Name</th>\n\t\t\t<th>Cheque Number</th>\n\t\t\t<th>Paid to: </th>\n\t\t\t<th>Description</th>\n\t\t\t<th>Reference</th>\n\t\t\t<th>Ledger Account</th>\n\t\t\t<th>Amount</th>\n\t\t</tr>";
    $ptotal = 0;
    // payments total
    // Connect to database
    db_Connect();
    $sql = "SELECT * FROM cashbook WHERE date >= '{$from}' AND date <= '{$to}' AND trantype='withdrawal' AND bankid='{$bankid}' AND div = '" . USER_DIV . "' {$order}";
    $accntRslt = db_exec($sql) or errDie("ERROR: Unable to retrieve bank deposits details from database.", SELF);
    if (pg_numrows($accntRslt) < 1) {
        $OUTPUT .= "<tr><td colspan='7' align='center'><li class='err'>There are no Payments made on the selected period.</td></tr>";
    } else {
        # Display all bank Deposits
        for ($i = 0; $accnt = pg_fetch_array($accntRslt); $i++) {
            # alternate bgcolor
            $bgColor = bgcolorc($i);
            if (strlen($accnt['accids']) > 0) {
                $acc['accname'] = "<a href=\"javascript: openSmallWindow('multi-acc-popup.php?cashid={$accnt['cashid']}&type=cash');\">Multiple Accounts</a>";
                $acc['accno'] = "";
            } else {
                # get account name for the account involved
                $AccRslt = get("core", "accname, topacc, accnum", "accounts", "accid", $accnt['accinv']);
                $acc = pg_fetch_array($AccRslt);
                $acc['accno'] = "{$acc['topacc']}/{$acc['accnum']}";
            }
            # get account name for bank account
            db_connect();
            $sql = "SELECT accname,btype FROM bankacct WHERE bankid= '{$accnt['bankid']}' AND div = '" . USER_DIV . "'";
            $bnameRslt = db_exec($sql);
            $bname = pg_fetch_array($bnameRslt);
            $ptotal += $accnt['amount'];
            //add to total
            $accnt['amount'] = sprint($accnt['amount']);
            $accnt['date'] = ext_rdate($accnt['date']);
            if ($bname['btype'] != "loc") {
                $ex = "/ {$fc} {$accnt['famount']}";
            } else {
                $ex = "";
            }
            $OUTPUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$accnt['date']}</td>\n\t\t\t\t<td align='center'>{$bname['accname']}</td>\n\t\t\t\t<td align='center'>{$accnt['cheqnum']}</td>\n\t\t\t\t<td align='center'>{$accnt['name']}</td>\n\t\t\t\t<td>{$accnt['descript']}</td>\n\t\t\t\t<td>{$accnt['reference']}</td>\n\t\t\t\t<td>{$acc['accno']}  {$acc['accname']}</td>\n\t\t\t\t<td>" . CUR . " {$accnt['amount']} {$ex}</td>";
            if (!$pure && $accnt['banked'] == "no" && $accnt['opt'] != 'n') {
                $OUTPUT .= "<td><a href='../bank/cheq-return.php?cashid={$accnt['cashid']}'>Returned/Unpaid</td>";
                // $OUTPUT .= "<td><a href='../bank/cheq-cancel.php?cashid=$accnt[cashid]'>Cancel</td>";
            }
            $OUTPUT .= "</tr>";
        }
        # print the total
        $OUTPUT .= "\n\t\t<tr class='" . bg_class() . "''>\n\t\t\t<td colspan='6'><b>Total Payments</b></td>\n\t\t\t<td><b>" . CUR . " " . sprintf("%01.2f", $ptotal) . "</b></td>\n\t\t</tr>";
    }
    if (!$pure) {
        $OUTPUT .= mkQuickLinks(ql("../core/acc-new2.php", "Add New Account"), ql("../core/acc-new2.php", "Add New Account (New Window)", true));
    }
    if (isset($export)) {
        $OUTPUT = clean_html($OUTPUT);
        require_lib("xls");
        StreamXLS("Cashbook", $OUTPUT);
    }
    return $OUTPUT;
}